BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-pre / src / platform / test / window.rs

window.rs

window.rs 18.6 KiB Download Raw
1use crate::{
2 AnyWindowHandle, Bounds, DevicePixels, DispatchEventResult, GpuSpecs, HeadlessAtlas, Pixels,
3 PlatformAtlas, PlatformDisplay, PlatformHeadlessRenderer, PlatformInput, PlatformInputHandler,
4 PlatformWindow, Point, PromptButton, RequestFrameOptions, Scene, Size, TestPlatform,
5 TextInputConfiguration, TextInputStateChange, WindowAppearance, WindowBackgroundAppearance,
6 WindowBounds, WindowControlArea, WindowInsets, WindowParams, WindowVisibility,
7};
8use gpui_util::ResultExt as _;
9#[cfg(any(test, feature = "test-support"))]
10use image::RgbaImage;
11use parking_lot::Mutex;
12use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
13use std::{
14 cell::Cell,
15 path::PathBuf,
16 rc::{Rc, Weak},
17 sync::{self, Arc},
18};
19
20pub(crate) struct TestWindowState {
21 pub(crate) bounds: Bounds<Pixels>,
22 pub(crate) handle: AnyWindowHandle,
23 display: Rc<dyn PlatformDisplay>,
24 pub(crate) title: Option<String>,
25 pub(crate) edited: bool,
26 pub(crate) document_path: Option<std::path::PathBuf>,
27 platform: Weak<TestPlatform>,
28 // TODO: Replace with `Rc`
29 sprite_atlas: Arc<dyn PlatformAtlas>,
30 renderer: Option<Box<dyn PlatformHeadlessRenderer>>,
31 pub(crate) should_close_handler: Option<Box<dyn FnMut() -> bool>>,
32 hit_test_window_control_callback: Option<Box<dyn FnMut() -> Option<WindowControlArea>>>,
33 input_callback: Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>,
34 active_status_change_callback: Option<Box<dyn FnMut(bool)>>,
35 visibility: WindowVisibility,
36 visibility_callback: Option<Box<dyn FnMut(WindowVisibility)>>,
37 hover_status_change_callback: Option<Box<dyn FnMut(bool)>>,
38 resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
39 visual_viewport: Option<Bounds<Pixels>>,
40 visual_viewport_callback: Option<Box<dyn FnMut()>>,
41 insets: WindowInsets,
42 insets_callback: Option<Box<dyn FnMut(WindowInsets)>>,
43 virtual_keyboard_requests: usize,
44 virtual_keyboard_dismissals: usize,
45 moved_callback: Option<Box<dyn FnMut()>>,
46 appearance_change_callback: Option<Box<dyn FnMut()>>,
47 request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
48 frame_wake_count: Rc<Cell<usize>>,
49 frame_scheduled: bool,
50 frame_callback_pending: bool,
51 input_handler: Option<PlatformInputHandler>,
52 text_input_configurations: Vec<TextInputConfiguration>,
53 text_input_state_changes: Vec<TextInputStateChange>,
54 is_fullscreen: bool,
55 scale_factor: f32,
56 appearance: WindowAppearance,
57 external_drag_files: Vec<(PathBuf, bool)>,
58 start_external_drag_result: bool,
59}
60
61#[derive(Clone)]
62pub struct TestWindow(pub(crate) Rc<Mutex<TestWindowState>>);
63
64// Test windows are not backed by a real platform window, so there is no raw
65// handle to report; `NotSupported` is `raw_window_handle`'s variant for exactly this.
66impl HasWindowHandle for TestWindow {
67 fn window_handle(
68 &self,
69 ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
70 Err(raw_window_handle::HandleError::NotSupported)
71 }
72}
73
74impl HasDisplayHandle for TestWindow {
75 fn display_handle(
76 &self,
77 ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
78 Err(raw_window_handle::HandleError::NotSupported)
79 }
80}
81
82impl TestWindow {
83 pub(crate) fn new(
84 handle: AnyWindowHandle,
85 params: WindowParams,
86 platform: Weak<TestPlatform>,
87 display: Rc<dyn PlatformDisplay>,
88 renderer: Option<Box<dyn PlatformHeadlessRenderer>>,
89 ) -> Self {
90 let sprite_atlas: Arc<dyn PlatformAtlas> = match &renderer {
91 Some(r) => r.sprite_atlas(),
92 None => Arc::new(HeadlessAtlas::default()),
93 };
94 Self(Rc::new(Mutex::new(TestWindowState {
95 bounds: params.bounds,
96 display,
97 platform,
98 handle,
99 sprite_atlas,
100 renderer,
101 title: Default::default(),
102 edited: false,
103 document_path: None,
104 should_close_handler: None,
105 hit_test_window_control_callback: None,
106 input_callback: None,
107 active_status_change_callback: None,
108 visibility: WindowVisibility::Visible,
109 visibility_callback: None,
110 hover_status_change_callback: None,
111 resize_callback: None,
112 visual_viewport: None,
113 visual_viewport_callback: None,
114 insets: WindowInsets::default(),
115 insets_callback: None,
116 virtual_keyboard_requests: 0,
117 virtual_keyboard_dismissals: 0,
118 moved_callback: None,
119 appearance_change_callback: None,
120 request_frame_callback: None,
121 frame_wake_count: Rc::new(Cell::new(0)),
122 frame_scheduled: false,
123 frame_callback_pending: false,
124 input_handler: None,
125 text_input_configurations: Vec::new(),
126 text_input_state_changes: Vec::new(),
127 is_fullscreen: false,
128 // Preserve the test platform's historical 2x default.
129 scale_factor: 2.0,
130 appearance: WindowAppearance::Light,
131 external_drag_files: Vec::new(),
132 start_external_drag_result: false,
133 })))
134 }
135 pub fn simulate_scheduled_frame(&self) -> bool {
136 let callback = {
137 let mut state = self.0.lock();
138 if !std::mem::take(&mut state.frame_scheduled) {
139 return false;
140 }
141 state.frame_callback_pending = false;
142 state.request_frame_callback.take()
143 };
144 let Some(mut callback) = callback else {
145 self.0.lock().frame_scheduled = true;
146 return false;
147 };
148
149 callback(RequestFrameOptions::default());
150 self.0.lock().request_frame_callback = Some(callback);
151 true
152 }
153
154 pub fn frame_scheduled(&self) -> bool {
155 self.0.lock().frame_scheduled
156 }
157
158 pub fn simulate_visibility_change(&self, visibility: WindowVisibility) {
159 let callback = {
160 let mut state = self.0.lock();
161 state.visibility = visibility;
162 state.visibility_callback.take()
163 };
164 if let Some(mut callback) = callback {
165 callback(visibility);
166 self.0.lock().visibility_callback = Some(callback);
167 }
168 }
169
170 pub fn simulate_visual_viewport_change(&self, bounds: Bounds<Pixels>) {
171 let callback = {
172 let mut state = self.0.lock();
173 state.visual_viewport = Some(bounds);
174 state.visual_viewport_callback.take()
175 };
176 if let Some(mut callback) = callback {
177 callback();
178 self.0.lock().visual_viewport_callback = Some(callback);
179 }
180 }
181
182 pub fn simulate_insets_change(&self, insets: WindowInsets) {
183 let callback = {
184 let mut state = self.0.lock();
185 state.insets = insets.clone();
186 state.insets_callback.take()
187 };
188 if let Some(mut callback) = callback {
189 callback(insets);
190 self.0.lock().insets_callback = Some(callback);
191 }
192 }
193
194 pub fn virtual_keyboard_requests(&self) -> usize {
195 self.0.lock().virtual_keyboard_requests
196 }
197
198 pub fn virtual_keyboard_dismissals(&self) -> usize {
199 self.0.lock().virtual_keyboard_dismissals
200 }
201
202 /// Every [`TextInputConfiguration`] forwarded to this window, in order.
203 pub fn text_input_configurations(&self) -> Vec<TextInputConfiguration> {
204 self.0.lock().text_input_configurations.clone()
205 }
206
207 pub fn text_input_state_changes(&self) -> Vec<TextInputStateChange> {
208 self.0.lock().text_input_state_changes.clone()
209 }
210
211 pub fn simulate_resize(&mut self, size: Size<Pixels>) {
212 let scale_factor = self.scale_factor();
213 let mut lock = self.0.lock();
214 // Always update bounds, even if no callback is registered
215 lock.bounds.size = size;
216 let Some(mut callback) = lock.resize_callback.take() else {
217 return;
218 };
219 drop(lock);
220 callback(size, scale_factor);
221 self.0.lock().resize_callback = Some(callback);
222 }
223
224 /// Simulates a display scale change through the resize callback, preserving logical bounds.
225 pub fn simulate_scale_factor_change(&mut self, scale_factor: f32) {
226 let size = {
227 let mut lock = self.0.lock();
228 lock.scale_factor = scale_factor;
229 lock.bounds.size
230 };
231 self.simulate_resize(size);
232 }
233
234 pub(crate) fn simulate_active_status_change(&self, active: bool) {
235 let mut lock = self.0.lock();
236 let Some(mut callback) = lock.active_status_change_callback.take() else {
237 return;
238 };
239 drop(lock);
240 callback(active);
241 self.0.lock().active_status_change_callback = Some(callback);
242 }
243
244 pub fn simulate_appearance_change(&self, appearance: WindowAppearance) {
245 let mut lock = self.0.lock();
246 lock.appearance = appearance;
247 let Some(mut callback) = lock.appearance_change_callback.take() else {
248 return;
249 };
250 drop(lock);
251 callback();
252 self.0.lock().appearance_change_callback = Some(callback);
253 }
254
255 /// Returns how many times this window's frame waker has been invoked.
256 pub fn frame_wake_count(&self) -> usize {
257 self.0.lock().frame_wake_count.get()
258 }
259
260 /// Delivers a frame request to the window, as the platform's frame source
261 /// would.
262 pub fn simulate_frame_request(&self, options: RequestFrameOptions) {
263 let mut lock = self.0.lock();
264 let Some(mut callback) = lock.request_frame_callback.take() else {
265 return;
266 };
267 drop(lock);
268 callback(options);
269 self.0.lock().request_frame_callback = Some(callback);
270 }
271
272 pub fn simulate_input(&mut self, event: PlatformInput) -> bool {
273 let mut lock = self.0.lock();
274 let Some(mut callback) = lock.input_callback.take() else {
275 return false;
276 };
277 drop(lock);
278 let result = callback(event);
279 self.0.lock().input_callback = Some(callback);
280 !result.propagate
281 }
282
283 pub fn external_drag_files(&self) -> Vec<(PathBuf, bool)> {
284 self.0.lock().external_drag_files.clone()
285 }
286
287 pub fn set_start_external_drag_result(&self, result: bool) {
288 self.0.lock().start_external_drag_result = result;
289 }
290}
291
292impl PlatformWindow for TestWindow {
293 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
294 let state = self.0.lock();
295 state
296 .visual_viewport
297 .unwrap_or_else(|| Bounds::new(Point::default(), state.bounds.size))
298 }
299
300 fn on_visual_viewport_changed(&self, callback: Box<dyn FnMut()>) {
301 self.0.lock().visual_viewport_callback = Some(callback);
302 }
303
304 fn insets(&self) -> WindowInsets {
305 self.0.lock().insets.clone()
306 }
307
308 fn on_insets_changed(&self, callback: Box<dyn FnMut(WindowInsets)>) {
309 self.0.lock().insets_callback = Some(callback);
310 }
311
312 fn show_soft_keyboard(&self) {
313 self.0.lock().virtual_keyboard_requests += 1;
314 }
315
316 fn hide_soft_keyboard(&self) {
317 self.0.lock().virtual_keyboard_dismissals += 1;
318 }
319
320 fn bounds(&self) -> Bounds<Pixels> {
321 self.0.lock().bounds
322 }
323
324 fn window_bounds(&self) -> WindowBounds {
325 WindowBounds::Windowed(self.bounds())
326 }
327
328 fn is_maximized(&self) -> bool {
329 false
330 }
331
332 fn content_size(&self) -> Size<Pixels> {
333 self.bounds().size
334 }
335
336 fn resize(&mut self, size: Size<Pixels>) {
337 let mut lock = self.0.lock();
338 lock.bounds.size = size;
339 }
340
341 fn scale_factor(&self) -> f32 {
342 self.0.lock().scale_factor
343 }
344
345 fn appearance(&self) -> WindowAppearance {
346 self.0.lock().appearance
347 }
348
349 fn display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
350 Some(self.0.lock().display.clone())
351 }
352
353 fn mouse_position(&self) -> Point<Pixels> {
354 Point::default()
355 }
356
357 fn modifiers(&self) -> crate::Modifiers {
358 crate::Modifiers::default()
359 }
360
361 fn capslock(&self) -> crate::Capslock {
362 crate::Capslock::default()
363 }
364
365 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
366 self.0.lock().input_handler = Some(input_handler);
367 }
368
369 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
370 self.0.lock().input_handler.take()
371 }
372
373 fn set_text_input_configuration(&mut self, configuration: TextInputConfiguration) {
374 self.0.lock().text_input_configurations.push(configuration);
375 }
376
377 fn text_input_state_changed(&self, change: TextInputStateChange) {
378 self.0.lock().text_input_state_changes.push(change);
379 }
380
381 fn prompt(
382 &self,
383 _level: crate::PromptLevel,
384 msg: &str,
385 detail: Option<&str>,
386 answers: &[PromptButton],
387 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
388 Some(
389 self.0
390 .lock()
391 .platform
392 .upgrade()
393 .expect("platform dropped")
394 .prompt(msg, detail, answers),
395 )
396 }
397
398 fn activate(&self) {
399 self.0
400 .lock()
401 .platform
402 .upgrade()
403 .unwrap()
404 .set_active_window(Some(self.clone()))
405 }
406
407 fn is_active(&self) -> bool {
408 false
409 }
410
411 fn visibility(&self) -> WindowVisibility {
412 self.0.lock().visibility
413 }
414
415 fn is_hovered(&self) -> bool {
416 false
417 }
418
419 fn background_appearance(&self) -> WindowBackgroundAppearance {
420 WindowBackgroundAppearance::Opaque
421 }
422
423 fn is_subpixel_rendering_supported(&self) -> bool {
424 false
425 }
426
427 fn set_title(&mut self, title: &str) {
428 self.0.lock().title = Some(title.to_owned());
429 }
430
431 fn set_app_id(&mut self, _app_id: &str) {}
432
433 fn set_background_appearance(&self, _background: WindowBackgroundAppearance) {}
434
435 fn set_edited(&mut self, edited: bool) {
436 self.0.lock().edited = edited;
437 }
438
439 fn set_document_path(&self, path: Option<&std::path::Path>) {
440 self.0.lock().document_path = path.map(|p| p.to_path_buf());
441 }
442
443 fn show_character_palette(&self) {
444 unimplemented!()
445 }
446
447 fn minimize(&self) {
448 unimplemented!()
449 }
450
451 fn zoom(&self) {
452 unimplemented!()
453 }
454
455 fn toggle_fullscreen(&self) {
456 let mut lock = self.0.lock();
457 lock.is_fullscreen = !lock.is_fullscreen;
458 }
459
460 fn is_fullscreen(&self) -> bool {
461 self.0.lock().is_fullscreen
462 }
463
464 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
465 // Tests can inspect wakes without delivering a frame synchronously.
466 let frame_wake_count = self.0.lock().frame_wake_count.clone();
467 #[cfg(feature = "bench-support")]
468 let window = Rc::downgrade(&self.0);
469 Some(Rc::new(move || {
470 frame_wake_count.set(frame_wake_count.get() + 1);
471 #[cfg(feature = "bench-support")]
472 if let Some(window) = window.upgrade() {
473 TestWindow(window).schedule_frame();
474 }
475 }))
476 }
477
478 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
479 self.0.lock().request_frame_callback = Some(callback);
480 }
481
482 fn schedule_frame(&self) {
483 let mut state = self.0.lock();
484 if !state.frame_callback_pending {
485 state.frame_scheduled = true;
486 }
487 }
488
489 fn on_input(&self, callback: Box<dyn FnMut(crate::PlatformInput) -> DispatchEventResult>) {
490 self.0.lock().input_callback = Some(callback)
491 }
492
493 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
494 self.0.lock().active_status_change_callback = Some(callback)
495 }
496
497 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
498 self.0.lock().visibility_callback = Some(callback);
499 }
500
501 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
502 self.0.lock().hover_status_change_callback = Some(callback)
503 }
504
505 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
506 self.0.lock().resize_callback = Some(callback)
507 }
508
509 fn on_moved(&self, callback: Box<dyn FnMut()>) {
510 self.0.lock().moved_callback = Some(callback)
511 }
512
513 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
514 self.0.lock().should_close_handler = Some(callback);
515 }
516
517 fn on_close(&self, _callback: Box<dyn FnOnce()>) {}
518
519 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
520 self.0.lock().hit_test_window_control_callback = Some(callback);
521 }
522
523 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
524 self.0.lock().appearance_change_callback = Some(callback);
525 }
526
527 fn draw(&self, scene: &Scene) {
528 let scale_factor = self.scale_factor();
529 let mut state = self.0.lock();
530 state.frame_callback_pending = true;
531 state.frame_scheduled = true;
532 let device_size: Size<DevicePixels> = state.bounds.size.to_device_pixels(scale_factor);
533 if let Some(renderer) = &mut state.renderer {
534 renderer.render_scene(scene, device_size).warn_on_err();
535 }
536 }
537
538 fn sprite_atlas(&self) -> sync::Arc<dyn crate::PlatformAtlas> {
539 self.0.lock().sprite_atlas.clone()
540 }
541
542 #[cfg(any(test, feature = "test-support"))]
543 fn render_to_image(&self, scene: &Scene) -> anyhow::Result<RgbaImage> {
544 let scale_factor = self.scale_factor();
545 let mut state = self.0.lock();
546 let size = state.bounds.size;
547 if let Some(renderer) = &mut state.renderer {
548 let device_size: Size<DevicePixels> = size.to_device_pixels(scale_factor);
549 renderer.render_scene_to_image(scene, device_size)
550 } else {
551 anyhow::bail!("render_to_image not available: no HeadlessRenderer configured")
552 }
553 }
554
555 fn as_test(&mut self) -> Option<&mut TestWindow> {
556 Some(self)
557 }
558
559 #[cfg(target_os = "windows")]
560 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
561 unimplemented!()
562 }
563
564 fn show_window_menu(&self, _position: Point<Pixels>) {
565 unimplemented!()
566 }
567
568 fn start_window_move(&self) {
569 unimplemented!()
570 }
571
572 fn can_start_external_drag(&self) -> bool {
573 true
574 }
575
576 fn start_external_drag(&self, payload: &crate::ExternalDragPayload) -> bool {
577 let mut state = self.0.lock();
578 match payload {
579 crate::ExternalDragPayload::Files(paths) => {
580 state.external_drag_files.extend_from_slice(paths.entries());
581 }
582 }
583 state.start_external_drag_result
584 }
585
586 fn update_ime_position(&self, _bounds: Bounds<Pixels>) {}
587
588 fn gpu_specs(&self) -> Option<GpuSpecs> {
589 None
590 }
591}