platform.rs

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