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