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