1use crate::{
2 AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DevicePixels,
3 DummyKeyboardMapper, ForegroundExecutor, Keymap, NoopTextSystem, Platform, PlatformDisplay,
4 PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, PromptButton,
5 ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream, SourceMetadata, Task,
6 TestDisplay, TestWindow, ThermalState, WindowAppearance, WindowParams, size,
7};
8use anyhow::Result;
9use collections::VecDeque;
10use futures::channel::oneshot;
11use parking_lot::Mutex;
12use std::{
13 cell::RefCell,
14 path::{Path, PathBuf},
15 rc::{Rc, Weak},
16 sync::Arc,
17};
18#[cfg(target_os = "windows")]
19use windows::Win32::{
20 Graphics::Imaging::{CLSID_WICImagingFactory, IWICImagingFactory},
21 System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance},
22};
23
24/// TestPlatform implements the Platform trait for use in tests.
25pub(crate) struct TestPlatform {
26 background_executor: BackgroundExecutor,
27 foreground_executor: ForegroundExecutor,
28
29 pub(crate) active_window: RefCell<Option<TestWindow>>,
30 active_display: Rc<dyn PlatformDisplay>,
31 active_cursor: Mutex<CursorStyle>,
32 current_clipboard_item: Mutex<Option<ClipboardItem>>,
33 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
34 current_primary_item: Mutex<Option<ClipboardItem>>,
35 #[cfg(target_os = "macos")]
36 current_find_pasteboard_item: Mutex<Option<ClipboardItem>>,
37 pub(crate) prompts: RefCell<TestPrompts>,
38 screen_capture_sources: RefCell<Vec<TestScreenCaptureSource>>,
39 pub opened_url: RefCell<Option<String>>,
40 pub text_system: Arc<dyn PlatformTextSystem>,
41 pub expect_restart: RefCell<Option<oneshot::Sender<Option<PathBuf>>>>,
42 #[cfg(target_os = "windows")]
43 bitmap_factory: std::mem::ManuallyDrop<IWICImagingFactory>,
44 weak: Weak<Self>,
45}
46
47#[derive(Clone)]
48/// A fake screen capture source, used for testing.
49pub struct TestScreenCaptureSource {}
50
51/// A fake screen capture stream, used for testing.
52pub struct TestScreenCaptureStream {}
53
54impl ScreenCaptureSource for TestScreenCaptureSource {
55 fn metadata(&self) -> Result<SourceMetadata> {
56 Ok(SourceMetadata {
57 id: 0,
58 is_main: None,
59 label: None,
60 resolution: size(DevicePixels(1), DevicePixels(1)),
61 })
62 }
63
64 fn stream(
65 &self,
66 _foreground_executor: &ForegroundExecutor,
67 _frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
68 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {
69 let (mut tx, rx) = oneshot::channel();
70 let stream = TestScreenCaptureStream {};
71 tx.send(Ok(Box::new(stream) as Box<dyn ScreenCaptureStream>))
72 .ok();
73 rx
74 }
75}
76
77impl ScreenCaptureStream for TestScreenCaptureStream {
78 fn metadata(&self) -> Result<SourceMetadata> {
79 TestScreenCaptureSource {}.metadata()
80 }
81}
82
83struct TestPrompt {
84 msg: String,
85 detail: Option<String>,
86 answers: Vec<String>,
87 tx: oneshot::Sender<usize>,
88}
89
90#[derive(Default)]
91pub(crate) struct TestPrompts {
92 multiple_choice: VecDeque<TestPrompt>,
93 new_path: VecDeque<(PathBuf, oneshot::Sender<Result<Option<PathBuf>>>)>,
94}
95
96impl TestPlatform {
97 pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Rc<Self> {
98 #[cfg(target_os = "windows")]
99 let bitmap_factory = unsafe {
100 windows::Win32::System::Ole::OleInitialize(None)
101 .expect("unable to initialize Windows OLE");
102 std::mem::ManuallyDrop::new(
103 CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
104 .expect("Error creating bitmap factory."),
105 )
106 };
107
108 let text_system = Arc::new(NoopTextSystem);
109
110 Rc::new_cyclic(|weak| TestPlatform {
111 background_executor: executor,
112 foreground_executor,
113 prompts: Default::default(),
114 screen_capture_sources: Default::default(),
115 active_cursor: Default::default(),
116 active_display: Rc::new(TestDisplay::new()),
117 active_window: Default::default(),
118 expect_restart: Default::default(),
119 current_clipboard_item: Mutex::new(None),
120 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
121 current_primary_item: Mutex::new(None),
122 #[cfg(target_os = "macos")]
123 current_find_pasteboard_item: Mutex::new(None),
124 weak: weak.clone(),
125 opened_url: Default::default(),
126 #[cfg(target_os = "windows")]
127 bitmap_factory,
128 text_system,
129 })
130 }
131
132 pub(crate) fn simulate_new_path_selection(
133 &self,
134 select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
135 ) {
136 let (path, tx) = self
137 .prompts
138 .borrow_mut()
139 .new_path
140 .pop_front()
141 .expect("no pending new path prompt");
142 tx.send(Ok(select_path(&path))).ok();
143 }
144
145 #[track_caller]
146 pub(crate) fn simulate_prompt_answer(&self, response: &str) {
147 let prompt = self
148 .prompts
149 .borrow_mut()
150 .multiple_choice
151 .pop_front()
152 .expect("no pending multiple choice prompt");
153 let Some(ix) = prompt.answers.iter().position(|a| a == response) else {
154 panic!(
155 "PROMPT: {}\n{:?}\n{:?}\nCannot respond with {}",
156 prompt.msg, prompt.detail, prompt.answers, response
157 )
158 };
159 prompt.tx.send(ix).ok();
160 }
161
162 pub(crate) fn has_pending_prompt(&self) -> bool {
163 !self.prompts.borrow().multiple_choice.is_empty()
164 }
165
166 pub(crate) fn pending_prompt(&self) -> Option<(String, String)> {
167 let prompts = self.prompts.borrow();
168 let prompt = prompts.multiple_choice.front()?;
169 Some((
170 prompt.msg.clone(),
171 prompt.detail.clone().unwrap_or_default(),
172 ))
173 }
174
175 pub(crate) fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) {
176 *self.screen_capture_sources.borrow_mut() = sources;
177 }
178
179 pub(crate) fn prompt(
180 &self,
181 msg: &str,
182 detail: Option<&str>,
183 answers: &[PromptButton],
184 ) -> oneshot::Receiver<usize> {
185 let (tx, rx) = oneshot::channel();
186 let answers: Vec<String> = answers.iter().map(|s| s.label().to_string()).collect();
187 self.prompts
188 .borrow_mut()
189 .multiple_choice
190 .push_back(TestPrompt {
191 msg: msg.to_string(),
192 detail: detail.map(|s| s.to_string()),
193 answers,
194 tx,
195 });
196 rx
197 }
198
199 pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
200 let executor = self.foreground_executor();
201 let previous_window = self.active_window.borrow_mut().take();
202 self.active_window.borrow_mut().clone_from(&window);
203
204 executor
205 .spawn(async move {
206 if let Some(previous_window) = previous_window {
207 if let Some(window) = window.as_ref()
208 && Rc::ptr_eq(&previous_window.0, &window.0)
209 {
210 return;
211 }
212 previous_window.simulate_active_status_change(false);
213 }
214 if let Some(window) = window {
215 window.simulate_active_status_change(true);
216 }
217 })
218 .detach();
219 }
220
221 pub(crate) fn did_prompt_for_new_path(&self) -> bool {
222 !self.prompts.borrow().new_path.is_empty()
223 }
224}
225
226impl Platform for TestPlatform {
227 fn background_executor(&self) -> BackgroundExecutor {
228 self.background_executor.clone()
229 }
230
231 fn foreground_executor(&self) -> ForegroundExecutor {
232 self.foreground_executor.clone()
233 }
234
235 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
236 self.text_system.clone()
237 }
238
239 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
240 Box::new(TestKeyboardLayout)
241 }
242
243 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
244 Rc::new(DummyKeyboardMapper)
245 }
246
247 fn on_keyboard_layout_change(&self, _: Box<dyn FnMut()>) {}
248
249 fn on_thermal_state_change(&self, _: Box<dyn FnMut()>) {}
250
251 fn thermal_state(&self) -> ThermalState {
252 ThermalState::Nominal
253 }
254
255 fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
256 unimplemented!()
257 }
258
259 fn quit(&self) {}
260
261 fn restart(&self, path: Option<PathBuf>) {
262 if let Some(tx) = self.expect_restart.take() {
263 tx.send(path).unwrap();
264 }
265 }
266
267 fn activate(&self, _ignoring_other_apps: bool) {
268 //
269 }
270
271 fn hide(&self) {
272 unimplemented!()
273 }
274
275 fn hide_other_apps(&self) {
276 unimplemented!()
277 }
278
279 fn unhide_other_apps(&self) {
280 unimplemented!()
281 }
282
283 fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
284 vec![self.active_display.clone()]
285 }
286
287 fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
288 Some(self.active_display.clone())
289 }
290
291 #[cfg(feature = "screen-capture")]
292 fn is_screen_capture_supported(&self) -> bool {
293 true
294 }
295
296 #[cfg(feature = "screen-capture")]
297 fn screen_capture_sources(
298 &self,
299 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
300 let (mut tx, rx) = oneshot::channel();
301 tx.send(Ok(self
302 .screen_capture_sources
303 .borrow()
304 .iter()
305 .map(|source| Rc::new(source.clone()) as Rc<dyn ScreenCaptureSource>)
306 .collect()))
307 .ok();
308 rx
309 }
310
311 fn active_window(&self) -> Option<crate::AnyWindowHandle> {
312 self.active_window
313 .borrow()
314 .as_ref()
315 .map(|window| window.0.lock().handle)
316 }
317
318 fn open_window(
319 &self,
320 handle: AnyWindowHandle,
321 params: WindowParams,
322 ) -> anyhow::Result<Box<dyn crate::PlatformWindow>> {
323 let window = TestWindow::new(
324 handle,
325 params,
326 self.weak.clone(),
327 self.active_display.clone(),
328 );
329 Ok(Box::new(window))
330 }
331
332 fn window_appearance(&self) -> WindowAppearance {
333 WindowAppearance::Light
334 }
335
336 fn open_url(&self, url: &str) {
337 *self.opened_url.borrow_mut() = Some(url.to_string())
338 }
339
340 fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
341 unimplemented!()
342 }
343
344 fn prompt_for_paths(
345 &self,
346 _options: crate::PathPromptOptions,
347 ) -> oneshot::Receiver<Result<Option<Vec<std::path::PathBuf>>>> {
348 unimplemented!()
349 }
350
351 fn prompt_for_new_path(
352 &self,
353 directory: &std::path::Path,
354 _suggested_name: Option<&str>,
355 ) -> oneshot::Receiver<Result<Option<std::path::PathBuf>>> {
356 let (tx, rx) = oneshot::channel();
357 self.prompts
358 .borrow_mut()
359 .new_path
360 .push_back((directory.to_path_buf(), tx));
361 rx
362 }
363
364 fn can_select_mixed_files_and_dirs(&self) -> bool {
365 true
366 }
367
368 fn reveal_path(&self, _path: &std::path::Path) {
369 unimplemented!()
370 }
371
372 fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
373
374 fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
375 unimplemented!()
376 }
377
378 fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
379 fn set_dock_menu(&self, _menu: Vec<crate::MenuItem>, _keymap: &Keymap) {}
380
381 fn add_recent_document(&self, _paths: &Path) {}
382
383 fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
384
385 fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
386
387 fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
388
389 fn app_path(&self) -> Result<std::path::PathBuf> {
390 unimplemented!()
391 }
392
393 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
394 unimplemented!()
395 }
396
397 fn set_cursor_style(&self, style: crate::CursorStyle) {
398 *self.active_cursor.lock() = style;
399 }
400
401 fn should_auto_hide_scrollbars(&self) -> bool {
402 false
403 }
404
405 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
406 self.current_clipboard_item.lock().clone()
407 }
408
409 fn write_to_clipboard(&self, item: ClipboardItem) {
410 *self.current_clipboard_item.lock() = Some(item);
411 }
412
413 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
414 fn read_from_primary(&self) -> Option<ClipboardItem> {
415 self.current_primary_item.lock().clone()
416 }
417
418 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
419 fn write_to_primary(&self, item: ClipboardItem) {
420 *self.current_primary_item.lock() = Some(item);
421 }
422
423 #[cfg(target_os = "macos")]
424 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
425 self.current_find_pasteboard_item.lock().clone()
426 }
427
428 #[cfg(target_os = "macos")]
429 fn write_to_find_pasteboard(&self, item: ClipboardItem) {
430 *self.current_find_pasteboard_item.lock() = Some(item);
431 }
432
433 fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
434 Task::ready(Ok(()))
435 }
436
437 fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
438 Task::ready(Ok(None))
439 }
440
441 fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
442 Task::ready(Ok(()))
443 }
444
445 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
446 unimplemented!()
447 }
448
449 fn open_with_system(&self, _path: &Path) {
450 unimplemented!()
451 }
452}
453
454impl TestScreenCaptureSource {
455 /// Create a fake screen capture source, for testing.
456 pub fn new() -> Self {
457 Self {}
458 }
459}
460
461#[cfg(target_os = "windows")]
462impl Drop for TestPlatform {
463 fn drop(&mut self) {
464 unsafe {
465 std::mem::ManuallyDrop::drop(&mut self.bitmap_factory);
466 windows::Win32::System::Ole::OleUninitialize();
467 }
468 }
469}
470
471struct TestKeyboardLayout;
472
473impl PlatformKeyboardLayout for TestKeyboardLayout {
474 fn id(&self) -> &str {
475 "zed.keyboard.example"
476 }
477
478 fn name(&self) -> &str {
479 "zed.keyboard.example"
480 }
481}