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