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 = "linux")]
126        return Arc::new(crate::platform::linux::LinuxTextSystem::new());
127
128        #[cfg(target_os = "macos")]
129        return Arc::new(crate::platform::mac::MacTextSystem::new());
130
131        #[cfg(target_os = "windows")]
132        return Arc::new(crate::platform::windows::WindowsTextSystem::new());
133    }
134
135    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
136        unimplemented!()
137    }
138
139    fn quit(&self) {}
140
141    fn restart(&self) {
142        unimplemented!()
143    }
144
145    fn activate(&self, _ignoring_other_apps: bool) {
146        //
147    }
148
149    fn hide(&self) {
150        unimplemented!()
151    }
152
153    fn hide_other_apps(&self) {
154        unimplemented!()
155    }
156
157    fn unhide_other_apps(&self) {
158        unimplemented!()
159    }
160
161    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
162        vec![self.active_display.clone()]
163    }
164
165    fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
166        Some(self.active_display.clone())
167    }
168
169    fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
170        self.displays().iter().find(|d| d.id() == id).cloned()
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_become_active(&self, _callback: Box<dyn FnMut()>) {}
230
231    fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
232
233    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
234
235    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
236        unimplemented!()
237    }
238
239    fn on_event(&self, _callback: Box<dyn FnMut(crate::PlatformInput) -> bool>) {
240        unimplemented!()
241    }
242
243    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
244
245    fn add_recent_document(&self, _paths: &Path) {}
246
247    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
248
249    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
250
251    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
252
253    fn os_name(&self) -> &'static str {
254        "test"
255    }
256
257    fn os_version(&self) -> Result<crate::SemanticVersion> {
258        Err(anyhow!("os_version called on TestPlatform"))
259    }
260
261    fn app_version(&self) -> Result<crate::SemanticVersion> {
262        Err(anyhow!("app_version called on TestPlatform"))
263    }
264
265    fn app_path(&self) -> Result<std::path::PathBuf> {
266        unimplemented!()
267    }
268
269    fn local_timezone(&self) -> time::UtcOffset {
270        time::UtcOffset::UTC
271    }
272
273    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
274        unimplemented!()
275    }
276
277    fn set_cursor_style(&self, style: crate::CursorStyle) {
278        *self.active_cursor.lock() = style;
279    }
280
281    fn should_auto_hide_scrollbars(&self) -> bool {
282        false
283    }
284
285    fn write_to_clipboard(&self, item: ClipboardItem) {
286        *self.current_clipboard_item.lock() = Some(item);
287    }
288
289    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
290        self.current_clipboard_item.lock().clone()
291    }
292
293    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
294        Task::ready(Ok(()))
295    }
296
297    fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
298        Task::ready(Ok(None))
299    }
300
301    fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
302        Task::ready(Ok(()))
303    }
304
305    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
306        unimplemented!()
307    }
308}