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: Arc<Mutex<Option<AnyWindowHandle>>>,
 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
 84// todo!("implement out what our tests needed in GPUI 1")
 85impl Platform for TestPlatform {
 86    fn background_executor(&self) -> BackgroundExecutor {
 87        self.background_executor.clone()
 88    }
 89
 90    fn foreground_executor(&self) -> ForegroundExecutor {
 91        self.foreground_executor.clone()
 92    }
 93
 94    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 95        Arc::new(crate::platform::mac::MacTextSystem::new())
 96    }
 97
 98    fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
 99        unimplemented!()
100    }
101
102    fn quit(&self) {}
103
104    fn restart(&self) {
105        unimplemented!()
106    }
107
108    fn activate(&self, _ignoring_other_apps: bool) {
109        //
110    }
111
112    fn hide(&self) {
113        unimplemented!()
114    }
115
116    fn hide_other_apps(&self) {
117        unimplemented!()
118    }
119
120    fn unhide_other_apps(&self) {
121        unimplemented!()
122    }
123
124    fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
125        vec![self.active_display.clone()]
126    }
127
128    fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
129        self.displays().iter().find(|d| d.id() == id).cloned()
130    }
131
132    fn active_window(&self) -> Option<crate::AnyWindowHandle> {
133        self.active_window.lock().clone()
134    }
135
136    fn open_window(
137        &self,
138        handle: AnyWindowHandle,
139        options: WindowOptions,
140        _draw: Box<dyn FnMut() -> Result<Scene>>,
141    ) -> Box<dyn crate::PlatformWindow> {
142        *self.active_window.lock() = Some(handle);
143        Box::new(TestWindow::new(
144            options,
145            handle,
146            self.weak.clone(),
147            self.active_display.clone(),
148        ))
149    }
150
151    fn set_display_link_output_callback(
152        &self,
153        _display_id: DisplayId,
154        mut callback: Box<dyn FnMut(&crate::VideoTimestamp, &crate::VideoTimestamp) + Send>,
155    ) {
156        let timestamp = crate::VideoTimestamp {
157            version: 0,
158            video_time_scale: 0,
159            video_time: 0,
160            host_time: 0,
161            rate_scalar: 0.0,
162            video_refresh_period: 0,
163            smpte_time: crate::SmtpeTime::default(),
164            flags: 0,
165            reserved: 0,
166        };
167        callback(&timestamp, &timestamp)
168    }
169
170    fn start_display_link(&self, _display_id: DisplayId) {}
171
172    fn stop_display_link(&self, _display_id: DisplayId) {}
173
174    fn open_url(&self, _url: &str) {
175        unimplemented!()
176    }
177
178    fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
179        unimplemented!()
180    }
181
182    fn prompt_for_paths(
183        &self,
184        _options: crate::PathPromptOptions,
185    ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
186        unimplemented!()
187    }
188
189    fn prompt_for_new_path(
190        &self,
191        directory: &std::path::Path,
192    ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
193        let (tx, rx) = oneshot::channel();
194        self.prompts
195            .borrow_mut()
196            .new_path
197            .push_back((directory.to_path_buf(), tx));
198        rx
199    }
200
201    fn reveal_path(&self, _path: &std::path::Path) {
202        unimplemented!()
203    }
204
205    fn on_become_active(&self, _callback: Box<dyn FnMut()>) {}
206
207    fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
208
209    fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
210
211    fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
212        unimplemented!()
213    }
214
215    fn on_event(&self, _callback: Box<dyn FnMut(crate::InputEvent) -> bool>) {
216        unimplemented!()
217    }
218
219    fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
220
221    fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
222
223    fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
224
225    fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
226
227    fn os_name(&self) -> &'static str {
228        "test"
229    }
230
231    fn os_version(&self) -> Result<crate::SemanticVersion> {
232        Err(anyhow!("os_version called on TestPlatform"))
233    }
234
235    fn app_version(&self) -> Result<crate::SemanticVersion> {
236        Err(anyhow!("app_version called on TestPlatform"))
237    }
238
239    fn app_path(&self) -> Result<std::path::PathBuf> {
240        unimplemented!()
241    }
242
243    fn local_timezone(&self) -> time::UtcOffset {
244        unimplemented!()
245    }
246
247    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
248        unimplemented!()
249    }
250
251    fn set_cursor_style(&self, style: crate::CursorStyle) {
252        *self.active_cursor.lock() = style;
253    }
254
255    fn should_auto_hide_scrollbars(&self) -> bool {
256        // todo()
257        true
258    }
259
260    fn write_to_clipboard(&self, item: ClipboardItem) {
261        *self.current_clipboard_item.lock() = Some(item);
262    }
263
264    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
265        self.current_clipboard_item.lock().clone()
266    }
267
268    fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Result<()> {
269        Ok(())
270    }
271
272    fn read_credentials(&self, _url: &str) -> Result<Option<(String, Vec<u8>)>> {
273        Ok(None)
274    }
275
276    fn delete_credentials(&self, _url: &str) -> Result<()> {
277        Ok(())
278    }
279
280    fn double_click_interval(&self) -> std::time::Duration {
281        Duration::from_millis(500)
282    }
283}