platform.rs

  1use crate::{
  2    AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor, Keymap,
  3    Platform, PlatformDisplay, PlatformTextSystem, Task, TestDisplay, TestWindow, WindowAppearance,
  4    WindowParams,
  5};
  6use anyhow::Result;
  7use collections::VecDeque;
  8use futures::channel::oneshot;
  9use parking_lot::Mutex;
 10use std::{
 11    cell::RefCell,
 12    path::{Path, PathBuf},
 13    rc::{Rc, Weak},
 14    sync::Arc,
 15};
 16
 17/// TestPlatform implements the Platform trait for use in tests.
 18pub(crate) struct TestPlatform {
 19    background_executor: BackgroundExecutor,
 20    foreground_executor: ForegroundExecutor,
 21
 22    pub(crate) active_window: RefCell<Option<TestWindow>>,
 23    active_display: Rc<dyn PlatformDisplay>,
 24    active_cursor: Mutex<CursorStyle>,
 25    current_clipboard_item: Mutex<Option<ClipboardItem>>,
 26    #[cfg(target_os = "linux")]
 27    current_primary_item: Mutex<Option<ClipboardItem>>,
 28    pub(crate) prompts: RefCell<TestPrompts>,
 29    pub opened_url: RefCell<Option<String>>,
 30    weak: Weak<Self>,
 31}
 32
 33#[derive(Default)]
 34pub(crate) struct TestPrompts {
 35    multiple_choice: VecDeque<oneshot::Sender<usize>>,
 36    new_path: VecDeque<(PathBuf, oneshot::Sender<Option<PathBuf>>)>,
 37}
 38
 39impl TestPlatform {
 40    pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Rc<Self> {
 41        #[cfg(target_os = "windows")]
 42        unsafe {
 43            windows::Win32::System::Ole::OleInitialize(None)
 44                .expect("unable to initialize Windows OLE");
 45        }
 46
 47        Rc::new_cyclic(|weak| TestPlatform {
 48            background_executor: executor,
 49            foreground_executor,
 50            prompts: Default::default(),
 51            active_cursor: Default::default(),
 52            active_display: Rc::new(TestDisplay::new()),
 53            active_window: Default::default(),
 54            current_clipboard_item: Mutex::new(None),
 55            #[cfg(target_os = "linux")]
 56            current_primary_item: Mutex::new(None),
 57            weak: weak.clone(),
 58            opened_url: Default::default(),
 59        })
 60    }
 61
 62    pub(crate) fn simulate_new_path_selection(
 63        &self,
 64        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
 65    ) {
 66        let (path, tx) = self
 67            .prompts
 68            .borrow_mut()
 69            .new_path
 70            .pop_front()
 71            .expect("no pending new path prompt");
 72        tx.send(select_path(&path)).ok();
 73    }
 74
 75    pub(crate) fn simulate_prompt_answer(&self, response_ix: usize) {
 76        let tx = self
 77            .prompts
 78            .borrow_mut()
 79            .multiple_choice
 80            .pop_front()
 81            .expect("no pending multiple choice prompt");
 82        self.background_executor().set_waiting_hint(None);
 83        tx.send(response_ix).ok();
 84    }
 85
 86    pub(crate) fn has_pending_prompt(&self) -> bool {
 87        !self.prompts.borrow().multiple_choice.is_empty()
 88    }
 89
 90    pub(crate) fn prompt(&self, msg: &str, detail: Option<&str>) -> oneshot::Receiver<usize> {
 91        let (tx, rx) = oneshot::channel();
 92        self.background_executor()
 93            .set_waiting_hint(Some(format!("PROMPT: {:?} {:?}", msg, detail)));
 94        self.prompts.borrow_mut().multiple_choice.push_back(tx);
 95        rx
 96    }
 97
 98    pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
 99        let executor = self.foreground_executor().clone();
100        let previous_window = self.active_window.borrow_mut().take();
101        self.active_window.borrow_mut().clone_from(&window);
102
103        executor
104            .spawn(async move {
105                if let Some(previous_window) = previous_window {
106                    if let Some(window) = window.as_ref() {
107                        if Arc::ptr_eq(&previous_window.0, &window.0) {
108                            return;
109                        }
110                    }
111                    previous_window.simulate_active_status_change(false);
112                }
113                if let Some(window) = window {
114                    window.simulate_active_status_change(true);
115                }
116            })
117            .detach();
118    }
119
120    pub(crate) fn did_prompt_for_new_path(&self) -> bool {
121        self.prompts.borrow().new_path.len() > 0
122    }
123}
124
125impl Platform for TestPlatform {
126    fn background_executor(&self) -> BackgroundExecutor {
127        self.background_executor.clone()
128    }
129
130    fn foreground_executor(&self) -> ForegroundExecutor {
131        self.foreground_executor.clone()
132    }
133
134    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
135        #[cfg(target_os = "macos")]
136        return Arc::new(crate::platform::mac::MacTextSystem::new());
137
138        #[cfg(target_os = "linux")]
139        return Arc::new(crate::platform::cosmic_text::CosmicTextSystem::new());
140
141        #[cfg(target_os = "windows")]
142        return Arc::new(crate::platform::windows::DirectWriteTextSystem::new().unwrap());
143    }
144
145    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
146        unimplemented!()
147    }
148
149    fn quit(&self) {}
150
151    fn restart(&self, _: Option<PathBuf>) {
152        unimplemented!()
153    }
154
155    fn activate(&self, _ignoring_other_apps: bool) {
156        //
157    }
158
159    fn hide(&self) {
160        unimplemented!()
161    }
162
163    fn hide_other_apps(&self) {
164        unimplemented!()
165    }
166
167    fn unhide_other_apps(&self) {
168        unimplemented!()
169    }
170
171    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
172        vec![self.active_display.clone()]
173    }
174
175    fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
176        Some(self.active_display.clone())
177    }
178
179    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
180        self.active_window
181            .borrow()
182            .as_ref()
183            .map(|window| window.0.lock().handle)
184    }
185
186    fn open_window(
187        &self,
188        handle: AnyWindowHandle,
189        params: WindowParams,
190    ) -> anyhow::Result<Box<dyn crate::PlatformWindow>> {
191        let window = TestWindow::new(
192            handle,
193            params,
194            self.weak.clone(),
195            self.active_display.clone(),
196        );
197        Ok(Box::new(window))
198    }
199
200    fn window_appearance(&self) -> WindowAppearance {
201        WindowAppearance::Light
202    }
203
204    fn open_url(&self, url: &str) {
205        *self.opened_url.borrow_mut() = Some(url.to_string())
206    }
207
208    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
209        unimplemented!()
210    }
211
212    fn prompt_for_paths(
213        &self,
214        _options: crate::PathPromptOptions,
215    ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
216        unimplemented!()
217    }
218
219    fn prompt_for_new_path(
220        &self,
221        directory: &std::path::Path,
222    ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
223        let (tx, rx) = oneshot::channel();
224        self.prompts
225            .borrow_mut()
226            .new_path
227            .push_back((directory.to_path_buf(), tx));
228        rx
229    }
230
231    fn reveal_path(&self, _path: &std::path::Path) {
232        unimplemented!()
233    }
234
235    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
236
237    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
238        unimplemented!()
239    }
240
241    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
242    fn set_dock_menu(&self, _menu: Vec<crate::MenuItem>, _keymap: &Keymap) {}
243
244    fn add_recent_document(&self, _paths: &Path) {}
245
246    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
247
248    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
249
250    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
251
252    fn app_path(&self) -> Result<std::path::PathBuf> {
253        unimplemented!()
254    }
255
256    fn local_timezone(&self) -> time::UtcOffset {
257        time::UtcOffset::UTC
258    }
259
260    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
261        unimplemented!()
262    }
263
264    fn set_cursor_style(&self, style: crate::CursorStyle) {
265        *self.active_cursor.lock() = style;
266    }
267
268    fn should_auto_hide_scrollbars(&self) -> bool {
269        false
270    }
271
272    #[cfg(target_os = "linux")]
273    fn write_to_primary(&self, item: ClipboardItem) {
274        *self.current_primary_item.lock() = Some(item);
275    }
276
277    fn write_to_clipboard(&self, item: ClipboardItem) {
278        *self.current_clipboard_item.lock() = Some(item);
279    }
280
281    #[cfg(target_os = "linux")]
282    fn read_from_primary(&self) -> Option<ClipboardItem> {
283        self.current_primary_item.lock().clone()
284    }
285
286    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
287        self.current_clipboard_item.lock().clone()
288    }
289
290    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
291        Task::ready(Ok(()))
292    }
293
294    fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
295        Task::ready(Ok(None))
296    }
297
298    fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
299        Task::ready(Ok(()))
300    }
301
302    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
303        unimplemented!()
304    }
305}