1use crate::{
2 AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor, Keymap,
3 Platform, PlatformDisplay, PlatformTextSystem, Task, TestDisplay, TestWindow, WindowAppearance,
4 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().clone_from(&window);
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 active_window(&self) -> Option<crate::AnyWindowHandle> {
172 self.active_window
173 .borrow()
174 .as_ref()
175 .map(|window| window.0.lock().handle)
176 }
177
178 fn open_window(
179 &self,
180 handle: AnyWindowHandle,
181 params: WindowParams,
182 ) -> Box<dyn crate::PlatformWindow> {
183 let window = TestWindow::new(
184 handle,
185 params,
186 self.weak.clone(),
187 self.active_display.clone(),
188 );
189 Box::new(window)
190 }
191
192 fn window_appearance(&self) -> WindowAppearance {
193 WindowAppearance::Light
194 }
195
196 fn open_url(&self, url: &str) {
197 *self.opened_url.borrow_mut() = Some(url.to_string())
198 }
199
200 fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
201 unimplemented!()
202 }
203
204 fn prompt_for_paths(
205 &self,
206 _options: crate::PathPromptOptions,
207 ) -> oneshot::Receiver<Option<Vec<std::path::PathBuf>>> {
208 unimplemented!()
209 }
210
211 fn prompt_for_new_path(
212 &self,
213 directory: &std::path::Path,
214 ) -> oneshot::Receiver<Option<std::path::PathBuf>> {
215 let (tx, rx) = oneshot::channel();
216 self.prompts
217 .borrow_mut()
218 .new_path
219 .push_back((directory.to_path_buf(), tx));
220 rx
221 }
222
223 fn reveal_path(&self, _path: &std::path::Path) {
224 unimplemented!()
225 }
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 set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
234
235 fn add_recent_document(&self, _paths: &Path) {}
236
237 fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
238
239 fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
240
241 fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
242
243 fn os_name(&self) -> &'static str {
244 "test"
245 }
246
247 fn os_version(&self) -> Result<crate::SemanticVersion> {
248 Err(anyhow!("os_version called on TestPlatform"))
249 }
250
251 fn app_version(&self) -> Result<crate::SemanticVersion> {
252 Err(anyhow!("app_version called on TestPlatform"))
253 }
254
255 fn app_path(&self) -> Result<std::path::PathBuf> {
256 unimplemented!()
257 }
258
259 fn local_timezone(&self) -> time::UtcOffset {
260 time::UtcOffset::UTC
261 }
262
263 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
264 unimplemented!()
265 }
266
267 fn set_cursor_style(&self, style: crate::CursorStyle) {
268 *self.active_cursor.lock() = style;
269 }
270
271 fn should_auto_hide_scrollbars(&self) -> bool {
272 false
273 }
274
275 fn write_to_primary(&self, item: ClipboardItem) {
276 *self.current_primary_item.lock() = Some(item);
277 }
278
279 fn write_to_clipboard(&self, item: ClipboardItem) {
280 *self.current_clipboard_item.lock() = Some(item);
281 }
282
283 fn read_from_primary(&self) -> Option<ClipboardItem> {
284 self.current_primary_item.lock().clone()
285 }
286
287 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
288 self.current_clipboard_item.lock().clone()
289 }
290
291 fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
292 Task::ready(Ok(()))
293 }
294
295 fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
296 Task::ready(Ok(None))
297 }
298
299 fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
300 Task::ready(Ok(()))
301 }
302
303 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
304 unimplemented!()
305 }
306}