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