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