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    pub expect_restart: RefCell<Option<oneshot::Sender<Option<PathBuf>>>>,
 40    #[cfg(target_os = "windows")]
 41    bitmap_factory: std::mem::ManuallyDrop<IWICImagingFactory>,
 42    weak: Weak<Self>,
 43}
 44
 45#[derive(Clone)]
 46/// A fake screen capture source, used for testing.
 47pub struct TestScreenCaptureSource {}
 48
 49/// A fake screen capture stream, used for testing.
 50pub struct TestScreenCaptureStream {}
 51
 52impl ScreenCaptureSource for TestScreenCaptureSource {
 53    fn metadata(&self) -> Result<SourceMetadata> {
 54        Ok(SourceMetadata {
 55            id: 0,
 56            is_main: None,
 57            label: None,
 58            resolution: size(DevicePixels(1), DevicePixels(1)),
 59        })
 60    }
 61
 62    fn stream(
 63        &self,
 64        _foreground_executor: &ForegroundExecutor,
 65        _frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
 66    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {
 67        let (mut tx, rx) = oneshot::channel();
 68        let stream = TestScreenCaptureStream {};
 69        tx.send(Ok(Box::new(stream) as Box<dyn ScreenCaptureStream>))
 70            .ok();
 71        rx
 72    }
 73}
 74
 75impl ScreenCaptureStream for TestScreenCaptureStream {
 76    fn metadata(&self) -> Result<SourceMetadata> {
 77        TestScreenCaptureSource {}.metadata()
 78    }
 79}
 80
 81struct TestPrompt {
 82    msg: String,
 83    detail: Option<String>,
 84    answers: Vec<String>,
 85    tx: oneshot::Sender<usize>,
 86}
 87
 88#[derive(Default)]
 89pub(crate) struct TestPrompts {
 90    multiple_choice: VecDeque<TestPrompt>,
 91    new_path: VecDeque<(PathBuf, oneshot::Sender<Result<Option<PathBuf>>>)>,
 92}
 93
 94impl TestPlatform {
 95    pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Rc<Self> {
 96        #[cfg(target_os = "windows")]
 97        let bitmap_factory = unsafe {
 98            windows::Win32::System::Ole::OleInitialize(None)
 99                .expect("unable to initialize Windows OLE");
100            std::mem::ManuallyDrop::new(
101                CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
102                    .expect("Error creating bitmap factory."),
103            )
104        };
105
106        let text_system = Arc::new(NoopTextSystem);
107
108        Rc::new_cyclic(|weak| TestPlatform {
109            background_executor: executor,
110            foreground_executor,
111            prompts: Default::default(),
112            screen_capture_sources: Default::default(),
113            active_cursor: Default::default(),
114            active_display: Rc::new(TestDisplay::new()),
115            active_window: Default::default(),
116            expect_restart: Default::default(),
117            current_clipboard_item: Mutex::new(None),
118            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
119            current_primary_item: Mutex::new(None),
120            weak: weak.clone(),
121            opened_url: Default::default(),
122            #[cfg(target_os = "windows")]
123            bitmap_factory,
124            text_system,
125        })
126    }
127
128    pub(crate) fn simulate_new_path_selection(
129        &self,
130        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
131    ) {
132        let (path, tx) = self
133            .prompts
134            .borrow_mut()
135            .new_path
136            .pop_front()
137            .expect("no pending new path prompt");
138        self.background_executor().set_waiting_hint(None);
139        tx.send(Ok(select_path(&path))).ok();
140    }
141
142    #[track_caller]
143    pub(crate) fn simulate_prompt_answer(&self, response: &str) {
144        let prompt = self
145            .prompts
146            .borrow_mut()
147            .multiple_choice
148            .pop_front()
149            .expect("no pending multiple choice prompt");
150        self.background_executor().set_waiting_hint(None);
151        let Some(ix) = prompt.answers.iter().position(|a| a == response) else {
152            panic!(
153                "PROMPT: {}\n{:?}\n{:?}\nCannot respond with {}",
154                prompt.msg, prompt.detail, prompt.answers, response
155            )
156        };
157        prompt.tx.send(ix).ok();
158    }
159
160    pub(crate) fn has_pending_prompt(&self) -> bool {
161        !self.prompts.borrow().multiple_choice.is_empty()
162    }
163
164    pub(crate) fn pending_prompt(&self) -> Option<(String, String)> {
165        let prompts = self.prompts.borrow();
166        let prompt = prompts.multiple_choice.front()?;
167        Some((
168            prompt.msg.clone(),
169            prompt.detail.clone().unwrap_or_default(),
170        ))
171    }
172
173    pub(crate) fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) {
174        *self.screen_capture_sources.borrow_mut() = sources;
175    }
176
177    pub(crate) fn prompt(
178        &self,
179        msg: &str,
180        detail: Option<&str>,
181        answers: &[PromptButton],
182    ) -> oneshot::Receiver<usize> {
183        let (tx, rx) = oneshot::channel();
184        let answers: Vec<String> = answers.iter().map(|s| s.label().to_string()).collect();
185        self.background_executor()
186            .set_waiting_hint(Some(format!("PROMPT: {:?} {:?}", msg, detail)));
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.background_executor()
352            .set_waiting_hint(Some(format!("PROMPT FOR PATH: {:?}", directory)));
353        self.prompts
354            .borrow_mut()
355            .new_path
356            .push_back((directory.to_path_buf(), tx));
357        rx
358    }
359
360    fn can_select_mixed_files_and_dirs(&self) -> bool {
361        true
362    }
363
364    fn reveal_path(&self, _path: &std::path::Path) {
365        unimplemented!()
366    }
367
368    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
369
370    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
371        unimplemented!()
372    }
373
374    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
375    fn set_dock_menu(&self, _menu: Vec<crate::MenuItem>, _keymap: &Keymap) {}
376
377    fn add_recent_document(&self, _paths: &Path) {}
378
379    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
380
381    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
382
383    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
384
385    fn app_path(&self) -> Result<std::path::PathBuf> {
386        unimplemented!()
387    }
388
389    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
390        unimplemented!()
391    }
392
393    fn set_cursor_style(&self, style: crate::CursorStyle) {
394        *self.active_cursor.lock() = style;
395    }
396
397    fn should_auto_hide_scrollbars(&self) -> bool {
398        false
399    }
400
401    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
402    fn write_to_primary(&self, item: ClipboardItem) {
403        *self.current_primary_item.lock() = Some(item);
404    }
405
406    fn write_to_clipboard(&self, item: ClipboardItem) {
407        *self.current_clipboard_item.lock() = Some(item);
408    }
409
410    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
411    fn read_from_primary(&self) -> Option<ClipboardItem> {
412        self.current_primary_item.lock().clone()
413    }
414
415    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
416        self.current_clipboard_item.lock().clone()
417    }
418
419    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
420        Task::ready(Ok(()))
421    }
422
423    fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
424        Task::ready(Ok(None))
425    }
426
427    fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
428        Task::ready(Ok(()))
429    }
430
431    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
432        unimplemented!()
433    }
434
435    fn open_with_system(&self, _path: &Path) {
436        unimplemented!()
437    }
438}
439
440impl TestScreenCaptureSource {
441    /// Create a fake screen capture source, for testing.
442    pub fn new() -> Self {
443        Self {}
444    }
445}
446
447#[cfg(target_os = "windows")]
448impl Drop for TestPlatform {
449    fn drop(&mut self) {
450        unsafe {
451            std::mem::ManuallyDrop::drop(&mut self.bitmap_factory);
452            windows::Win32::System::Ole::OleUninitialize();
453        }
454    }
455}
456
457struct TestKeyboardLayout;
458
459impl PlatformKeyboardLayout for TestKeyboardLayout {
460    fn id(&self) -> &str {
461        "zed.keyboard.example"
462    }
463
464    fn name(&self) -> &str {
465        "zed.keyboard.example"
466    }
467}