platform.rs

  1use crate::{
  2    AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId, ForegroundExecutor,
  3    Keymap, Platform, PlatformDisplay, PlatformTextSystem, TestDisplay, TestWindow, WindowOptions,
  4};
  5use anyhow::{anyhow, Result};
  6use collections::VecDeque;
  7use futures::channel::oneshot;
  8use parking_lot::Mutex;
  9use std::{
 10    cell::RefCell,
 11    path::PathBuf,
 12    rc::{Rc, Weak},
 13    sync::Arc,
 14    time::Duration,
 15};
 16
 17/// TestPlatform implements the Platform trait for use in tests.
 18pub 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    weak: Weak<Self>,
 28}
 29
 30#[derive(Default)]
 31pub(crate) struct TestPrompts {
 32    multiple_choice: VecDeque<oneshot::Sender<usize>>,
 33    new_path: VecDeque<(PathBuf, oneshot::Sender<Option<PathBuf>>)>,
 34}
 35
 36impl TestPlatform {
 37    pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Rc<Self> {
 38        Rc::new_cyclic(|weak| TestPlatform {
 39            background_executor: executor,
 40            foreground_executor,
 41            prompts: Default::default(),
 42            active_cursor: Default::default(),
 43            active_display: Rc::new(TestDisplay::new()),
 44            active_window: Default::default(),
 45            current_clipboard_item: Mutex::new(None),
 46            weak: weak.clone(),
 47        })
 48    }
 49
 50    pub(crate) fn simulate_new_path_selection(
 51        &self,
 52        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
 53    ) {
 54        let (path, tx) = self
 55            .prompts
 56            .borrow_mut()
 57            .new_path
 58            .pop_front()
 59            .expect("no pending new path prompt");
 60        tx.send(select_path(&path)).ok();
 61    }
 62
 63    pub(crate) fn simulate_prompt_answer(&self, response_ix: usize) {
 64        let tx = self
 65            .prompts
 66            .borrow_mut()
 67            .multiple_choice
 68            .pop_front()
 69            .expect("no pending multiple choice prompt");
 70        tx.send(response_ix).ok();
 71    }
 72
 73    pub(crate) fn has_pending_prompt(&self) -> bool {
 74        !self.prompts.borrow().multiple_choice.is_empty()
 75    }
 76
 77    pub(crate) fn prompt(&self) -> oneshot::Receiver<usize> {
 78        let (tx, rx) = oneshot::channel();
 79        self.prompts.borrow_mut().multiple_choice.push_back(tx);
 80        rx
 81    }
 82
 83    pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
 84        let executor = self.foreground_executor().clone();
 85        let previous_window = self.active_window.borrow_mut().take();
 86        *self.active_window.borrow_mut() = window.clone();
 87
 88        executor
 89            .spawn(async move {
 90                if let Some(previous_window) = previous_window {
 91                    if let Some(window) = window.as_ref() {
 92                        if Arc::ptr_eq(&previous_window.0, &window.0) {
 93                            return;
 94                        }
 95                    }
 96                    previous_window.simulate_active_status_change(false);
 97                }
 98                if let Some(window) = window {
 99                    window.simulate_active_status_change(true);
100                }
101            })
102            .detach();
103    }
104
105    pub(crate) fn did_prompt_for_new_path(&self) -> bool {
106        self.prompts.borrow().new_path.len() > 0
107    }
108}
109
110impl Platform for TestPlatform {
111    fn background_executor(&self) -> BackgroundExecutor {
112        self.background_executor.clone()
113    }
114
115    fn foreground_executor(&self) -> ForegroundExecutor {
116        self.foreground_executor.clone()
117    }
118
119    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
120        Arc::new(crate::platform::mac::MacTextSystem::new())
121    }
122
123    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
124        unimplemented!()
125    }
126
127    fn quit(&self) {}
128
129    fn restart(&self) {
130        unimplemented!()
131    }
132
133    fn activate(&self, _ignoring_other_apps: bool) {
134        //
135    }
136
137    fn hide(&self) {
138        unimplemented!()
139    }
140
141    fn hide_other_apps(&self) {
142        unimplemented!()
143    }
144
145    fn unhide_other_apps(&self) {
146        unimplemented!()
147    }
148
149    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
150        vec![self.active_display.clone()]
151    }
152
153    fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
154        self.displays().iter().find(|d| d.id() == id).cloned()
155    }
156
157    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
158        self.active_window
159            .borrow()
160            .as_ref()
161            .map(|window| window.0.lock().handle)
162    }
163
164    fn open_window(
165        &self,
166        handle: AnyWindowHandle,
167        options: WindowOptions,
168    ) -> Box<dyn crate::PlatformWindow> {
169        let window = TestWindow::new(
170            options,
171            handle,
172            self.weak.clone(),
173            self.active_display.clone(),
174        );
175        Box::new(window)
176    }
177
178    fn set_display_link_output_callback(
179        &self,
180        _display_id: DisplayId,
181        mut callback: Box<dyn FnMut(&crate::VideoTimestamp, &crate::VideoTimestamp) + Send>,
182    ) {
183        let timestamp = crate::VideoTimestamp {
184            version: 0,
185            video_time_scale: 0,
186            video_time: 0,
187            host_time: 0,
188            rate_scalar: 0.0,
189            video_refresh_period: 0,
190            smpte_time: crate::SmtpeTime::default(),
191            flags: 0,
192            reserved: 0,
193        };
194        callback(&timestamp, &timestamp)
195    }
196
197    fn start_display_link(&self, _display_id: DisplayId) {}
198
199    fn stop_display_link(&self, _display_id: DisplayId) {}
200
201    fn open_url(&self, _url: &str) {
202        unimplemented!()
203    }
204
205    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
206        unimplemented!()
207    }
208
209    fn prompt_for_paths(
210        &self,
211        _options: crate::PathPromptOptions,
212    ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
213        unimplemented!()
214    }
215
216    fn prompt_for_new_path(
217        &self,
218        directory: &std::path::Path,
219    ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
220        let (tx, rx) = oneshot::channel();
221        self.prompts
222            .borrow_mut()
223            .new_path
224            .push_back((directory.to_path_buf(), tx));
225        rx
226    }
227
228    fn reveal_path(&self, _path: &std::path::Path) {
229        unimplemented!()
230    }
231
232    fn on_become_active(&self, _callback: Box<dyn FnMut()>) {}
233
234    fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
235
236    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
237
238    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
239        unimplemented!()
240    }
241
242    fn on_event(&self, _callback: Box<dyn FnMut(crate::InputEvent) -> bool>) {
243        unimplemented!()
244    }
245
246    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
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]) -> Result<()> {
295        Ok(())
296    }
297
298    fn read_credentials(&self, _url: &str) -> Result<Option<(String, Vec<u8>)>> {
299        Ok(None)
300    }
301
302    fn delete_credentials(&self, _url: &str) -> Result<()> {
303        Ok(())
304    }
305
306    fn double_click_interval(&self) -> std::time::Duration {
307        Duration::from_millis(500)
308    }
309}