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 #[cfg(target_os = "windows")]
130 todo!("windows")
131 }
132
133 fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
134 unimplemented!()
135 }
136
137 fn quit(&self) {}
138
139 fn restart(&self) {
140 unimplemented!()
141 }
142
143 fn activate(&self, _ignoring_other_apps: bool) {
144 //
145 }
146
147 fn hide(&self) {
148 unimplemented!()
149 }
150
151 fn hide_other_apps(&self) {
152 unimplemented!()
153 }
154
155 fn unhide_other_apps(&self) {
156 unimplemented!()
157 }
158
159 fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
160 vec![self.active_display.clone()]
161 }
162
163 fn display(&self, id: DisplayId) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
164 self.displays().iter().find(|d| d.id() == id).cloned()
165 }
166
167 fn active_window(&self) -> Option<crate::AnyWindowHandle> {
168 self.active_window
169 .borrow()
170 .as_ref()
171 .map(|window| window.0.lock().handle)
172 }
173
174 fn open_window(
175 &self,
176 handle: AnyWindowHandle,
177 options: WindowOptions,
178 ) -> Box<dyn crate::PlatformWindow> {
179 let window = TestWindow::new(
180 options,
181 handle,
182 self.weak.clone(),
183 self.active_display.clone(),
184 );
185 Box::new(window)
186 }
187
188 fn window_appearance(&self) -> WindowAppearance {
189 WindowAppearance::Light
190 }
191
192 fn open_url(&self, url: &str) {
193 *self.opened_url.borrow_mut() = Some(url.to_string())
194 }
195
196 fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
197 unimplemented!()
198 }
199
200 fn prompt_for_paths(
201 &self,
202 _options: crate::PathPromptOptions,
203 ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
204 unimplemented!()
205 }
206
207 fn prompt_for_new_path(
208 &self,
209 directory: &std::path::Path,
210 ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
211 let (tx, rx) = oneshot::channel();
212 self.prompts
213 .borrow_mut()
214 .new_path
215 .push_back((directory.to_path_buf(), tx));
216 rx
217 }
218
219 fn reveal_path(&self, _path: &std::path::Path) {
220 unimplemented!()
221 }
222
223 fn on_become_active(&self, _callback: Box<dyn FnMut()>) {}
224
225 fn on_resign_active(&self, _callback: Box<dyn FnMut()>) {}
226
227 fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
228
229 fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
230 unimplemented!()
231 }
232
233 fn on_event(&self, _callback: Box<dyn FnMut(crate::PlatformInput) -> bool>) {
234 unimplemented!()
235 }
236
237 fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
238
239 fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
240
241 fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
242
243 fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
244
245 fn os_name(&self) -> &'static str {
246 "test"
247 }
248
249 fn os_version(&self) -> Result<crate::SemanticVersion> {
250 Err(anyhow!("os_version called on TestPlatform"))
251 }
252
253 fn app_version(&self) -> Result<crate::SemanticVersion> {
254 Err(anyhow!("app_version called on TestPlatform"))
255 }
256
257 fn app_path(&self) -> Result<std::path::PathBuf> {
258 unimplemented!()
259 }
260
261 fn local_timezone(&self) -> time::UtcOffset {
262 time::UtcOffset::UTC
263 }
264
265 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
266 unimplemented!()
267 }
268
269 fn set_cursor_style(&self, style: crate::CursorStyle) {
270 *self.active_cursor.lock() = style;
271 }
272
273 fn should_auto_hide_scrollbars(&self) -> bool {
274 false
275 }
276
277 fn write_to_clipboard(&self, item: ClipboardItem) {
278 *self.current_clipboard_item.lock() = Some(item);
279 }
280
281 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
282 self.current_clipboard_item.lock().clone()
283 }
284
285 fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
286 Task::ready(Ok(()))
287 }
288
289 fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
290 Task::ready(Ok(None))
291 }
292
293 fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
294 Task::ready(Ok(()))
295 }
296
297 fn double_click_interval(&self) -> std::time::Duration {
298 Duration::from_millis(500)
299 }
300}