test.rs

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