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