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(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    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() + Send>,
182    ) {
183        callback()
184    }
185
186    fn start_display_link(&self, _display_id: DisplayId) {}
187
188    fn stop_display_link(&self, _display_id: DisplayId) {}
189
190    fn open_url(&self, _url: &str) {
191        unimplemented!()
192    }
193
194    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
195        unimplemented!()
196    }
197
198    fn prompt_for_paths(
199        &self,
200        _options: crate::PathPromptOptions,
201    ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
202        unimplemented!()
203    }
204
205    fn prompt_for_new_path(
206        &self,
207        directory: &std::path::Path,
208    ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
209        let (tx, rx) = oneshot::channel();
210        self.prompts
211            .borrow_mut()
212            .new_path
213            .push_back((directory.to_path_buf(), tx));
214        rx
215    }
216
217    fn reveal_path(&self, _path: &std::path::Path) {
218        unimplemented!()
219    }
220
221    fn on_become_active(&self, _callback: Box<dyn FnMut()>) {}
222
223    fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
224
225    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
226
227    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
228        unimplemented!()
229    }
230
231    fn on_event(&self, _callback: Box<dyn FnMut(crate::PlatformInput) -> bool>) {
232        unimplemented!()
233    }
234
235    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
236
237    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
238
239    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
240
241    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
242
243    fn os_name(&self) -> &'static str {
244        "test"
245    }
246
247    fn os_version(&self) -> Result<crate::SemanticVersion> {
248        Err(anyhow!("os_version called on TestPlatform"))
249    }
250
251    fn app_version(&self) -> Result<crate::SemanticVersion> {
252        Err(anyhow!("app_version called on TestPlatform"))
253    }
254
255    fn app_path(&self) -> Result<std::path::PathBuf> {
256        unimplemented!()
257    }
258
259    fn local_timezone(&self) -> time::UtcOffset {
260        time::UtcOffset::UTC
261    }
262
263    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
264        unimplemented!()
265    }
266
267    fn set_cursor_style(&self, style: crate::CursorStyle) {
268        *self.active_cursor.lock() = style;
269    }
270
271    fn should_auto_hide_scrollbars(&self) -> bool {
272        false
273    }
274
275    fn write_to_clipboard(&self, item: ClipboardItem) {
276        *self.current_clipboard_item.lock() = Some(item);
277    }
278
279    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
280        self.current_clipboard_item.lock().clone()
281    }
282
283    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Result<()> {
284        Ok(())
285    }
286
287    fn read_credentials(&self, _url: &str) -> Result<Option<(String, Vec<u8>)>> {
288        Ok(None)
289    }
290
291    fn delete_credentials(&self, _url: &str) -> Result<()> {
292        Ok(())
293    }
294
295    fn double_click_interval(&self) -> std::time::Duration {
296        Duration::from_millis(500)
297    }
298}