platform.rs

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