platform.rs

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