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};
 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        tx.send(response_ix).ok();
 73    }
 74
 75    pub(crate) fn has_pending_prompt(&self) -> bool {
 76        !self.prompts.borrow().multiple_choice.is_empty()
 77    }
 78
 79    pub(crate) fn prompt(&self) -> oneshot::Receiver<usize> {
 80        let (tx, rx) = oneshot::channel();
 81        self.prompts.borrow_mut().multiple_choice.push_back(tx);
 82        rx
 83    }
 84
 85    pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
 86        let executor = self.foreground_executor().clone();
 87        let previous_window = self.active_window.borrow_mut().take();
 88        *self.active_window.borrow_mut() = window.clone();
 89
 90        executor
 91            .spawn(async move {
 92                if let Some(previous_window) = previous_window {
 93                    if let Some(window) = window.as_ref() {
 94                        if Arc::ptr_eq(&previous_window.0, &window.0) {
 95                            return;
 96                        }
 97                    }
 98                    previous_window.simulate_active_status_change(false);
 99                }
100                if let Some(window) = window {
101                    window.simulate_active_status_change(true);
102                }
103            })
104            .detach();
105    }
106
107    pub(crate) fn did_prompt_for_new_path(&self) -> bool {
108        self.prompts.borrow().new_path.len() > 0
109    }
110}
111
112impl Platform for TestPlatform {
113    fn background_executor(&self) -> BackgroundExecutor {
114        self.background_executor.clone()
115    }
116
117    fn foreground_executor(&self) -> ForegroundExecutor {
118        self.foreground_executor.clone()
119    }
120
121    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
122        #[cfg(target_os = "linux")]
123        return Arc::new(crate::platform::linux::LinuxTextSystem::new());
124
125        #[cfg(target_os = "macos")]
126        return Arc::new(crate::platform::mac::MacTextSystem::new());
127
128        // todo("windows")
129        #[cfg(target_os = "windows")]
130        unimplemented!()
131    }
132
133    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
134        unimplemented!()
135    }
136
137    fn quit(&self) {}
138
139    fn restart(&self) {
140        unimplemented!()
141    }
142
143    fn activate(&self, _ignoring_other_apps: bool) {
144        //
145    }
146
147    fn hide(&self) {
148        unimplemented!()
149    }
150
151    fn hide_other_apps(&self) {
152        unimplemented!()
153    }
154
155    fn unhide_other_apps(&self) {
156        unimplemented!()
157    }
158
159    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
160        vec![self.active_display.clone()]
161    }
162
163    fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
164        Some(self.active_display.clone())
165    }
166
167    fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
168        self.displays().iter().find(|d| d.id() == id).cloned()
169    }
170
171    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
172        self.active_window
173            .borrow()
174            .as_ref()
175            .map(|window| window.0.lock().handle)
176    }
177
178    fn open_window(
179        &self,
180        handle: AnyWindowHandle,
181        params: WindowParams,
182    ) -> Box<dyn crate::PlatformWindow> {
183        let window = TestWindow::new(
184            handle,
185            params,
186            self.weak.clone(),
187            self.active_display.clone(),
188        );
189        Box::new(window)
190    }
191
192    fn window_appearance(&self) -> WindowAppearance {
193        WindowAppearance::Light
194    }
195
196    fn open_url(&self, url: &str) {
197        *self.opened_url.borrow_mut() = Some(url.to_string())
198    }
199
200    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
201        unimplemented!()
202    }
203
204    fn prompt_for_paths(
205        &self,
206        _options: crate::PathPromptOptions,
207    ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
208        unimplemented!()
209    }
210
211    fn prompt_for_new_path(
212        &self,
213        directory: &std::path::Path,
214    ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
215        let (tx, rx) = oneshot::channel();
216        self.prompts
217            .borrow_mut()
218            .new_path
219            .push_back((directory.to_path_buf(), tx));
220        rx
221    }
222
223    fn reveal_path(&self, _path: &std::path::Path) {
224        unimplemented!()
225    }
226
227    fn on_become_active(&self, _callback: Box<dyn FnMut()>) {}
228
229    fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
230
231    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
232
233    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
234        unimplemented!()
235    }
236
237    fn on_event(&self, _callback: Box<dyn FnMut(crate::PlatformInput) -> bool>) {
238        unimplemented!()
239    }
240
241    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
242
243    fn add_recent_documents(&self, _paths: &[PathBuf]) {}
244
245    fn clear_recent_documents(&self) {}
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}