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
18/// TestPlatform implements the Platform trait for use in tests.
19pub struct TestPlatform {
20 background_executor: BackgroundExecutor,
21 foreground_executor: ForegroundExecutor,
22
23 pub(crate) active_window: RefCell<Option<TestWindow>>,
24 active_display: Rc<dyn PlatformDisplay>,
25 active_cursor: Mutex<CursorStyle>,
26 current_clipboard_item: Mutex<Option<ClipboardItem>>,
27 pub(crate) prompts: RefCell<TestPrompts>,
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 })
49 }
50
51 pub(crate) fn simulate_new_path_selection(
52 &self,
53 select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
54 ) {
55 let (path, tx) = self
56 .prompts
57 .borrow_mut()
58 .new_path
59 .pop_front()
60 .expect("no pending new path prompt");
61 tx.send(select_path(&path)).ok();
62 }
63
64 pub(crate) fn simulate_prompt_answer(&self, response_ix: usize) {
65 let tx = self
66 .prompts
67 .borrow_mut()
68 .multiple_choice
69 .pop_front()
70 .expect("no pending multiple choice prompt");
71 tx.send(response_ix).ok();
72 }
73
74 pub(crate) fn has_pending_prompt(&self) -> bool {
75 !self.prompts.borrow().multiple_choice.is_empty()
76 }
77
78 pub(crate) fn prompt(&self) -> oneshot::Receiver<usize> {
79 let (tx, rx) = oneshot::channel();
80 self.prompts.borrow_mut().multiple_choice.push_back(tx);
81 rx
82 }
83
84 pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
85 let executor = self.foreground_executor().clone();
86 let previous_window = self.active_window.borrow_mut().take();
87 *self.active_window.borrow_mut() = window.clone();
88
89 executor
90 .spawn(async move {
91 if let Some(previous_window) = previous_window {
92 if let Some(window) = window.as_ref() {
93 if Arc::ptr_eq(&previous_window.0, &window.0) {
94 return;
95 }
96 }
97 previous_window.simulate_active_status_change(false);
98 }
99 if let Some(window) = window {
100 window.simulate_active_status_change(true);
101 }
102 })
103 .detach();
104 }
105
106 pub(crate) fn did_prompt_for_new_path(&self) -> bool {
107 self.prompts.borrow().new_path.len() > 0
108 }
109}
110
111impl Platform for TestPlatform {
112 fn background_executor(&self) -> BackgroundExecutor {
113 self.background_executor.clone()
114 }
115
116 fn foreground_executor(&self) -> ForegroundExecutor {
117 self.foreground_executor.clone()
118 }
119
120 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
121 Arc::new(crate::platform::mac::MacTextSystem::new())
122 }
123
124 fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
125 unimplemented!()
126 }
127
128 fn quit(&self) {}
129
130 fn restart(&self) {
131 unimplemented!()
132 }
133
134 fn activate(&self, _ignoring_other_apps: bool) {
135 //
136 }
137
138 fn hide(&self) {
139 unimplemented!()
140 }
141
142 fn hide_other_apps(&self) {
143 unimplemented!()
144 }
145
146 fn unhide_other_apps(&self) {
147 unimplemented!()
148 }
149
150 fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
151 vec![self.active_display.clone()]
152 }
153
154 fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
155 self.displays().iter().find(|d| d.id() == id).cloned()
156 }
157
158 fn active_window(&self) -> Option<crate::AnyWindowHandle> {
159 self.active_window
160 .borrow()
161 .as_ref()
162 .map(|window| window.0.lock().handle)
163 }
164
165 fn open_window(
166 &self,
167 handle: AnyWindowHandle,
168 options: WindowOptions,
169 _draw: Box<dyn FnMut() -> Result<Scene>>,
170 ) -> Box<dyn crate::PlatformWindow> {
171 let window = TestWindow::new(
172 options,
173 handle,
174 self.weak.clone(),
175 self.active_display.clone(),
176 );
177 Box::new(window)
178 }
179
180 fn set_display_link_output_callback(
181 &self,
182 _display_id: DisplayId,
183 mut callback: Box<dyn FnMut(&crate::VideoTimestamp, &crate::VideoTimestamp) + Send>,
184 ) {
185 let timestamp = crate::VideoTimestamp {
186 version: 0,
187 video_time_scale: 0,
188 video_time: 0,
189 host_time: 0,
190 rate_scalar: 0.0,
191 video_refresh_period: 0,
192 smpte_time: crate::SmtpeTime::default(),
193 flags: 0,
194 reserved: 0,
195 };
196 callback(×tamp, ×tamp)
197 }
198
199 fn start_display_link(&self, _display_id: DisplayId) {}
200
201 fn stop_display_link(&self, _display_id: DisplayId) {}
202
203 fn open_url(&self, _url: &str) {
204 unimplemented!()
205 }
206
207 fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
208 unimplemented!()
209 }
210
211 fn prompt_for_paths(
212 &self,
213 _options: crate::PathPromptOptions,
214 ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
215 unimplemented!()
216 }
217
218 fn prompt_for_new_path(
219 &self,
220 directory: &std::path::Path,
221 ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
222 let (tx, rx) = oneshot::channel();
223 self.prompts
224 .borrow_mut()
225 .new_path
226 .push_back((directory.to_path_buf(), tx));
227 rx
228 }
229
230 fn reveal_path(&self, _path: &std::path::Path) {
231 unimplemented!()
232 }
233
234 fn on_become_active(&self, _callback: Box<dyn FnMut()>) {}
235
236 fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
237
238 fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
239
240 fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
241 unimplemented!()
242 }
243
244 fn on_event(&self, _callback: Box<dyn FnMut(crate::InputEvent) -> bool>) {
245 unimplemented!()
246 }
247
248 fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
249
250 fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
251
252 fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
253
254 fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
255
256 fn os_name(&self) -> &'static str {
257 "test"
258 }
259
260 fn os_version(&self) -> Result<crate::SemanticVersion> {
261 Err(anyhow!("os_version called on TestPlatform"))
262 }
263
264 fn app_version(&self) -> Result<crate::SemanticVersion> {
265 Err(anyhow!("app_version called on TestPlatform"))
266 }
267
268 fn app_path(&self) -> Result<std::path::PathBuf> {
269 unimplemented!()
270 }
271
272 fn local_timezone(&self) -> time::UtcOffset {
273 time::UtcOffset::UTC
274 }
275
276 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
277 unimplemented!()
278 }
279
280 fn set_cursor_style(&self, style: crate::CursorStyle) {
281 *self.active_cursor.lock() = style;
282 }
283
284 fn should_auto_hide_scrollbars(&self) -> bool {
285 false
286 }
287
288 fn write_to_clipboard(&self, item: ClipboardItem) {
289 *self.current_clipboard_item.lock() = Some(item);
290 }
291
292 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
293 self.current_clipboard_item.lock().clone()
294 }
295
296 fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Result<()> {
297 Ok(())
298 }
299
300 fn read_credentials(&self, _url: &str) -> Result<Option<(String, Vec<u8>)>> {
301 Ok(None)
302 }
303
304 fn delete_credentials(&self, _url: &str) -> Result<()> {
305 Ok(())
306 }
307
308 fn double_click_interval(&self) -> std::time::Duration {
309 Duration::from_millis(500)
310 }
311}