platform.rs

  1use crate::{
  2    AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId, ForegroundExecutor,
  3    Keymap, Platform, PlatformDisplay, PlatformTextSystem, Scene, TestDisplay, TestWindow,
  4    WindowOptions,
  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    time::Duration,
 16};
 17
 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
106impl Platform for TestPlatform {
107    fn background_executor(&self) -> BackgroundExecutor {
108        self.background_executor.clone()
109    }
110
111    fn foreground_executor(&self) -> ForegroundExecutor {
112        self.foreground_executor.clone()
113    }
114
115    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
116        Arc::new(crate::platform::mac::MacTextSystem::new())
117    }
118
119    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
120        unimplemented!()
121    }
122
123    fn quit(&self) {}
124
125    fn restart(&self) {
126        unimplemented!()
127    }
128
129    fn activate(&self, _ignoring_other_apps: bool) {
130        //
131    }
132
133    fn hide(&self) {
134        unimplemented!()
135    }
136
137    fn hide_other_apps(&self) {
138        unimplemented!()
139    }
140
141    fn unhide_other_apps(&self) {
142        unimplemented!()
143    }
144
145    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
146        vec![self.active_display.clone()]
147    }
148
149    fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
150        self.displays().iter().find(|d| d.id() == id).cloned()
151    }
152
153    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
154        self.active_window
155            .borrow()
156            .as_ref()
157            .map(|window| window.0.lock().handle)
158    }
159
160    fn open_window(
161        &self,
162        handle: AnyWindowHandle,
163        options: WindowOptions,
164        _draw: Box<dyn FnMut() -> Result<Scene>>,
165    ) -> Box<dyn crate::PlatformWindow> {
166        let window = TestWindow::new(
167            options,
168            handle,
169            self.weak.clone(),
170            self.active_display.clone(),
171        );
172        Box::new(window)
173    }
174
175    fn set_display_link_output_callback(
176        &self,
177        _display_id: DisplayId,
178        mut callback: Box<dyn FnMut(&crate::VideoTimestamp, &crate::VideoTimestamp) + Send>,
179    ) {
180        let timestamp = crate::VideoTimestamp {
181            version: 0,
182            video_time_scale: 0,
183            video_time: 0,
184            host_time: 0,
185            rate_scalar: 0.0,
186            video_refresh_period: 0,
187            smpte_time: crate::SmtpeTime::default(),
188            flags: 0,
189            reserved: 0,
190        };
191        callback(&timestamp, &timestamp)
192    }
193
194    fn start_display_link(&self, _display_id: DisplayId) {}
195
196    fn stop_display_link(&self, _display_id: DisplayId) {}
197
198    fn open_url(&self, _url: &str) {
199        unimplemented!()
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::InputEvent) -> bool>) {
240        unimplemented!()
241    }
242
243    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
244
245    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
246
247    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
248
249    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
250
251    fn os_name(&self) -> &'static str {
252        "test"
253    }
254
255    fn os_version(&self) -> Result<crate::SemanticVersion> {
256        Err(anyhow!("os_version called on TestPlatform"))
257    }
258
259    fn app_version(&self) -> Result<crate::SemanticVersion> {
260        Err(anyhow!("app_version called on TestPlatform"))
261    }
262
263    fn app_path(&self) -> Result<std::path::PathBuf> {
264        unimplemented!()
265    }
266
267    fn local_timezone(&self) -> time::UtcOffset {
268        time::UtcOffset::UTC
269    }
270
271    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
272        unimplemented!()
273    }
274
275    fn set_cursor_style(&self, style: crate::CursorStyle) {
276        *self.active_cursor.lock() = style;
277    }
278
279    fn should_auto_hide_scrollbars(&self) -> bool {
280        // todo()
281        true
282    }
283
284    fn write_to_clipboard(&self, item: ClipboardItem) {
285        *self.current_clipboard_item.lock() = Some(item);
286    }
287
288    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
289        self.current_clipboard_item.lock().clone()
290    }
291
292    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Result<()> {
293        Ok(())
294    }
295
296    fn read_credentials(&self, _url: &str) -> Result<Option<(String, Vec<u8>)>> {
297        Ok(None)
298    }
299
300    fn delete_credentials(&self, _url: &str) -> Result<()> {
301        Ok(())
302    }
303
304    fn double_click_interval(&self) -> std::time::Duration {
305        Duration::from_millis(500)
306    }
307}