test.rs

  1use super::{AppVersion, CursorStyle, WindowBounds};
  2use crate::{
  3    geometry::vector::{vec2f, Vector2F},
  4    keymap, Action, ClipboardItem,
  5};
  6use anyhow::{anyhow, Result};
  7use collections::VecDeque;
  8use parking_lot::Mutex;
  9use postage::oneshot;
 10use std::{
 11    any::Any,
 12    cell::RefCell,
 13    path::{Path, PathBuf},
 14    rc::Rc,
 15    sync::Arc,
 16};
 17use time::UtcOffset;
 18
 19pub struct Platform {
 20    dispatcher: Arc<dyn super::Dispatcher>,
 21    fonts: Arc<dyn super::FontSystem>,
 22    current_clipboard_item: Mutex<Option<ClipboardItem>>,
 23    cursor: Mutex<CursorStyle>,
 24}
 25
 26#[derive(Default)]
 27pub struct ForegroundPlatform {
 28    last_prompt_for_new_path_args: RefCell<Option<(PathBuf, oneshot::Sender<Option<PathBuf>>)>>,
 29}
 30
 31struct Dispatcher;
 32
 33pub struct Window {
 34    size: Vector2F,
 35    scale_factor: f32,
 36    current_scene: Option<crate::Scene>,
 37    event_handlers: Vec<Box<dyn FnMut(super::Event) -> bool>>,
 38    resize_handlers: Vec<Box<dyn FnMut()>>,
 39    close_handlers: Vec<Box<dyn FnOnce()>>,
 40    pub(crate) should_close_handler: Option<Box<dyn FnMut() -> bool>>,
 41    pub(crate) title: Option<String>,
 42    pub(crate) edited: bool,
 43    pub(crate) pending_prompts: RefCell<VecDeque<oneshot::Sender<usize>>>,
 44}
 45
 46#[cfg(any(test, feature = "test-support"))]
 47impl ForegroundPlatform {
 48    pub(crate) fn simulate_new_path_selection(
 49        &self,
 50        result: impl FnOnce(PathBuf) -> Option<PathBuf>,
 51    ) {
 52        let (dir_path, mut done_tx) = self
 53            .last_prompt_for_new_path_args
 54            .take()
 55            .expect("prompt_for_new_path was not called");
 56        let _ = postage::sink::Sink::try_send(&mut done_tx, result(dir_path));
 57    }
 58
 59    pub(crate) fn did_prompt_for_new_path(&self) -> bool {
 60        self.last_prompt_for_new_path_args.borrow().is_some()
 61    }
 62}
 63
 64impl super::ForegroundPlatform for ForegroundPlatform {
 65    fn on_become_active(&self, _: Box<dyn FnMut()>) {}
 66
 67    fn on_resign_active(&self, _: Box<dyn FnMut()>) {}
 68
 69    fn on_quit(&self, _: Box<dyn FnMut()>) {}
 70
 71    fn on_event(&self, _: Box<dyn FnMut(crate::Event) -> bool>) {}
 72
 73    fn on_open_urls(&self, _: Box<dyn FnMut(Vec<String>)>) {}
 74
 75    fn run(&self, _on_finish_launching: Box<dyn FnOnce() -> ()>) {
 76        unimplemented!()
 77    }
 78
 79    fn on_menu_command(&self, _: Box<dyn FnMut(&dyn Action)>) {}
 80    fn on_validate_menu_command(&self, _: Box<dyn FnMut(&dyn Action) -> bool>) {}
 81    fn on_will_open_menu(&self, _: Box<dyn FnMut()>) {}
 82    fn set_menus(&self, _: Vec<crate::Menu>, _: &keymap::Matcher) {}
 83
 84    fn prompt_for_paths(
 85        &self,
 86        _: super::PathPromptOptions,
 87    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 88        let (_done_tx, done_rx) = oneshot::channel();
 89        done_rx
 90    }
 91
 92    fn prompt_for_new_path(&self, path: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 93        let (done_tx, done_rx) = oneshot::channel();
 94        *self.last_prompt_for_new_path_args.borrow_mut() = Some((path.to_path_buf(), done_tx));
 95        done_rx
 96    }
 97}
 98
 99impl Platform {
100    fn new() -> Self {
101        Self {
102            dispatcher: Arc::new(Dispatcher),
103            fonts: Arc::new(super::current::FontSystem::new()),
104            current_clipboard_item: Default::default(),
105            cursor: Mutex::new(CursorStyle::Arrow),
106        }
107    }
108}
109
110impl super::Platform for Platform {
111    fn dispatcher(&self) -> Arc<dyn super::Dispatcher> {
112        self.dispatcher.clone()
113    }
114
115    fn fonts(&self) -> std::sync::Arc<dyn super::FontSystem> {
116        self.fonts.clone()
117    }
118
119    fn activate(&self, _ignoring_other_apps: bool) {}
120
121    fn open_window(
122        &self,
123        _: usize,
124        options: super::WindowOptions,
125        _executor: Rc<super::executor::Foreground>,
126    ) -> Box<dyn super::Window> {
127        Box::new(Window::new(match options.bounds {
128            WindowBounds::Maximized => vec2f(1024., 768.),
129            WindowBounds::Fixed(rect) => rect.size(),
130        }))
131    }
132
133    fn key_window_id(&self) -> Option<usize> {
134        None
135    }
136
137    fn quit(&self) {}
138
139    fn write_to_clipboard(&self, item: ClipboardItem) {
140        *self.current_clipboard_item.lock() = Some(item);
141    }
142
143    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
144        self.current_clipboard_item.lock().clone()
145    }
146
147    fn open_url(&self, _: &str) {}
148
149    fn write_credentials(&self, _: &str, _: &str, _: &[u8]) -> Result<()> {
150        Ok(())
151    }
152
153    fn read_credentials(&self, _: &str) -> Result<Option<(String, Vec<u8>)>> {
154        Ok(None)
155    }
156
157    fn delete_credentials(&self, _: &str) -> Result<()> {
158        Ok(())
159    }
160
161    fn set_cursor_style(&self, style: CursorStyle) {
162        *self.cursor.lock() = style;
163    }
164
165    fn local_timezone(&self) -> UtcOffset {
166        UtcOffset::UTC
167    }
168
169    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
170        Err(anyhow!("app not running inside a bundle"))
171    }
172
173    fn app_path(&self) -> Result<PathBuf> {
174        Err(anyhow!("app not running inside a bundle"))
175    }
176
177    fn app_version(&self) -> Result<AppVersion> {
178        Ok(AppVersion {
179            major: 1,
180            minor: 0,
181            patch: 0,
182        })
183    }
184}
185
186impl Window {
187    fn new(size: Vector2F) -> Self {
188        Self {
189            size,
190            event_handlers: Default::default(),
191            resize_handlers: Default::default(),
192            close_handlers: Default::default(),
193            should_close_handler: Default::default(),
194            scale_factor: 1.0,
195            current_scene: None,
196            title: None,
197            edited: false,
198            pending_prompts: Default::default(),
199        }
200    }
201
202    pub fn title(&self) -> Option<String> {
203        self.title.clone()
204    }
205}
206
207impl super::Dispatcher for Dispatcher {
208    fn is_main_thread(&self) -> bool {
209        true
210    }
211
212    fn run_on_main_thread(&self, task: async_task::Runnable) {
213        task.run();
214    }
215}
216
217impl super::WindowContext for Window {
218    fn size(&self) -> Vector2F {
219        self.size
220    }
221
222    fn scale_factor(&self) -> f32 {
223        self.scale_factor
224    }
225
226    fn titlebar_height(&self) -> f32 {
227        24.
228    }
229
230    fn present_scene(&mut self, scene: crate::Scene) {
231        self.current_scene = Some(scene);
232    }
233}
234
235impl super::Window for Window {
236    fn as_any_mut(&mut self) -> &mut dyn Any {
237        self
238    }
239
240    fn on_event(&mut self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
241        self.event_handlers.push(callback);
242    }
243
244    fn on_active_status_change(&mut self, _: Box<dyn FnMut(bool)>) {}
245
246    fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
247        self.resize_handlers.push(callback);
248    }
249
250    fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
251        self.close_handlers.push(callback);
252    }
253
254    fn prompt(&self, _: crate::PromptLevel, _: &str, _: &[&str]) -> oneshot::Receiver<usize> {
255        let (done_tx, done_rx) = oneshot::channel();
256        self.pending_prompts.borrow_mut().push_back(done_tx);
257        done_rx
258    }
259
260    fn activate(&self) {}
261
262    fn set_title(&mut self, title: &str) {
263        self.title = Some(title.to_string())
264    }
265
266    fn set_edited(&mut self, edited: bool) {
267        self.edited = edited;
268    }
269
270    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
271        self.should_close_handler = Some(callback);
272    }
273}
274
275pub fn platform() -> Platform {
276    Platform::new()
277}
278
279pub fn foreground_platform() -> ForegroundPlatform {
280    ForegroundPlatform::default()
281}