platform.rs

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