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