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