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