use crate::{
AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DevicePixels,
DummyKeyboardMapper, ForegroundExecutor, Keymap, MouseButton, NoopTextSystem,
PathPromptOptions, Platform, PlatformDisplay, PlatformFocusedWindow, PlatformHeadlessRenderer,
PlatformHoveredWindow, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
PromptButton, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream, SourceMetadata,
Task, TestDisplay, TestWindow, ThermalState, WindowAppearance, WindowParams, size,
};
use anyhow::Result;
use futures::channel::oneshot;
use open_gpui_collections::VecDeque;
use parking_lot::Mutex;
use std::{
cell::RefCell,
path::{Path, PathBuf},
rc::{Rc, Weak},
sync::Arc,
};
pub(crate) struct TestPlatform {
background_executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
pub(crate) active_window: RefCell<Option<TestWindow>>,
pub(crate) focused_window_available: RefCell<bool>,
pub(crate) hovered_window_available: RefCell<bool>,
pub(crate) hovered_window: RefCell<Option<TestWindow>>,
window_stack: RefCell<Option<Vec<TestWindow>>>,
platform_viewport_windows: RefCell<bool>,
no_input_windows: RefCell<bool>,
active_display: Rc<dyn PlatformDisplay>,
active_cursor: Mutex<CursorStyle>,
pressed_mouse_buttons: Mutex<Option<Vec<MouseButton>>>,
current_clipboard_item: Mutex<Option<ClipboardItem>>,
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
current_primary_item: Mutex<Option<ClipboardItem>>,
#[cfg(target_os = "macos")]
current_find_pasteboard_item: Mutex<Option<ClipboardItem>>,
pub(crate) prompts: RefCell<TestPrompts>,
screen_capture_sources: RefCell<Vec<TestScreenCaptureSource>>,
pub opened_url: RefCell<Option<String>>,
pub text_system: Arc<dyn PlatformTextSystem>,
pub expect_restart: RefCell<Option<oneshot::Sender<Option<PathBuf>>>>,
quit_requested: RefCell<bool>,
system_wake_callback: RefCell<Option<Box<dyn FnMut()>>>,
headless_renderer_factory: Option<Box<dyn Fn() -> Option<Box<dyn PlatformHeadlessRenderer>>>>,
weak: Weak<Self>,
}
#[derive(Clone)]
pub struct TestScreenCaptureSource {}
pub struct TestScreenCaptureStream {}
impl ScreenCaptureSource for TestScreenCaptureSource {
fn metadata(&self) -> Result<SourceMetadata> {
Ok(SourceMetadata {
id: 0,
is_main: None,
label: None,
resolution: size(DevicePixels(1), DevicePixels(1)),
})
}
fn stream(
&self,
_foreground_executor: &ForegroundExecutor,
_frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {
let (mut tx, rx) = oneshot::channel();
let stream = TestScreenCaptureStream {};
tx.send(Ok(Box::new(stream) as Box<dyn ScreenCaptureStream>))
.ok();
rx
}
}
impl ScreenCaptureStream for TestScreenCaptureStream {
fn metadata(&self) -> Result<SourceMetadata> {
TestScreenCaptureSource {}.metadata()
}
}
struct TestPrompt {
msg: String,
detail: Option<String>,
answers: Vec<String>,
tx: oneshot::Sender<usize>,
}
#[derive(Default)]
pub(crate) struct TestPrompts {
multiple_choice: VecDeque<TestPrompt>,
new_path: VecDeque<(PathBuf, oneshot::Sender<Result<Option<PathBuf>>>)>,
paths: VecDeque<(
PathPromptOptions,
oneshot::Sender<Result<Option<Vec<PathBuf>>>>,
)>,
}
impl TestPlatform {
pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Rc<Self> {
Self::with_platform(
executor,
foreground_executor,
Arc::new(NoopTextSystem),
None,
)
}
pub fn with_text_system(
executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
text_system: Arc<dyn PlatformTextSystem>,
) -> Rc<Self> {
Self::with_platform(executor, foreground_executor, text_system, None)
}
pub fn with_platform(
executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
text_system: Arc<dyn PlatformTextSystem>,
headless_renderer_factory: Option<
Box<dyn Fn() -> Option<Box<dyn PlatformHeadlessRenderer>>>,
>,
) -> Rc<Self> {
Rc::new_cyclic(|weak| TestPlatform {
background_executor: executor,
foreground_executor,
prompts: Default::default(),
screen_capture_sources: Default::default(),
active_cursor: Default::default(),
pressed_mouse_buttons: Default::default(),
active_display: Rc::new(TestDisplay::new()),
active_window: Default::default(),
focused_window_available: RefCell::new(true),
hovered_window_available: RefCell::new(true),
hovered_window: Default::default(),
window_stack: Default::default(),
platform_viewport_windows: RefCell::new(true),
no_input_windows: RefCell::new(true),
expect_restart: Default::default(),
quit_requested: Default::default(),
system_wake_callback: Default::default(),
current_clipboard_item: Mutex::new(None),
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
current_primary_item: Mutex::new(None),
#[cfg(target_os = "macos")]
current_find_pasteboard_item: Mutex::new(None),
weak: weak.clone(),
opened_url: Default::default(),
text_system,
headless_renderer_factory,
})
}
pub(crate) fn set_no_input_windows(&self, supported: bool) {
*self.no_input_windows.borrow_mut() = supported;
}
pub(crate) fn set_platform_viewport_windows(&self, supported: bool) {
*self.platform_viewport_windows.borrow_mut() = supported;
}
pub(crate) fn simulate_new_path_selection(
&self,
select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
) {
let (path, tx) = self
.prompts
.borrow_mut()
.new_path
.pop_front()
.expect("no pending new path prompt");
tx.send(Ok(select_path(&path))).ok();
}
pub(crate) fn simulate_path_prompt_response(
&self,
select_paths: impl FnOnce(&PathPromptOptions) -> Option<Vec<std::path::PathBuf>>,
) {
let (options, tx) = self
.prompts
.borrow_mut()
.paths
.pop_front()
.expect("no pending paths prompt");
let selection = select_paths(&options);
if let Some(paths) = &selection
&& !options.multiple
&& paths.len() > 1
{
panic!(
"selected {} paths for a prompt that does not allow multiple selection",
paths.len()
);
}
tx.send(Ok(selection)).ok();
}
pub(crate) fn did_prompt_for_paths(&self) -> bool {
!self.prompts.borrow().paths.is_empty()
}
#[track_caller]
pub(crate) fn simulate_prompt_answer(&self, response: &str) {
let prompt = self
.prompts
.borrow_mut()
.multiple_choice
.pop_front()
.expect("no pending multiple choice prompt");
let Some(ix) = prompt.answers.iter().position(|a| a == response) else {
panic!(
"PROMPT: {}\n{:?}\n{:?}\nCannot respond with {}",
prompt.msg, prompt.detail, prompt.answers, response
)
};
prompt.tx.send(ix).ok();
}
pub(crate) fn has_pending_prompt(&self) -> bool {
!self.prompts.borrow().multiple_choice.is_empty()
}
pub(crate) fn did_quit(&self) -> bool {
*self.quit_requested.borrow()
}
pub(crate) fn pending_prompt(&self) -> Option<(String, String)> {
let prompts = self.prompts.borrow();
let prompt = prompts.multiple_choice.front()?;
Some((
prompt.msg.clone(),
prompt.detail.clone().unwrap_or_default(),
))
}
pub(crate) fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) {
*self.screen_capture_sources.borrow_mut() = sources;
}
pub(crate) fn prompt(
&self,
msg: &str,
detail: Option<&str>,
answers: &[PromptButton],
) -> oneshot::Receiver<usize> {
let (tx, rx) = oneshot::channel();
let answers: Vec<String> = answers.iter().map(|s| s.label().to_string()).collect();
self.prompts
.borrow_mut()
.multiple_choice
.push_back(TestPrompt {
msg: msg.to_string(),
detail: detail.map(|s| s.to_string()),
answers,
tx,
});
rx
}
pub(crate) fn set_active_window(&self, window: Option<TestWindow>) {
let executor = self.foreground_executor();
let previous_window = self.active_window.borrow_mut().take();
self.active_window.borrow_mut().clone_from(&window);
executor
.spawn(async move {
if let Some(previous_window) = previous_window {
if let Some(window) = window.as_ref()
&& Rc::ptr_eq(&previous_window.0, &window.0)
{
return;
}
previous_window.simulate_active_status_change(false);
}
if let Some(window) = window {
window.simulate_active_status_change(true);
}
})
.detach();
}
pub(crate) fn set_focused_window_available(&self, available: bool) {
*self.focused_window_available.borrow_mut() = available;
}
pub(crate) fn set_hovered_window_available(&self, available: bool) {
*self.hovered_window_available.borrow_mut() = available;
}
pub(crate) fn cursor_style(&self) -> CursorStyle {
*self.active_cursor.lock()
}
pub(crate) fn set_window_cursor_style(&self, window: &TestWindow, style: CursorStyle) {
let cursor_owner = if *self.hovered_window_available.borrow() {
self.hovered_window
.borrow()
.as_ref()
.is_some_and(|hovered| Rc::ptr_eq(&hovered.0, &window.0))
} else {
self.active_window
.borrow()
.as_ref()
.is_some_and(|active| Rc::ptr_eq(&active.0, &window.0))
};
if cursor_owner {
*self.active_cursor.lock() = style;
}
}
pub(crate) fn set_hovered_window(&self, window: Option<TestWindow>) {
let previous_window = self.hovered_window.borrow_mut().take();
self.hovered_window.borrow_mut().clone_from(&window);
*self.active_cursor.lock() = window
.as_ref()
.map(|window| window.0.lock().cursor_style)
.unwrap_or(CursorStyle::Arrow);
if let Some(previous_window) = previous_window {
if let Some(window) = window.as_ref()
&& Rc::ptr_eq(&previous_window.0, &window.0)
{
return;
}
previous_window.simulate_hover_status_change(false);
}
if let Some(window) = window {
window.simulate_hover_status_change(true);
}
}
pub(crate) fn set_window_stack(&self, windows: Option<Vec<TestWindow>>) {
*self.window_stack.borrow_mut() = windows;
}
pub(crate) fn set_mouse_button_is_pressed(&self, button: MouseButton, pressed: Option<bool>) {
let mut buttons = self.pressed_mouse_buttons.lock();
match pressed {
Some(true) => {
let buttons = buttons.get_or_insert_with(Vec::new);
if !buttons.contains(&button) {
buttons.push(button);
}
}
Some(false) => {
let Some(buttons) = buttons.as_mut() else {
*buttons = Some(Vec::new());
return;
};
buttons.retain(|pressed_button| pressed_button != &button);
}
None => {
*buttons = None;
}
}
}
pub(crate) fn simulate_system_wake(&self) {
let Some(mut callback) = self.system_wake_callback.take() else {
return;
};
callback();
self.system_wake_callback.replace(Some(callback));
}
pub(crate) fn did_prompt_for_new_path(&self) -> bool {
!self.prompts.borrow().new_path.is_empty()
}
}
impl Platform for TestPlatform {
fn background_executor(&self) -> BackgroundExecutor {
self.background_executor.clone()
}
fn foreground_executor(&self) -> ForegroundExecutor {
self.foreground_executor.clone()
}
fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
self.text_system.clone()
}
fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
Box::new(TestKeyboardLayout)
}
fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
Rc::new(DummyKeyboardMapper)
}
fn on_keyboard_layout_change(&self, _: Box<dyn FnMut()>) {}
fn on_thermal_state_change(&self, _: Box<dyn FnMut()>) {}
fn on_system_wake(&self, callback: Box<dyn FnMut()>) {
self.system_wake_callback.replace(Some(callback));
}
fn thermal_state(&self) -> ThermalState {
ThermalState::Nominal
}
fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
unimplemented!()
}
fn quit(&self) {
self.quit_requested.replace(true);
}
fn restart(&self, path: Option<PathBuf>) {
if let Some(tx) = self.expect_restart.take() {
tx.send(path).unwrap();
}
}
fn activate(&self, _ignoring_other_apps: bool) {
}
fn hide(&self) {
unimplemented!()
}
fn hide_other_apps(&self) {
unimplemented!()
}
fn unhide_other_apps(&self) {
unimplemented!()
}
fn displays(&self) -> Vec<std::rc::Rc<dyn crate::PlatformDisplay>> {
vec![self.active_display.clone()]
}
fn primary_display(&self) -> Option<std::rc::Rc<dyn crate::PlatformDisplay>> {
Some(self.active_display.clone())
}
fn is_screen_capture_supported(&self) -> bool {
true
}
fn screen_capture_sources(
&self,
) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
let (mut tx, rx) = oneshot::channel();
tx.send(Ok(self
.screen_capture_sources
.borrow()
.iter()
.map(|source| Rc::new(source.clone()) as Rc<dyn ScreenCaptureSource>)
.collect()))
.ok();
rx
}
fn active_window(&self) -> Option<crate::AnyWindowHandle> {
self.active_window
.borrow()
.as_ref()
.map(|window| window.0.lock().handle)
}
fn focused_window(&self) -> PlatformFocusedWindow {
if *self.focused_window_available.borrow() {
PlatformFocusedWindow::from_window(self.active_window())
} else {
PlatformFocusedWindow::Unavailable
}
}
fn hovered_window(&self) -> PlatformHoveredWindow {
if !*self.hovered_window_available.borrow() {
return PlatformHoveredWindow::Unavailable;
}
PlatformHoveredWindow::from_window(
self.hovered_window
.borrow()
.as_ref()
.map(|window| window.0.lock().handle),
)
}
fn window_stack(&self) -> Option<Vec<crate::AnyWindowHandle>> {
self.window_stack.borrow().as_ref().map(|windows| {
windows
.iter()
.map(|window| window.0.lock().handle)
.collect()
})
}
fn viewport_capabilities(&self) -> crate::PlatformViewportCapabilities {
crate::PlatformViewportCapabilities {
platform_viewport_windows: *self.platform_viewport_windows.borrow(),
global_window_bounds: true,
window_stack: self.window_stack.borrow().is_some(),
display_work_area: true,
dpi_scale: true,
no_input_windows: *self.no_input_windows.borrow(),
hovered_window_ignores_no_input: true,
..Default::default()
}
}
fn mouse_button_is_pressed(&self, button: MouseButton) -> Option<bool> {
self.pressed_mouse_buttons
.lock()
.as_ref()
.map(|buttons| buttons.contains(&button))
}
fn open_window(
&self,
handle: AnyWindowHandle,
params: WindowParams,
) -> anyhow::Result<Box<dyn crate::PlatformWindow>> {
let renderer = self.headless_renderer_factory.as_ref().and_then(|f| f());
let window = TestWindow::new(
handle,
params,
self.weak.clone(),
self.active_display.clone(),
renderer,
);
Ok(Box::new(window))
}
fn window_appearance(&self) -> WindowAppearance {
WindowAppearance::Light
}
fn open_url(&self, url: &str) {
*self.opened_url.borrow_mut() = Some(url.to_string())
}
fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {
unimplemented!()
}
fn prompt_for_paths(
&self,
options: crate::PathPromptOptions,
) -> oneshot::Receiver<Result<Option<Vec<std::path::PathBuf>>>> {
let (tx, rx) = oneshot::channel();
self.prompts.borrow_mut().paths.push_back((options, tx));
rx
}
fn prompt_for_new_path(
&self,
directory: &std::path::Path,
_suggested_name: Option<&str>,
) -> oneshot::Receiver<Result<Option<std::path::PathBuf>>> {
let (tx, rx) = oneshot::channel();
self.prompts
.borrow_mut()
.new_path
.push_back((directory.to_path_buf(), tx));
rx
}
fn can_select_mixed_files_and_dirs(&self) -> bool {
true
}
fn reveal_path(&self, _path: &std::path::Path) {
unimplemented!()
}
fn on_quit(&self, _callback: Box<dyn FnMut()>) {}
fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
unimplemented!()
}
fn set_menus(&self, _menus: Vec<crate::Menu>, _keymap: &Keymap) {}
fn set_dock_menu(&self, _menu: Vec<crate::MenuItem>, _keymap: &Keymap) {}
fn add_recent_document(&self, _paths: &Path) {}
fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn crate::Action)>) {}
fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn crate::Action) -> bool>) {}
fn app_path(&self) -> Result<std::path::PathBuf> {
unimplemented!()
}
fn path_for_auxiliary_executable(&self, _name: &str) -> Result<std::path::PathBuf> {
unimplemented!()
}
fn hide_cursor_until_mouse_moves(&self) {}
fn is_cursor_visible(&self) -> bool {
true
}
fn should_auto_hide_scrollbars(&self) -> bool {
false
}
fn read_from_clipboard(&self) -> Option<ClipboardItem> {
self.current_clipboard_item.lock().clone()
}
fn write_to_clipboard(&self, item: ClipboardItem) {
*self.current_clipboard_item.lock() = Some(item);
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn read_from_primary(&self) -> Option<ClipboardItem> {
self.current_primary_item.lock().clone()
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn write_to_primary(&self, item: ClipboardItem) {
*self.current_primary_item.lock() = Some(item);
}
#[cfg(target_os = "macos")]
fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
self.current_find_pasteboard_item.lock().clone()
}
#[cfg(target_os = "macos")]
fn write_to_find_pasteboard(&self, item: ClipboardItem) {
*self.current_find_pasteboard_item.lock() = Some(item);
}
fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
Task::ready(Ok(()))
}
fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
Task::ready(Ok(None))
}
fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
Task::ready(Ok(()))
}
fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
unimplemented!()
}
fn open_with_system(&self, _path: &Path) {
unimplemented!()
}
}
impl TestScreenCaptureSource {
pub fn new() -> Self {
Self {}
}
}
struct TestKeyboardLayout;
impl PlatformKeyboardLayout for TestKeyboardLayout {
fn id(&self) -> &str {
"open-gpui.keyboard.example"
}
fn name(&self) -> &str {
"open-gpui.keyboard.example"
}
}