platform.rs

  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::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        self.background_executor().set_waiting_hint(None);
143        tx.send(Ok(select_path(&path))).ok();
144    }
145
146    #[track_caller]
147    pub(crate) fn simulate_prompt_answer(&self, response: &str) {
148        let prompt = self
149            .prompts
150            .borrow_mut()
151            .multiple_choice
152            .pop_front()
153            .expect("no pending multiple choice prompt");
154        self.background_executor().set_waiting_hint(None);
155        let Some(ix) = prompt.answers.iter().position(|a| a == response) else {
156            panic!(
157                "PROMPT: {}\n{:?}\n{:?}\nCannot respond with {}",
158                prompt.msg, prompt.detail, prompt.answers, response
159            )
160        };
161        prompt.tx.send(ix).ok();
162    }
163
164    pub(crate) fn has_pending_prompt(&self) -> bool {
165        !self.prompts.borrow().multiple_choice.is_empty()
166    }
167
168    pub(crate) fn pending_prompt(&self) -> Option<(String, String)> {
169        let prompts = self.prompts.borrow();
170        let prompt = prompts.multiple_choice.front()?;
171        Some((
172            prompt.msg.clone(),
173            prompt.detail.clone().unwrap_or_default(),
174        ))
175    }
176
177    pub(crate) fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) {
178        *self.screen_capture_sources.borrow_mut() = sources;
179    }
180
181    pub(crate) fn prompt(
182        &self,
183        msg: &str,
184        detail: Option<&str>,
185        answers: &[PromptButton],
186    ) -> oneshot::Receiver<usize> {
187        let (tx, rx) = oneshot::channel();
188        let answers: Vec<String> = answers.iter().map(|s| s.label().to_string()).collect();
189        self.background_executor()
190            .set_waiting_hint(Some(format!("PROMPT: {:?} {:?}", msg, detail)));
191        self.prompts
192            .borrow_mut()
193            .multiple_choice
194            .push_back(TestPrompt {
195                msg: msg.to_string(),
196                detail: detail.map(|s| s.to_string()),
197                answers,
198                tx,
199            });
200        rx
201    }
202
203    pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
204        let executor = self.foreground_executor();
205        let previous_window = self.active_window.borrow_mut().take();
206        self.active_window.borrow_mut().clone_from(&window);
207
208        executor
209            .spawn(async move {
210                if let Some(previous_window) = previous_window {
211                    if let Some(window) = window.as_ref()
212                        && Rc::ptr_eq(&previous_window.0, &window.0)
213                    {
214                        return;
215                    }
216                    previous_window.simulate_active_status_change(false);
217                }
218                if let Some(window) = window {
219                    window.simulate_active_status_change(true);
220                }
221            })
222            .detach();
223    }
224
225    pub(crate) fn did_prompt_for_new_path(&self) -> bool {
226        !self.prompts.borrow().new_path.is_empty()
227    }
228}
229
230impl Platform for TestPlatform {
231    fn background_executor(&self) -> BackgroundExecutor {
232        self.background_executor.clone()
233    }
234
235    fn foreground_executor(&self) -> ForegroundExecutor {
236        self.foreground_executor.clone()
237    }
238
239    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
240        self.text_system.clone()
241    }
242
243    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
244        Box::new(TestKeyboardLayout)
245    }
246
247    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
248        Rc::new(DummyKeyboardMapper)
249    }
250
251    fn on_keyboard_layout_change(&self, _: Box<dyn FnMut()>) {}
252
253    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
254        unimplemented!()
255    }
256
257    fn quit(&self) {}
258
259    fn restart(&self, path: Option<PathBuf>) {
260        if let Some(tx) = self.expect_restart.take() {
261            tx.send(path).unwrap();
262        }
263    }
264
265    fn activate(&self, _ignoring_other_apps: bool) {
266        //
267    }
268
269    fn hide(&self) {
270        unimplemented!()
271    }
272
273    fn hide_other_apps(&self) {
274        unimplemented!()
275    }
276
277    fn unhide_other_apps(&self) {
278        unimplemented!()
279    }
280
281    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
282        vec![self.active_display.clone()]
283    }
284
285    fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
286        Some(self.active_display.clone())
287    }
288
289    #[cfg(feature = "screen-capture")]
290    fn is_screen_capture_supported(&self) -> bool {
291        true
292    }
293
294    #[cfg(feature = "screen-capture")]
295    fn screen_capture_sources(
296        &self,
297    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
298        let (mut tx, rx) = oneshot::channel();
299        tx.send(Ok(self
300            .screen_capture_sources
301            .borrow()
302            .iter()
303            .map(|source| Rc::new(source.clone()) as Rc<dyn ScreenCaptureSource>)
304            .collect()))
305            .ok();
306        rx
307    }
308
309    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
310        self.active_window
311            .borrow()
312            .as_ref()
313            .map(|window| window.0.lock().handle)
314    }
315
316    fn open_window(
317        &self,
318        handle: AnyWindowHandle,
319        params: WindowParams,
320    ) -> anyhow::Result<Box<dyn crate::PlatformWindow>> {
321        let window = TestWindow::new(
322            handle,
323            params,
324            self.weak.clone(),
325            self.active_display.clone(),
326        );
327        Ok(Box::new(window))
328    }
329
330    fn window_appearance(&self) -> WindowAppearance {
331        WindowAppearance::Light
332    }
333
334    fn open_url(&self, url: &str) {
335        *self.opened_url.borrow_mut() = Some(url.to_string())
336    }
337
338    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
339        unimplemented!()
340    }
341
342    fn prompt_for_paths(
343        &self,
344        _options: crate::PathPromptOptions,
345    ) -> oneshot::Receiver<Result<Option<Vec<std::path::PathBuf>>>> {
346        unimplemented!()
347    }
348
349    fn prompt_for_new_path(
350        &self,
351        directory: &std::path::Path,
352        _suggested_name: Option<&str>,
353    ) -> oneshot::Receiver<Result<Option<std::path::PathBuf>>> {
354        let (tx, rx) = oneshot::channel();
355        self.background_executor()
356            .set_waiting_hint(Some(format!("PROMPT FOR PATH: {:?}", directory)));
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}