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