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        tx.send(Ok(select_path(&path))).ok();
143    }
144
145    #[track_caller]
146    pub(crate) fn simulate_prompt_answer(&self, response: &str) {
147        let prompt = self
148            .prompts
149            .borrow_mut()
150            .multiple_choice
151            .pop_front()
152            .expect("no pending multiple choice prompt");
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.prompts
188            .borrow_mut()
189            .multiple_choice
190            .push_back(TestPrompt {
191                msg: msg.to_string(),
192                detail: detail.map(|s| s.to_string()),
193                answers,
194                tx,
195            });
196        rx
197    }
198
199    pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
200        let executor = self.foreground_executor();
201        let previous_window = self.active_window.borrow_mut().take();
202        self.active_window.borrow_mut().clone_from(&window);
203
204        executor
205            .spawn(async move {
206                if let Some(previous_window) = previous_window {
207                    if let Some(window) = window.as_ref()
208                        && Rc::ptr_eq(&previous_window.0, &window.0)
209                    {
210                        return;
211                    }
212                    previous_window.simulate_active_status_change(false);
213                }
214                if let Some(window) = window {
215                    window.simulate_active_status_change(true);
216                }
217            })
218            .detach();
219    }
220
221    pub(crate) fn did_prompt_for_new_path(&self) -> bool {
222        !self.prompts.borrow().new_path.is_empty()
223    }
224}
225
226impl Platform for TestPlatform {
227    fn background_executor(&self) -> BackgroundExecutor {
228        self.background_executor.clone()
229    }
230
231    fn foreground_executor(&self) -> ForegroundExecutor {
232        self.foreground_executor.clone()
233    }
234
235    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
236        self.text_system.clone()
237    }
238
239    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
240        Box::new(TestKeyboardLayout)
241    }
242
243    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
244        Rc::new(DummyKeyboardMapper)
245    }
246
247    fn on_keyboard_layout_change(&self, _: Box<dyn FnMut()>) {}
248
249    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
250        unimplemented!()
251    }
252
253    fn quit(&self) {}
254
255    fn restart(&self, path: Option<PathBuf>) {
256        if let Some(tx) = self.expect_restart.take() {
257            tx.send(path).unwrap();
258        }
259    }
260
261    fn activate(&self, _ignoring_other_apps: bool) {
262        //
263    }
264
265    fn hide(&self) {
266        unimplemented!()
267    }
268
269    fn hide_other_apps(&self) {
270        unimplemented!()
271    }
272
273    fn unhide_other_apps(&self) {
274        unimplemented!()
275    }
276
277    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
278        vec![self.active_display.clone()]
279    }
280
281    fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
282        Some(self.active_display.clone())
283    }
284
285    #[cfg(feature = "screen-capture")]
286    fn is_screen_capture_supported(&self) -> bool {
287        true
288    }
289
290    #[cfg(feature = "screen-capture")]
291    fn screen_capture_sources(
292        &self,
293    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
294        let (mut tx, rx) = oneshot::channel();
295        tx.send(Ok(self
296            .screen_capture_sources
297            .borrow()
298            .iter()
299            .map(|source| Rc::new(source.clone()) as Rc<dyn ScreenCaptureSource>)
300            .collect()))
301            .ok();
302        rx
303    }
304
305    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
306        self.active_window
307            .borrow()
308            .as_ref()
309            .map(|window| window.0.lock().handle)
310    }
311
312    fn open_window(
313        &self,
314        handle: AnyWindowHandle,
315        params: WindowParams,
316    ) -> anyhow::Result<Box<dyn crate::PlatformWindow>> {
317        let window = TestWindow::new(
318            handle,
319            params,
320            self.weak.clone(),
321            self.active_display.clone(),
322        );
323        Ok(Box::new(window))
324    }
325
326    fn window_appearance(&self) -> WindowAppearance {
327        WindowAppearance::Light
328    }
329
330    fn open_url(&self, url: &str) {
331        *self.opened_url.borrow_mut() = Some(url.to_string())
332    }
333
334    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
335        unimplemented!()
336    }
337
338    fn prompt_for_paths(
339        &self,
340        _options: crate::PathPromptOptions,
341    ) -> oneshot::Receiver<Result<Option<Vec<std::path::PathBuf>>>> {
342        unimplemented!()
343    }
344
345    fn prompt_for_new_path(
346        &self,
347        directory: &std::path::Path,
348        _suggested_name: Option<&str>,
349    ) -> oneshot::Receiver<Result<Option<std::path::PathBuf>>> {
350        let (tx, rx) = oneshot::channel();
351        self.prompts
352            .borrow_mut()
353            .new_path
354            .push_back((directory.to_path_buf(), tx));
355        rx
356    }
357
358    fn can_select_mixed_files_and_dirs(&self) -> bool {
359        true
360    }
361
362    fn reveal_path(&self, _path: &std::path::Path) {
363        unimplemented!()
364    }
365
366    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
367
368    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
369        unimplemented!()
370    }
371
372    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
373    fn set_dock_menu(&self, _menu: Vec<crate::MenuItem>, _keymap: &Keymap) {}
374
375    fn add_recent_document(&self, _paths: &Path) {}
376
377    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
378
379    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
380
381    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
382
383    fn app_path(&self) -> Result<std::path::PathBuf> {
384        unimplemented!()
385    }
386
387    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
388        unimplemented!()
389    }
390
391    fn set_cursor_style(&self, style: crate::CursorStyle) {
392        *self.active_cursor.lock() = style;
393    }
394
395    fn should_auto_hide_scrollbars(&self) -> bool {
396        false
397    }
398
399    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
400        self.current_clipboard_item.lock().clone()
401    }
402
403    fn write_to_clipboard(&self, item: ClipboardItem) {
404        *self.current_clipboard_item.lock() = Some(item);
405    }
406
407    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
408    fn read_from_primary(&self) -> Option<ClipboardItem> {
409        self.current_primary_item.lock().clone()
410    }
411
412    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
413    fn write_to_primary(&self, item: ClipboardItem) {
414        *self.current_primary_item.lock() = Some(item);
415    }
416
417    #[cfg(target_os = "macos")]
418    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
419        self.current_find_pasteboard_item.lock().clone()
420    }
421
422    #[cfg(target_os = "macos")]
423    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
424        *self.current_find_pasteboard_item.lock() = Some(item);
425    }
426
427    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
428        Task::ready(Ok(()))
429    }
430
431    fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
432        Task::ready(Ok(None))
433    }
434
435    fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
436        Task::ready(Ok(()))
437    }
438
439    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
440        unimplemented!()
441    }
442
443    fn open_with_system(&self, _path: &Path) {
444        unimplemented!()
445    }
446}
447
448impl TestScreenCaptureSource {
449    /// Create a fake screen capture source, for testing.
450    pub fn new() -> Self {
451        Self {}
452    }
453}
454
455#[cfg(target_os = "windows")]
456impl Drop for TestPlatform {
457    fn drop(&mut self) {
458        unsafe {
459            std::mem::ManuallyDrop::drop(&mut self.bitmap_factory);
460            windows::Win32::System::Ole::OleUninitialize();
461        }
462    }
463}
464
465struct TestKeyboardLayout;
466
467impl PlatformKeyboardLayout for TestKeyboardLayout {
468    fn id(&self) -> &str {
469        "zed.keyboard.example"
470    }
471
472    fn name(&self) -> &str {
473        "zed.keyboard.example"
474    }
475}