Skip to repository content604 lines · 18.6 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T07:59:51.059Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
platform.rs
1use crate::{
2 AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DevicePixels,
3 DummyKeyboardMapper, ForegroundExecutor, Keymap, NoopTextSystem, PathPromptOptions, Platform,
4 PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout, PlatformKeyboardMapper,
5 PlatformTextSystem, PromptButton, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream,
6 SharedString, SourceMetadata, SystemNotification, SystemNotificationResponse, Task,
7 TestDisplay, TestWindow, ThermalState, WindowAppearance, WindowParams, size,
8};
9use anyhow::Result;
10use collections::VecDeque;
11use futures::channel::oneshot;
12use parking_lot::Mutex;
13use std::{
14 cell::RefCell,
15 path::{Path, PathBuf},
16 rc::{Rc, Weak},
17 sync::Arc,
18};
19
20/// TestPlatform implements the Platform trait for use in tests.
21pub(crate) struct TestPlatform {
22 background_executor: BackgroundExecutor,
23 foreground_executor: ForegroundExecutor,
24
25 pub(crate) active_window: RefCell<Option<TestWindow>>,
26 active_display: Rc<dyn PlatformDisplay>,
27 active_cursor: Mutex<CursorStyle>,
28 current_clipboard_item: Mutex<Option<ClipboardItem>>,
29 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
30 current_primary_item: Mutex<Option<ClipboardItem>>,
31 #[cfg(target_os = "macos")]
32 current_find_pasteboard_item: Mutex<Option<ClipboardItem>>,
33 pub(crate) prompts: RefCell<TestPrompts>,
34 screen_capture_sources: RefCell<Vec<TestScreenCaptureSource>>,
35 pub opened_url: RefCell<Option<String>>,
36 pub(crate) system_notifications: RefCell<TestSystemNotifications>,
37 pub text_system: Arc<dyn PlatformTextSystem>,
38 pub expect_restart: RefCell<Option<oneshot::Sender<Option<PathBuf>>>>,
39 headless_renderer_factory: Option<Box<dyn Fn() -> Option<Box<dyn PlatformHeadlessRenderer>>>>,
40 weak: Weak<Self>,
41}
42
43#[derive(Clone)]
44/// A fake screen capture source, used for testing.
45pub struct TestScreenCaptureSource {}
46
47/// A fake screen capture stream, used for testing.
48pub struct TestScreenCaptureStream {}
49
50impl ScreenCaptureSource for TestScreenCaptureSource {
51 fn metadata(&self) -> Result<SourceMetadata> {
52 Ok(SourceMetadata {
53 id: 0,
54 is_main: None,
55 label: None,
56 resolution: size(DevicePixels(1), DevicePixels(1)),
57 })
58 }
59
60 fn stream(
61 &self,
62 _foreground_executor: &ForegroundExecutor,
63 _frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
64 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {
65 let (mut tx, rx) = oneshot::channel();
66 let stream = TestScreenCaptureStream {};
67 tx.send(Ok(Box::new(stream) as Box<dyn ScreenCaptureStream>))
68 .ok();
69 rx
70 }
71}
72
73impl ScreenCaptureStream for TestScreenCaptureStream {
74 fn metadata(&self) -> Result<SourceMetadata> {
75 TestScreenCaptureSource {}.metadata()
76 }
77}
78
79struct TestPrompt {
80 msg: String,
81 detail: Option<String>,
82 answers: Vec<String>,
83 tx: oneshot::Sender<usize>,
84}
85
86#[derive(Default)]
87pub(crate) struct TestSystemNotifications {
88 pub(crate) app_identity: Option<(SharedString, SharedString)>,
89 pub(crate) shown: Vec<SystemNotification>,
90 pub(crate) delivered: Vec<SystemNotification>,
91 pub(crate) dismissed: Vec<SharedString>,
92 response_callback: Option<Box<dyn FnMut(SystemNotificationResponse)>>,
93}
94
95#[derive(Default)]
96pub(crate) struct TestPrompts {
97 multiple_choice: VecDeque<TestPrompt>,
98 new_path: VecDeque<(PathBuf, oneshot::Sender<Result<Option<PathBuf>>>)>,
99 paths: VecDeque<(
100 PathPromptOptions,
101 oneshot::Sender<Result<Option<Vec<PathBuf>>>>,
102 )>,
103}
104
105impl TestPlatform {
106 pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Rc<Self> {
107 Self::with_platform(
108 executor,
109 foreground_executor,
110 Arc::new(NoopTextSystem),
111 None,
112 )
113 }
114
115 pub fn with_text_system(
116 executor: BackgroundExecutor,
117 foreground_executor: ForegroundExecutor,
118 text_system: Arc<dyn PlatformTextSystem>,
119 ) -> Rc<Self> {
120 Self::with_platform(executor, foreground_executor, text_system, None)
121 }
122
123 pub fn with_platform(
124 executor: BackgroundExecutor,
125 foreground_executor: ForegroundExecutor,
126 text_system: Arc<dyn PlatformTextSystem>,
127 headless_renderer_factory: Option<
128 Box<dyn Fn() -> Option<Box<dyn PlatformHeadlessRenderer>>>,
129 >,
130 ) -> Rc<Self> {
131 Rc::new_cyclic(|weak| TestPlatform {
132 background_executor: executor,
133 foreground_executor,
134 prompts: Default::default(),
135 screen_capture_sources: Default::default(),
136 active_cursor: Default::default(),
137 active_display: Rc::new(TestDisplay::new()),
138 active_window: Default::default(),
139 expect_restart: Default::default(),
140 current_clipboard_item: Mutex::new(None),
141 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
142 current_primary_item: Mutex::new(None),
143 #[cfg(target_os = "macos")]
144 current_find_pasteboard_item: Mutex::new(None),
145 weak: weak.clone(),
146 opened_url: Default::default(),
147 system_notifications: Default::default(),
148 text_system,
149 headless_renderer_factory,
150 })
151 }
152
153 pub(crate) fn simulate_new_path_selection(
154 &self,
155 select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
156 ) {
157 let (path, tx) = self
158 .prompts
159 .borrow_mut()
160 .new_path
161 .pop_front()
162 .expect("no pending new path prompt");
163 tx.send(Ok(select_path(&path))).ok();
164 }
165
166 pub(crate) fn simulate_path_prompt_response(
167 &self,
168 select_paths: impl FnOnce(&PathPromptOptions) -> Option<Vec<std::path::PathBuf>>,
169 ) {
170 let (options, tx) = self
171 .prompts
172 .borrow_mut()
173 .paths
174 .pop_front()
175 .expect("no pending paths prompt");
176 let selection = select_paths(&options);
177 if let Some(paths) = &selection
178 && !options.multiple
179 && paths.len() > 1
180 {
181 panic!(
182 "selected {} paths for a prompt that does not allow multiple selection",
183 paths.len()
184 );
185 }
186 tx.send(Ok(selection)).ok();
187 }
188
189 pub(crate) fn did_prompt_for_paths(&self) -> bool {
190 !self.prompts.borrow().paths.is_empty()
191 }
192
193 #[track_caller]
194 pub(crate) fn simulate_prompt_answer(&self, response: &str) {
195 let prompt = self
196 .prompts
197 .borrow_mut()
198 .multiple_choice
199 .pop_front()
200 .expect("no pending multiple choice prompt");
201 let Some(ix) = prompt.answers.iter().position(|a| a == response) else {
202 panic!(
203 "PROMPT: {}\n{:?}\n{:?}\nCannot respond with {}",
204 prompt.msg, prompt.detail, prompt.answers, response
205 )
206 };
207 prompt.tx.send(ix).ok();
208 }
209
210 pub(crate) fn has_pending_prompt(&self) -> bool {
211 !self.prompts.borrow().multiple_choice.is_empty()
212 }
213
214 pub(crate) fn pending_prompt(&self) -> Option<(String, String)> {
215 let prompts = self.prompts.borrow();
216 let prompt = prompts.multiple_choice.front()?;
217 Some((
218 prompt.msg.clone(),
219 prompt.detail.clone().unwrap_or_default(),
220 ))
221 }
222
223 pub(crate) fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) {
224 *self.screen_capture_sources.borrow_mut() = sources;
225 }
226
227 pub(crate) fn prompt(
228 &self,
229 msg: &str,
230 detail: Option<&str>,
231 answers: &[PromptButton],
232 ) -> oneshot::Receiver<usize> {
233 let (tx, rx) = oneshot::channel();
234 let answers: Vec<String> = answers.iter().map(|s| s.label().to_string()).collect();
235 self.prompts
236 .borrow_mut()
237 .multiple_choice
238 .push_back(TestPrompt {
239 msg: msg.to_string(),
240 detail: detail.map(|s| s.to_string()),
241 answers,
242 tx,
243 });
244 rx
245 }
246
247 pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
248 let executor = self.foreground_executor();
249 let previous_window = self.active_window.borrow_mut().take();
250 self.active_window.borrow_mut().clone_from(&window);
251
252 executor
253 .spawn(async move {
254 if let Some(previous_window) = previous_window {
255 if let Some(window) = window.as_ref()
256 && Rc::ptr_eq(&previous_window.0, &window.0)
257 {
258 return;
259 }
260 previous_window.simulate_active_status_change(false);
261 }
262 if let Some(window) = window {
263 window.simulate_active_status_change(true);
264 }
265 })
266 .detach();
267 }
268
269 pub(crate) fn did_prompt_for_new_path(&self) -> bool {
270 !self.prompts.borrow().new_path.is_empty()
271 }
272
273 pub(crate) fn app_identity(&self) -> Option<(SharedString, SharedString)> {
274 self.system_notifications.borrow().app_identity.clone()
275 }
276
277 pub(crate) fn shown_system_notifications(&self) -> Vec<SystemNotification> {
278 self.system_notifications.borrow().shown.clone()
279 }
280
281 pub(crate) fn delivered_system_notifications(&self) -> Vec<SystemNotification> {
282 self.system_notifications.borrow().delivered.clone()
283 }
284
285 pub(crate) fn dismissed_system_notifications(&self) -> Vec<SharedString> {
286 self.system_notifications.borrow().dismissed.clone()
287 }
288
289 pub(crate) fn simulate_system_notification_response(
290 &self,
291 response: SystemNotificationResponse,
292 ) {
293 let callback = self
294 .system_notifications
295 .borrow_mut()
296 .response_callback
297 .take();
298 if let Some(mut callback) = callback {
299 callback(response);
300 self.system_notifications
301 .borrow_mut()
302 .response_callback
303 .get_or_insert(callback);
304 }
305 }
306}
307
308impl Platform for TestPlatform {
309 fn background_executor(&self) -> BackgroundExecutor {
310 self.background_executor.clone()
311 }
312
313 fn foreground_executor(&self) -> ForegroundExecutor {
314 self.foreground_executor.clone()
315 }
316
317 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
318 self.text_system.clone()
319 }
320
321 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
322 Box::new(TestKeyboardLayout)
323 }
324
325 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
326 Rc::new(DummyKeyboardMapper)
327 }
328
329 fn on_keyboard_layout_change(&self, _: Box<dyn FnMut()>) {}
330
331 fn on_thermal_state_change(&self, _: Box<dyn FnMut()>) {}
332
333 fn thermal_state(&self) -> ThermalState {
334 ThermalState::Nominal
335 }
336
337 fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
338 unimplemented!()
339 }
340
341 fn quit(&self) {}
342
343 fn restart(&self, path: Option<PathBuf>) {
344 if let Some(tx) = self.expect_restart.take() {
345 tx.send(path).unwrap();
346 }
347 }
348
349 fn activate(&self, _ignoring_other_apps: bool) {
350 //
351 }
352
353 fn hide(&self) {
354 unimplemented!()
355 }
356
357 fn hide_other_apps(&self) {
358 unimplemented!()
359 }
360
361 fn unhide_other_apps(&self) {
362 unimplemented!()
363 }
364
365 fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
366 vec![self.active_display.clone()]
367 }
368
369 fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
370 Some(self.active_display.clone())
371 }
372
373 fn is_screen_capture_supported(&self) -> bool {
374 true
375 }
376
377 fn screen_capture_sources(
378 &self,
379 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
380 let (mut tx, rx) = oneshot::channel();
381 tx.send(Ok(self
382 .screen_capture_sources
383 .borrow()
384 .iter()
385 .map(|source| Rc::new(source.clone()) as Rc<dyn ScreenCaptureSource>)
386 .collect()))
387 .ok();
388 rx
389 }
390
391 fn active_window(&self) -> Option<crate::AnyWindowHandle> {
392 self.active_window
393 .borrow()
394 .as_ref()
395 .map(|window| window.0.lock().handle)
396 }
397
398 fn open_window(
399 &self,
400 handle: AnyWindowHandle,
401 params: WindowParams,
402 ) -> anyhow::Result<Box<dyn crate::PlatformWindow>> {
403 let renderer = self.headless_renderer_factory.as_ref().and_then(|f| f());
404 let window = TestWindow::new(
405 handle,
406 params,
407 self.weak.clone(),
408 self.active_display.clone(),
409 renderer,
410 );
411 Ok(Box::new(window))
412 }
413
414 fn window_appearance(&self) -> WindowAppearance {
415 WindowAppearance::Light
416 }
417
418 fn open_url(&self, url: &str) {
419 *self.opened_url.borrow_mut() = Some(url.to_string())
420 }
421
422 fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
423 unimplemented!()
424 }
425
426 fn prompt_for_paths(
427 &self,
428 options: crate::PathPromptOptions,
429 ) -> oneshot::Receiver<Result<Option<Vec<std::path::PathBuf>>>> {
430 let (tx, rx) = oneshot::channel();
431 self.prompts.borrow_mut().paths.push_back((options, tx));
432 rx
433 }
434
435 fn prompt_for_new_path(
436 &self,
437 directory: &std::path::Path,
438 _suggested_name: Option<&str>,
439 ) -> oneshot::Receiver<Result<Option<std::path::PathBuf>>> {
440 let (tx, rx) = oneshot::channel();
441 self.prompts
442 .borrow_mut()
443 .new_path
444 .push_back((directory.to_path_buf(), tx));
445 rx
446 }
447
448 fn can_select_mixed_files_and_dirs(&self) -> bool {
449 true
450 }
451
452 fn reveal_path(&self, _path: &std::path::Path) {
453 unimplemented!()
454 }
455
456 fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
457
458 fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
459 unimplemented!()
460 }
461
462 fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
463
464 fn set_app_identity(&self, identifier: &str, name: &str) {
465 self.system_notifications.borrow_mut().app_identity =
466 Some((identifier.to_string().into(), name.to_string().into()));
467 }
468
469 fn show_system_notification(&self, notification: SystemNotification) {
470 let mut system_notifications = self.system_notifications.borrow_mut();
471 if system_notifications.app_identity.is_none() {
472 return;
473 }
474
475 let delivered = system_notifications
476 .delivered
477 .iter_mut()
478 .find(|delivered| delivered.tag == notification.tag);
479 if let Some(delivered) = delivered {
480 *delivered = notification.clone();
481 } else {
482 system_notifications.delivered.push(notification.clone());
483 }
484 system_notifications.shown.push(notification);
485 }
486
487 fn dismiss_system_notification(&self, tag: &str) {
488 let mut system_notifications = self.system_notifications.borrow_mut();
489 system_notifications
490 .delivered
491 .retain(|notification| notification.tag != tag);
492 system_notifications
493 .dismissed
494 .push(SharedString::from(tag.to_string()));
495 }
496
497 fn on_system_notification_response(
498 &self,
499 callback: Box<dyn FnMut(SystemNotificationResponse)>,
500 ) {
501 self.system_notifications.borrow_mut().response_callback = Some(callback);
502 }
503
504 fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
505 fn set_dock_menu(&self, _menu: Vec<crate::MenuItem>, _keymap: &Keymap) {}
506
507 fn add_recent_document(&self, _paths: &Path) {}
508
509 fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
510
511 fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
512
513 fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
514
515 fn app_path(&self) -> Result<std::path::PathBuf> {
516 unimplemented!()
517 }
518
519 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
520 unimplemented!()
521 }
522
523 fn set_cursor_style(&self, style: crate::CursorStyle) {
524 *self.active_cursor.lock() = style;
525 }
526
527 fn hide_cursor_until_mouse_moves(&self) {}
528
529 fn is_cursor_visible(&self) -> bool {
530 true
531 }
532
533 fn should_auto_hide_scrollbars(&self) -> bool {
534 false
535 }
536
537 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
538 self.current_clipboard_item.lock().clone()
539 }
540
541 fn write_to_clipboard(&self, item: ClipboardItem) {
542 *self.current_clipboard_item.lock() = Some(item);
543 }
544
545 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
546 fn read_from_primary(&self) -> Option<ClipboardItem> {
547 self.current_primary_item.lock().clone()
548 }
549
550 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
551 fn write_to_primary(&self, item: ClipboardItem) {
552 *self.current_primary_item.lock() = Some(item);
553 }
554
555 #[cfg(target_os = "macos")]
556 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
557 self.current_find_pasteboard_item.lock().clone()
558 }
559
560 #[cfg(target_os = "macos")]
561 fn write_to_find_pasteboard(&self, item: ClipboardItem) {
562 *self.current_find_pasteboard_item.lock() = Some(item);
563 }
564
565 fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
566 Task::ready(Ok(()))
567 }
568
569 fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
570 Task::ready(Ok(None))
571 }
572
573 fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
574 Task::ready(Ok(()))
575 }
576
577 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
578 unimplemented!()
579 }
580
581 fn open_with_system(&self, _path: &Path) {
582 unimplemented!()
583 }
584}
585
586impl TestScreenCaptureSource {
587 /// Create a fake screen capture source, for testing.
588 pub fn new() -> Self {
589 Self {}
590 }
591}
592
593struct TestKeyboardLayout;
594
595impl PlatformKeyboardLayout for TestKeyboardLayout {
596 fn id(&self) -> &str {
597 "zed.keyboard.example"
598 }
599
600 fn name(&self) -> &str {
601 "zed.keyboard.example"
602 }
603}
604