gpui: Make Modifiers::secondary web platform aware (#65970)

This introduces a new PlatformInfo abstraction that allows querying a
gpui app's platform from runtime facts.
This is necessary for correctness when dealing with web applications, as
their host platform there is a runtime fact, not a compile time fact.


Release Notes:

- [GPUI] Fixed platform-dependent modifiers and keybinding parsing and
formatting in web applications by querying the host operating system at
runtime.
This commit is contained in:
Lukas Wirth
2026-10-22 11:49:45 +00:00
committed by GitHub
parent 04470cd9b5
commit 389c22e1c7
73 changed files with 679 additions and 355 deletions
+3 -3
View File
@@ -6593,8 +6593,8 @@ impl AgentPanel {
}
}
fn key_context(&self) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults();
fn key_context(&self, cx: &App) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("AgentPanel");
key_context
}
@@ -6612,7 +6612,7 @@ impl Render for AgentPanel {
// - Scrolling in all views works as expected
// - Files can be dropped into the panel
let content = v_flex()
.key_context(self.key_context())
.key_context(self.key_context(cx))
.relative()
.size_full()
.justify_between()
+1 -1
View File
@@ -235,7 +235,7 @@ impl AgentRegistryPage {
}
fn render_search(&self, cx: &mut Context<Self>) -> Div {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("BufferSearchBar");
h_flex()
@@ -481,7 +481,8 @@ mod tests {
// Click handlers activate buttons on key release, not key press.
window.dispatch_event(
PlatformInput::KeyUp(KeyUpEvent {
keystroke: Keystroke::parse(key).expect("valid test keystroke"),
keystroke: Keystroke::parse_with_os(key, cx.platform_info().os)
.expect("valid test keystroke"),
}),
cx,
);
@@ -780,7 +780,7 @@ impl Render for ThreadSearchBar {
let query_empty = self.query_editor.read(cx).text(cx).is_empty();
let in_error_state = self.query_error || (!query_empty && !has_matches);
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("AcpThreadSearchBar");
let counter_text = self.active_match_text(cx).unwrap_or_default();
+1 -1
View File
@@ -2440,7 +2440,7 @@ impl CollabPanel {
}
fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("CollabPanel");
dispatch_context.add("menu");
+1 -1
View File
@@ -570,7 +570,7 @@ impl Render for NewProcessModal {
v_flex()
.key_context({
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("Pane");
key_context.add("RunModal");
key_context
+18 -14
View File
@@ -1753,37 +1753,40 @@ struct GutterButtonTooltip {
}
impl GutterButtonTooltip {
fn active_intent(&self, modifiers: Modifiers) -> GutterButtonIntent {
if modifiers.secondary() {
fn active_intent(&self, modifiers: Modifiers, cx: &App) -> GutterButtonIntent {
if modifiers.secondary(cx) {
self.secondary
} else {
self.primary
}
}
fn meta_text(&self) -> String {
fn meta_text(&self, cx: &App) -> String {
const RIGHT_CLICK_HINT: &str = "right-click for more options";
if self.primary == self.secondary {
return RIGHT_CLICK_HINT.to_string();
}
let modifier_as_text = gpui::Keystroke {
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
..Default::default()
};
let secondary = match self.secondary {
GutterButtonIntent::SetBookmark => "bookmark",
GutterButtonIntent::SetBreakpoint => "breakpoint",
};
format!("{modifier_as_text}-click to add a {secondary}\n{RIGHT_CLICK_HINT}")
format!(
"{}-click to add a {secondary}\n{RIGHT_CLICK_HINT}",
modifier_as_text.display(cx.platform_info().os)
)
}
}
impl Render for GutterButtonTooltip {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let intent = self.active_intent(window.modifiers());
let intent = self.active_intent(window.modifiers(), cx);
let key_binding = KeyBinding::for_action_in(intent.action(), &self.focus_handle, cx);
let meta_text = self.meta_text();
let meta_text = self.meta_text(cx);
#[cfg(test)]
if let Some(on_render) = &self.on_render {
@@ -2787,7 +2790,7 @@ impl Editor {
window: &mut Window,
cx: &mut App,
) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("Editor");
let mode = match self.mode {
EditorMode::SingleLine => "single_line",
@@ -4191,7 +4194,7 @@ impl Editor {
fn is_cmd_or_ctrl_pressed(modifiers: &Modifiers, cx: &mut Context<Self>) -> bool {
match EditorSettings::get_global(cx).multi_cursor_modifier {
MultiCursorModifier::Alt => modifiers.secondary(),
MultiCursorModifier::Alt => modifiers.secondary(cx),
MultiCursorModifier::CmdOrCtrl => modifiers.alt,
}
}
@@ -4199,7 +4202,7 @@ impl Editor {
fn is_alt_pressed(modifiers: &Modifiers, cx: &mut Context<Self>) -> bool {
match EditorSettings::get_global(cx).multi_cursor_modifier {
MultiCursorModifier::Alt => modifiers.alt,
MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
MultiCursorModifier::CmdOrCtrl => modifiers.secondary(cx),
}
}
@@ -4737,7 +4740,7 @@ impl Editor {
let breakpoint = Arc::from(breakpoint.clone());
let alt_as_text = gpui::Keystroke {
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
..Default::default()
};
let primary_action_text = "Unset breakpoint";
@@ -4748,7 +4751,8 @@ impl Editor {
SharedString::from("No executable code is associated with this line.")
} else if !breakpoint.is_disabled() {
SharedString::from(format!(
"{alt_as_text}-click to disable\nright-click for more options"
"{}-click to disable\nright-click for more options",
alt_as_text.display(cx.platform_info().os)
))
} else {
SharedString::from("Right-click for more options")
@@ -4818,7 +4822,7 @@ impl Editor {
}
};
let intent = if window.modifiers().secondary() {
let intent = if window.modifiers().secondary(cx) {
secondary
} else {
primary
@@ -4834,7 +4838,7 @@ impl Editor {
.on_click(cx.listener({
move |editor, _: &ClickEvent, window, cx| {
window.focus(&editor.focus_handle(cx), cx);
let intent = if window.modifiers().secondary() {
let intent = if window.modifiers().secondary(cx) {
secondary
} else {
primary
+5 -5
View File
@@ -36794,17 +36794,17 @@ fn test_gutter_button_tooltip_updates_intent_with_secondary_modifier(cx: &mut Te
on_render: None,
};
let primary_intent = tooltip.active_intent(Modifiers::none());
let primary_intent = cx.read(|cx| tooltip.active_intent(Modifiers::none(), cx));
assert_eq!(primary_intent, GutterButtonIntent::SetBreakpoint);
assert!(primary_intent.action().as_any().is::<ToggleBreakpoint>());
let secondary_intent = tooltip.active_intent(Modifiers::secondary_key());
let secondary_intent = cx.read(|cx| tooltip.active_intent(Modifiers::secondary_key(cx), cx));
assert_eq!(secondary_intent, GutterButtonIntent::SetBookmark);
assert!(secondary_intent.action().as_any().is::<ToggleBookmark>());
// When both features are enabled, the meta text advertises the
// modifier-click alternative.
let meta = tooltip.meta_text();
let meta = cx.read(|cx| tooltip.meta_text(cx));
assert!(meta.contains("-click to add a bookmark"), "got: {meta}");
assert!(!meta.contains("-click to add a breakpoint"), "got: {meta}");
assert!(meta.contains("right-click for more options"));
@@ -36818,7 +36818,7 @@ fn test_gutter_button_tooltip_updates_intent_with_secondary_modifier(cx: &mut Te
focus_handle: tooltip.focus_handle,
on_render: None,
};
let meta = single_feature_tooltip.meta_text();
let meta = cx.read(|cx| single_feature_tooltip.meta_text(cx));
assert_eq!(meta, "right-click for more options");
}
@@ -36847,7 +36847,7 @@ fn test_gutter_button_tooltip_renders_modifier_transitions(cx: &mut TestAppConte
assert_render("Set Breakpoint");
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
tooltip.update_in(cx, |_, _window, cx| cx.notify());
cx.run_until_parked();
assert_render("Set Bookmark");
+3 -3
View File
@@ -887,7 +887,7 @@ pub(crate) fn render_buffer_header(
move |editor, e: &ClickEvent, window, cx| {
editor.open_excerpts_common(
Some(jump_data.clone()),
e.modifiers().secondary(),
e.modifiers().secondary(cx),
window,
cx,
);
@@ -961,7 +961,7 @@ pub(crate) fn render_buffer_header(
move |editor, e: &ClickEvent, window, cx| {
editor.open_excerpts_common(
Some(jump_data.clone()),
e.modifiers().secondary(),
e.modifiers().secondary(cx),
window,
cx,
);
@@ -977,7 +977,7 @@ pub(crate) fn render_buffer_header(
if e.modifiers().alt {
editor.open_excerpts_common(
Some(jump_data.clone()),
e.modifiers().secondary(),
e.modifiers().secondary(cx),
window,
cx,
);
+6 -3
View File
@@ -266,7 +266,7 @@ impl EditorElement {
&position_map.snapshot,
hint_glyph,
Some(event.position),
modifiers.secondary(),
modifiers.secondary(cx),
modifiers.shift,
window,
cx,
@@ -506,7 +506,7 @@ impl EditorElement {
if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
delta = delta.coalesce(event.delta);
if event.modifiers.secondary()
if event.modifiers.secondary(cx)
&& editor.read(cx).enable_mouse_wheel_zoom
&& EditorSettings::get_global(cx).mouse_wheel_zoom
{
@@ -775,7 +775,10 @@ impl EditorElement {
window,
cx,
);
} else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
} else if modifiers.shift
&& !modifiers.control
&& !modifiers.alt
&& !modifiers.secondary(cx)
{
editor.select(
SelectPhase::Extend {
+76 -53
View File
@@ -1328,7 +1328,8 @@ mod tests {
"},
);
cx.simulate_modifiers_change(Modifiers::secondary_key());
let secondary_modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_modifiers_change(secondary_modifiers);
cx.run_until_parked();
// Assert no link highlights
cx.assert_editor_text_highlights(
@@ -1468,9 +1469,10 @@ mod tests {
cx.run_until_parked();
let screen_coord = cx.pixel_position(indoc! {"struct fiˇle;"});
cx.run_until_parked();
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.run_until_parked();
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.run_until_parked();
assert_eq!(
references_count.load(Ordering::SeqCst),
@@ -1525,9 +1527,10 @@ mod tests {
let screen_coord = cx.pixel_position(indoc! {"// see fileˇ2.rs"});
cx.run_until_parked();
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.run_until_parked();
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.run_until_parked();
cx.update_workspace(|workspace, _, cx| {
let path = workspace
@@ -1598,13 +1601,14 @@ mod tests {
fn do_work() { teˇst(); }
"});
cx.simulate_mouse_move(symbol_start, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(symbol_start, None, modifiers);
cx.run_until_parked();
cx.simulate_mouse_move(symbol_end, None, Modifiers::secondary_key());
cx.simulate_mouse_move(symbol_end, None, modifiers);
cx.run_until_parked();
cx.simulate_mouse_move(other_symbol, None, Modifiers::secondary_key());
cx.simulate_mouse_move(other_symbol, None, modifiers);
cx.run_until_parked();
assert_eq!(
@@ -1655,16 +1659,17 @@ mod tests {
fn do_work() { test(); }
"});
cx.simulate_mouse_move(first_point, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(first_point, None, modifiers);
cx.run_until_parked();
cx.simulate_mouse_move(second_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(second_point, None, modifiers);
cx.run_until_parked();
// Jiggle within the same character should not produce a new request,
// even though the previous response was empty and produced no link to
// highlight.
cx.simulate_mouse_move(second_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(second_point, None, modifiers);
cx.run_until_parked();
assert_eq!(
@@ -1719,7 +1724,8 @@ mod tests {
])))
});
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(hover_point, None, modifiers);
requests.next().await;
cx.background_executor.run_until_parked();
cx.assert_editor_text_highlights(
@@ -1752,7 +1758,7 @@ mod tests {
])))
});
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(hover_point, None, modifiers);
requests.next().await;
cx.background_executor.run_until_parked();
cx.assert_editor_text_highlights(
@@ -1774,7 +1780,7 @@ mod tests {
// No definitions returned
Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
});
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(hover_point, None, modifiers);
requests.next().await;
cx.background_executor.run_until_parked();
@@ -1825,7 +1831,7 @@ mod tests {
])))
});
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(modifiers);
requests.next().await;
cx.background_executor.run_until_parked();
@@ -1847,7 +1853,7 @@ mod tests {
"},
);
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(hover_point, None, modifiers);
cx.background_executor.run_until_parked();
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
@@ -1862,7 +1868,7 @@ mod tests {
fn test() { do_work(); }
fn do_work() { tesˇt(); }
"});
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(hover_point, None, modifiers);
cx.background_executor.run_until_parked();
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
@@ -1873,7 +1879,7 @@ mod tests {
);
// Cmd click with existing definition doesn't re-request and dismisses highlight
cx.simulate_click(hover_point, Modifiers::secondary_key());
cx.simulate_click(hover_point, modifiers);
cx.lsp
.set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
// Empty definition response to make sure we aren't hitting the lsp and using
@@ -1916,7 +1922,7 @@ mod tests {
},
])))
});
cx.simulate_click(hover_point, Modifiers::secondary_key());
cx.simulate_click(hover_point, modifiers);
requests.next().await;
cx.background_executor.run_until_parked();
cx.assert_editor_state(indoc! {"
@@ -1960,7 +1966,7 @@ mod tests {
s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
});
});
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
cx.simulate_mouse_move(hover_point, None, modifiers);
cx.background_executor.run_until_parked();
assert!(requests.try_recv().is_err());
cx.assert_editor_text_highlights(
@@ -3166,7 +3172,8 @@ mod tests {
});
// Press cmd to trigger highlight
let hover_point = cx.pixel_position_for(midpoint);
cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(hover_point, None, modifiers);
cx.background_executor.run_until_parked();
cx.update_editor(|editor, window, cx| {
let snapshot = editor.snapshot(window, cx);
@@ -3255,9 +3262,9 @@ mod tests {
}
"});
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(modifiers);
cx.background_executor.run_until_parked();
cx.simulate_click(hover_point, Modifiers::secondary_key());
cx.simulate_click(hover_point, modifiers);
cx.background_executor.run_until_parked();
let destination = indoc! {"
struct «TestStructˇ»;
@@ -3293,7 +3300,7 @@ mod tests {
assert!(!state.task.as_ref().expect("hover task").is_ready());
let down = MouseDownEvent {
position: click_point,
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
button: MouseButton::Left,
click_count: 1,
first_mouse: false,
@@ -3331,7 +3338,8 @@ mod tests {
Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"
@@ -3339,7 +3347,7 @@ mod tests {
"},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
assert_eq!(
cx.opened_url(),
Some("https://zed.dev/channel/had-(oops)".into())
@@ -3459,7 +3467,8 @@ mod tests {
Ok(Some(lsp::GotoDefinitionResponse::Array(locations.to_vec())))
});
let position = cx.pixel_position(&source);
cx.simulate_mouse_move(position, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(position, None, modifiers);
assert_eq!(symbols.next().await, Some(()));
cx.run_until_parked();
cx.editor(|editor, _, _| {
@@ -3468,7 +3477,7 @@ mod tests {
assert!(state.task.as_ref().expect("hover task").is_ready());
assert_eq!(state.links.len(), 1, "{marked}");
});
let mut modifiers = Modifiers::secondary_key();
let mut modifiers = cx.read(Modifiers::secondary_key);
modifiers.shift = true;
cx.simulate_click(position, modifiers);
assert!(types.try_recv().is_err());
@@ -3543,7 +3552,8 @@ mod tests {
let screen_coord = cx.pixel_position(indoc! {"
Let's test a [complex](https://zed.dev/channeˇl/) case.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"
@@ -3568,13 +3578,14 @@ mod tests {
let screen_coord =
cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
}
@@ -3594,13 +3605,14 @@ mod tests {
let screen_coord =
cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
}
@@ -3901,7 +3913,8 @@ Sentence ending file2.rs.
for (original, cursor_version, highlight_version) in test_cases {
let position_text = base.replace(original, cursor_version);
let screen_coord = cx.pixel_position(&position_text);
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
if let Some(highlight) = highlight_version {
let expected = base.replace(original, highlight);
@@ -3929,7 +3942,8 @@ Sentence ending file2.rs.
"Or [link](fiˇle2.rs) markdown",
);
let screen_coord = cx.pixel_position(&position_text);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
cx.update_workspace(|workspace, _, cx| {
@@ -3984,7 +3998,8 @@ Sentence ending file2.rs.
Go to filˇe2.rs:5:3 for the fix.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"
@@ -3992,7 +4007,7 @@ Sentence ending file2.rs.
"},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
cx.update_workspace(|workspace, window, cx| {
@@ -4061,7 +4076,8 @@ Sentence ending file2.rs.
Go to filˇe2.rs:3 please.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"
@@ -4069,7 +4085,7 @@ Sentence ending file2.rs.
"},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, window, cx| {
let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
@@ -4119,7 +4135,8 @@ Sentence ending file2.rs.
Error at filˇe2.rs:2:in 'method'
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"
@@ -4127,7 +4144,7 @@ Sentence ending file2.rs.
"},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, window, cx| {
let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
@@ -4179,7 +4196,8 @@ Sentence ending file2.rs.
See [here](filˇe2.rs:3:2) for details.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.assert_editor_text_highlights(
HighlightKey::HoveredLinkState,
indoc! {"
@@ -4187,7 +4205,7 @@ Sentence ending file2.rs.
"},
);
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, window, cx| {
let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
@@ -4249,7 +4267,8 @@ Sentence ending file2.rs.
let screen_coord = cx.pixel_position(indoc! {"
You can't open ../diˇr because it's a directory.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
// No highlight
cx.update_editor(|editor, window, cx| {
@@ -4264,7 +4283,7 @@ Sentence ending file2.rs.
});
// Does not open the directory
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
}
@@ -4287,7 +4306,8 @@ Sentence ending file2.rs.
let screen_coord = cx.pixel_position(indoc! {"
You can't open ˇ\"🤩\" because it's an emoji.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
// No highlight, does not panic...
cx.update_editor(|editor, window, cx| {
@@ -4302,7 +4322,7 @@ Sentence ending file2.rs.
});
// Does not open the directory
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
}
@@ -4437,7 +4457,8 @@ Sentence ending file2.rs.
}
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.run_until_parked();
cx.assert_editor_text_highlights(
@@ -4451,7 +4472,7 @@ Sentence ending file2.rs.
);
// Clicking opens the URL
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
assert_eq!(
cx.opened_url(),
Some("https://opensource.org/licenses/MIT".into())
@@ -4507,7 +4528,8 @@ Sentence ending file2.rs.
// See https://examˇple.com for more info
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
cx.run_until_parked();
// LSP document link range is highlighted, not just the URL portion
@@ -4520,7 +4542,7 @@ Sentence ending file2.rs.
// Clicking navigates to the LSP-provided target, not the detected URL.
// (Uri::to_string normalizes "https://host" to "https://host/")
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
assert_eq!(
cx.opened_url(),
Some("https://lsp-provided.example.com/".into())
@@ -4597,7 +4619,8 @@ Sentence ending file2.rs.
// See LICˇENSE for details
fn definition() {}
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(screen_coord, None, modifiers);
definition_requests.next().await;
cx.run_until_parked();
@@ -4628,7 +4651,7 @@ Sentence ending file2.rs.
// Cmd-click resolves the in-buffer location (definition) since the
// mixed Url + Text case lets `navigate_to_hover_links` prefer the
// location target over the external URL.
cx.simulate_click(screen_coord, Modifiers::secondary_key());
cx.simulate_click(screen_coord, modifiers);
cx.run_until_parked();
cx.assert_editor_state(indoc! {"
// See LICENSE for details
+2 -2
View File
@@ -495,7 +495,7 @@ impl RenderOnce for DiffStyleControls {
.text_ui_sm(cx)
.text_color(Color::Muted.color(cx))
.children(render_modifiers(
&gpui::Modifiers::secondary_key(),
&gpui::Modifiers::secondary_key(cx),
PlatformStyle::platform(),
None,
Some(TextSize::Small.rems(cx).into()),
@@ -508,7 +508,7 @@ impl RenderOnce for DiffStyleControls {
.on_click({
let splittable_editor = self.splittable_editor.clone();
move |_, window, cx| {
if window.modifiers().secondary() {
if window.modifiers().secondary(cx) {
window.dispatch_action(
OpenSettingsAt {
path: "minimum_split_diff_width".to_string(),
@@ -264,7 +264,8 @@ impl EditorTestContext {
// unlike cx.simulate_keystrokes(), this does not run_until_parked
// so you can use it to test detailed timing
pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
let keystroke = Keystroke::parse(keystroke_text).unwrap();
let os = self.cx.read(|cx| cx.platform_info().os);
let keystroke = Keystroke::parse_with_os(keystroke_text, os).unwrap();
self.cx.dispatch_keystroke(self.window, keystroke);
}
+1 -1
View File
@@ -860,7 +860,7 @@ impl ExtensionsPage {
}
fn render_search(&self, cx: &mut Context<Self>) -> Div {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("BufferSearchBar");
let editor_border = if self.query_contains_error {
+2 -2
View File
@@ -1702,8 +1702,8 @@ impl FileFinderDelegate {
0
}
fn key_context(&self, _window: &Window, _cx: &App) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults();
fn key_context(&self, _window: &Window, cx: &App) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("FileFinder");
key_context
}
+7 -7
View File
@@ -4458,7 +4458,7 @@ async fn test_keeps_file_finder_open_after_modifier_keys_release(cx: &mut gpui::
open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
open_file_picker(&workspace, cx);
cx.simulate_modifiers_change(Modifiers::none());
@@ -4489,7 +4489,7 @@ async fn test_opens_file_on_modifier_keys_release(cx: &mut gpui::TestAppContext)
open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
open_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
let picker = open_file_picker(&workspace, cx);
picker.update(cx, |finder, _| {
assert_eq!(finder.delegate.matches.len(), 2);
@@ -4532,7 +4532,7 @@ async fn test_switches_between_release_norelease_modes_on_forward_nav(
open_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
// Open with a shortcut
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
let picker = open_file_picker(&workspace, cx);
picker.update(cx, |finder, _| {
assert_eq!(finder.delegate.matches.len(), 2);
@@ -4553,7 +4553,7 @@ async fn test_switches_between_release_norelease_modes_on_forward_nav(
// Back to navigation with initial shortcut
// Open file on modifiers release
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
cx.dispatch_action(ToggleFileFinder::default());
cx.simulate_modifiers_change(Modifiers::none());
cx.read(|cx| {
@@ -4591,7 +4591,7 @@ async fn test_switches_between_release_norelease_modes_on_backward_nav(
open_queried_buffer("3", 1, "3.txt", &workspace, cx).await;
// Open with a shortcut
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
let picker = open_file_picker(&workspace, cx);
picker.update(cx, |finder, _| {
assert_eq!(finder.delegate.matches.len(), 3);
@@ -4614,7 +4614,7 @@ async fn test_switches_between_release_norelease_modes_on_backward_nav(
// Back to navigation with initial shortcut
// Open file on modifiers release
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
cx.dispatch_action(SelectPrevious); // <-- File Finder's SelectPrevious, not menu's
cx.simulate_modifiers_change(Modifiers::none());
cx.read(|cx| {
@@ -4645,7 +4645,7 @@ async fn test_extending_modifiers_does_not_confirm_selection(cx: &mut gpui::Test
open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.simulate_modifiers_change(cx.read(Modifiers::secondary_key));
open_file_picker(&workspace, cx);
cx.simulate_modifiers_change(Modifiers::command_shift());
+3 -3
View File
@@ -2118,7 +2118,7 @@ impl GitPanel {
}
fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("GitPanel");
if self.commit_editor.read(cx).is_focused(window) {
@@ -9045,7 +9045,7 @@ impl GitPanel {
this.apply_range_gesture(anchor_ix, ix);
this.selected_entry = Some(ix);
cx.notify();
} else if event.modifiers().secondary() {
} else if event.modifiers().secondary(cx) {
this.toggle_mark(ix, cx);
} else {
this.clear_marks_and_select(ix, cx);
@@ -9244,7 +9244,7 @@ impl GitPanel {
this.apply_range_gesture(anchor_ix, ix);
this.selected_entry = Some(ix);
cx.notify();
} else if event.modifiers().secondary() {
} else if event.modifiers().secondary(cx) {
this.toggle_mark(ix, cx);
} else {
this.clear_marks();
+1 -1
View File
@@ -432,7 +432,7 @@ impl Render for GitPicker {
}))
})
.key_context({
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("Pane");
key_context.add("GitPicker");
match self.tab {
+1 -1
View File
@@ -745,7 +745,7 @@ impl Render for InputExample {
.children(self.recent_keystrokes.iter().rev().map(|ks| {
format!(
"{:} {}",
ks.unparse(),
ks.unparse(cx.platform_info().os),
if let Some(key_char) = ks.key_char.as_ref() {
format!("-> {:?}", key_char)
} else {
+5
View File
@@ -1979,6 +1979,11 @@ impl App {
self.platform.compositor_name()
}
/// Returns the host OS and application target reported by the backend.
pub fn platform_info(&self) -> crate::PlatformInfo {
self.platform.platform_info()
}
/// Returns the file URL of the executable with the specified name in the application bundle
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
self.platform.path_for_auxiliary_executable(name)
+2 -1
View File
@@ -382,7 +382,8 @@ impl<V: 'static + Render> TestAppWindow<V> {
/// Simulate a keystroke.
pub fn simulate_keystroke(&mut self, keystroke: &str) {
let keystroke = Keystroke::parse(keystroke).unwrap();
let os = self.app.borrow().platform_info().os;
let keystroke = Keystroke::parse_with_os(keystroke, os).unwrap();
{
let mut app = self.app.borrow_mut();
let any_handle: AnyWindowHandle = self.handle.into();
+13 -2
View File
@@ -123,6 +123,11 @@ impl AppContext for TestAppContext {
}
impl TestAppContext {
/// Sets the runtime identity used by this test's application.
pub fn set_platform_info(&mut self, platform_info: crate::PlatformInfo) {
self.test_platform.platform_info.set(platform_info);
}
/// Creates a new `TestAppContext`. Usually you can rely on `#[gpui::test]` to do this for you.
pub fn build(dispatcher: TestDispatcher, fn_name: Option<&'static str>) -> Self {
let arc_dispatcher = Arc::new(dispatcher.clone());
@@ -615,9 +620,10 @@ impl TestAppContext {
/// in Zed, this will run backspace on the current editor through the command palette.
/// This will also run the background executor until it's parked.
pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
let os = self.read(|cx| cx.platform_info().os);
for keystroke in keystrokes
.split(' ')
.map(Keystroke::parse)
.map(|source| Keystroke::parse_with_os(source, os))
.map(Result::unwrap)
{
self.dispatch_keystroke(window, keystroke);
@@ -631,7 +637,12 @@ impl TestAppContext {
/// will type abc into your current editor
/// This will also run the background executor until it's parked.
pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
let os = self.read(|cx| cx.platform_info().os);
for keystroke in input
.split("")
.map(|source| Keystroke::parse_with_os(source, os))
.map(Result::unwrap)
{
self.dispatch_keystroke(window, keystroke);
}
+2 -1
View File
@@ -223,8 +223,9 @@ impl VisualTestAppContext {
///
/// Keystrokes are specified as a space-separated string, e.g., "cmd-p escape".
pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
let os = self.app.borrow().platform_info().os;
for keystroke_text in keystrokes.split_whitespace() {
let keystroke = Keystroke::parse(keystroke_text)
let keystroke = Keystroke::parse_with_os(keystroke_text, os)
.unwrap_or_else(|_| panic!("Invalid keystroke: {}", keystroke_text));
self.dispatch_keystroke(window, keystroke);
}
+8 -6
View File
@@ -2731,12 +2731,12 @@ impl Interactivity {
};
if let Some(source_location) = self.source_location
&& text_bounds.contains(&window.mouse_position())
&& window.modifiers().secondary()
&& window.modifiers().secondary(cx)
{
let secondary_held = window.modifiers().secondary();
let secondary_held = window.modifiers().secondary(cx);
window.on_key_event({
move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
if e.modifiers.secondary() != secondary_held
move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
if e.modifiers.secondary(cx) != secondary_held
&& text_bounds.contains(&window.mouse_position())
{
window.refresh();
@@ -5505,7 +5505,8 @@ mod tests {
}
fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
let keystroke = Keystroke::parse(key).unwrap();
let os = cx.read(|cx| cx.platform_info().os);
let keystroke = Keystroke::parse_with_os(key, os).unwrap();
cx.update_window(window, |_, window, cx| {
window.dispatch_event(
KeyDownEvent {
@@ -5521,7 +5522,8 @@ mod tests {
}
fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
let keystroke = Keystroke::parse(key).unwrap();
let os = cx.read(|cx| cx.platform_info().os);
let keystroke = Keystroke::parse_with_os(key, os).unwrap();
cx.update_window(window, |_, window, cx| {
window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
})
+1 -1
View File
@@ -1117,7 +1117,7 @@ mod tests {
fn dispatch(
tree: &mut DispatchTree,
pending: SmallVec<[Keystroke; 1]>,
key: &str,
key: &'static str,
path: &DispatchPath,
) -> DispatchResult {
tree.dispatch_key(pending, Keystroke::parse(key).unwrap(), path)
+11 -3
View File
@@ -868,7 +868,11 @@ mod tests {
fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
let actual = keymap
.bindings_for_action(action)
.map(|binding| binding.keystrokes[0].inner().unparse())
.map(|binding| {
binding.keystrokes[0]
.inner()
.unparse(crate::OperatingSystem::Mac)
})
.collect::<Vec<_>>();
assert_eq!(actual, expected, "{:?}", action);
}
@@ -921,7 +925,11 @@ mod tests {
fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
let actual = keymap
.bindings_for_action(action)
.map(|binding| binding.keystrokes[0].inner().unparse())
.map(|binding| {
binding.keystrokes[0]
.inner()
.unparse(crate::OperatingSystem::Mac)
})
.collect::<Vec<_>>();
assert_eq!(actual, expected, "{:?}", action);
}
@@ -1124,7 +1132,7 @@ mod tests {
binding
.keystrokes()
.iter()
.map(|keystroke| keystroke.inner().unparse())
.map(|keystroke| keystroke.inner().unparse(crate::OperatingSystem::Mac))
.collect::<Vec<_>>()
.join(" "),
binding.action().name(),
+27 -4
View File
@@ -29,17 +29,20 @@ impl Clone for KeyBinding {
}
impl KeyBinding {
/// Construct a new keybinding from the given data. Panics on parse error.
pub fn new<A: Action>(keystrokes: &str, action: A, context: Option<&str>) -> Self {
/// Constructs a static keybinding with explicit modifiers. Panics on parse error.
///
/// Use [`Self::load`] for dynamic input or to resolve `secondary-` using the host OS.
pub fn new<A: Action>(keystrokes: &'static str, action: A, context: Option<&str>) -> Self {
let context_predicate =
context.map(|context| KeyBindingContextPredicate::parse(context).unwrap().into());
Self::load(
Self::load_internal(
keystrokes,
Box::new(action),
context_predicate,
false,
None,
&DummyKeyboardMapper,
Keystroke::parse,
)
.unwrap()
}
@@ -51,12 +54,32 @@ impl KeyBinding {
context_predicate: Option<Rc<KeyBindingContextPredicate>>,
use_key_equivalents: bool,
action_input: Option<SharedString>,
cx: &crate::App,
) -> std::result::Result<Self, InvalidKeystrokeError> {
Self::load_internal(
keystrokes,
action,
context_predicate,
use_key_equivalents,
action_input,
cx.keyboard_mapper().as_ref(),
|source| Keystroke::parse_with_os(source, cx.platform_info().os),
)
}
fn load_internal<'a>(
keystrokes: &'a str,
action: Box<dyn Action>,
context_predicate: Option<Rc<KeyBindingContextPredicate>>,
use_key_equivalents: bool,
action_input: Option<SharedString>,
keyboard_mapper: &dyn PlatformKeyboardMapper,
parse_keystroke: impl Fn(&'a str) -> std::result::Result<Keystroke, InvalidKeystrokeError>,
) -> std::result::Result<Self, InvalidKeystrokeError> {
let keystrokes: SmallVec<[KeybindingKeystroke; 2]> = keystrokes
.split_whitespace()
.map(|source| {
let keystroke = Keystroke::parse(source)?;
let keystroke = parse_keystroke(source)?;
Ok(KeybindingKeystroke::new_with_mapper(
keystroke,
use_key_equivalents,
+13 -15
View File
@@ -27,22 +27,20 @@ impl<'a> TryFrom<&'a str> for KeyContext {
}
impl KeyContext {
/// Initialize a new [`KeyContext`] that contains an `os` key set to either `macos`, `linux`, `windows` or `unknown`.
pub fn new_with_defaults() -> Self {
/// Initializes a key context with the supplied host operating system.
pub fn new_with_defaults(os: crate::OperatingSystem) -> Self {
let mut context = Self::default();
#[cfg(target_os = "macos")]
context.set("os", "macos");
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
context.set("os", "linux");
#[cfg(target_os = "windows")]
context.set("os", "windows");
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "windows"
)))]
context.set("os", "unknown");
context.set(
"os",
match os {
crate::OperatingSystem::Mac => "macos",
crate::OperatingSystem::Linux | crate::OperatingSystem::FreeBsd => "linux",
crate::OperatingSystem::Windows => "windows",
crate::OperatingSystem::Ios => "ios",
crate::OperatingSystem::Android => "android",
crate::OperatingSystem::Unknown => "unknown",
},
);
context
}
+6
View File
@@ -1,6 +1,7 @@
mod app_menu;
mod keyboard;
mod keystroke;
mod platform_info;
#[cfg(all(target_os = "linux", feature = "wayland"))]
#[expect(missing_docs)]
@@ -359,8 +360,13 @@ bitflags::bitflags! {
}
}
pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
#[expect(missing_docs)]
pub trait Platform: 'static {
/// Returns the host OS and application target reported by this backend.
fn platform_info(&self) -> PlatformInfo;
fn background_executor(&self) -> BackgroundExecutor;
fn foreground_executor(&self) -> ForegroundExecutor;
fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
+117 -94
View File
@@ -5,7 +5,7 @@ use std::{
fmt::{Display, Write},
};
use crate::PlatformKeyboardMapper;
use crate::{OperatingSystem, PlatformKeyboardMapper};
/// This is a helper trait so that we can simplify the implementation of some functions
pub trait AsKeystroke {
@@ -112,12 +112,27 @@ impl Keystroke {
target.inner.modifiers == self.modifiers && target.inner.key == self.key
}
/// key syntax is:
/// [secondary-][ctrl-][alt-][shift-][cmd-][fn-]key[->key_char]
/// key_char syntax is only used for generating test events,
/// secondary means "cmd" on macOS and "ctrl" on other platforms
/// when matching a key with an key_char set will be matched without it.
pub fn parse(source: &str) -> std::result::Result<Self, InvalidKeystrokeError> {
/// Parses a static keystroke with explicit, platform-independent modifiers.
///
/// Syntax: `[ctrl-][alt-][shift-][cmd-][fn-]key[->key_char]`.
/// The `key_char` suffix is used for generating test events.
/// Use [`Self::parse_with_os`] for dynamic input or the `secondary-` alias.
pub fn parse(source: &'static str) -> std::result::Result<Self, InvalidKeystrokeError> {
Self::parse_internal(source, None)
}
/// Parses a keystroke, resolving `secondary-` using the supplied host OS.
pub fn parse_with_os(
source: &str,
os: OperatingSystem,
) -> std::result::Result<Self, InvalidKeystrokeError> {
Self::parse_internal(source, Some(os))
}
fn parse_internal(
source: &str,
os: Option<OperatingSystem>,
) -> std::result::Result<Self, InvalidKeystrokeError> {
let mut modifiers = Modifiers::none();
let mut key = None;
let mut key_char = None;
@@ -141,7 +156,10 @@ impl Keystroke {
continue;
}
if component.eq_ignore_ascii_case("secondary") {
if cfg!(target_os = "macos") {
let os = os.ok_or_else(|| InvalidKeystrokeError {
keystroke: source.to_owned(),
})?;
if os == OperatingSystem::Mac {
modifiers.platform = true;
} else {
modifiers.control = true;
@@ -219,9 +237,18 @@ impl Keystroke {
})
}
/// Produces a representation of this key that Parse can understand.
pub fn unparse(&self) -> String {
unparse(&self.modifiers, &self.key)
/// Serializes this keystroke with the supplied host OS's modifier spelling.
pub fn unparse(&self, os: OperatingSystem) -> String {
unparse(&self.modifiers, &self.key, os)
}
/// Formats this keystroke using the supplied host OS's key labels.
pub fn display(&self, os: OperatingSystem) -> KeystrokeDisplay<'_> {
KeystrokeDisplay {
modifiers: &self.modifiers,
key: &self.key,
os,
}
}
/// Returns true if this keystroke left
@@ -264,6 +291,15 @@ impl Keystroke {
}
impl KeybindingKeystroke {
/// Formats this binding using the supplied host OS's key labels.
pub fn display(&self, os: OperatingSystem) -> KeystrokeDisplay<'_> {
KeystrokeDisplay {
modifiers: self.modifiers(),
key: self.key(),
os,
}
}
#[cfg(target_os = "windows")]
#[expect(missing_docs)]
pub fn new(inner: Keystroke, display_modifiers: Modifiers, display_key: String) -> Self {
@@ -357,15 +393,15 @@ impl KeybindingKeystroke {
self.inner.key = key;
}
/// Produces a representation of this key that Parse can understand.
pub fn unparse(&self) -> String {
/// Serializes this binding with the supplied host OS's modifier spelling.
pub fn unparse(&self, os: OperatingSystem) -> String {
#[cfg(target_os = "windows")]
{
unparse(&self.display_modifiers, &self.display_key)
unparse(&self.display_modifiers, &self.display_key, os)
}
#[cfg(not(target_os = "windows"))]
{
unparse(&self.inner.modifiers, &self.inner.key)
unparse(&self.inner.modifiers, &self.inner.key, os)
}
}
@@ -429,17 +465,17 @@ fn is_printable_key(key: &str) -> bool {
)
}
impl std::fmt::Display for Keystroke {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
display_modifiers(&self.modifiers, f)?;
display_key(&self.key, f)
}
/// A keystroke formatted with an explicit host operating system.
pub struct KeystrokeDisplay<'a> {
modifiers: &'a Modifiers,
key: &'a str,
os: OperatingSystem,
}
impl std::fmt::Display for KeybindingKeystroke {
impl std::fmt::Display for KeystrokeDisplay<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
display_modifiers(self.modifiers(), f)?;
display_key(self.key(), f)
display_modifiers(self.modifiers, self.os, f)?;
display_key(self.key, self.os, f)
}
}
@@ -480,14 +516,10 @@ impl Modifiers {
///
/// On macOS, this is the command key.
/// On Linux and Windows, this is the control key.
pub fn secondary(&self) -> bool {
#[cfg(target_os = "macos")]
{
pub fn secondary(&self, cx: &crate::App) -> bool {
if cx.platform_info().is_mac() {
self.platform
}
#[cfg(not(target_os = "macos"))]
{
} else {
self.control
}
}
@@ -514,18 +546,14 @@ impl Modifiers {
}
}
/// A Returns [`Modifiers`] with just the secondary key pressed.
pub fn secondary_key() -> Modifiers {
#[cfg(target_os = "macos")]
{
/// Returns [`Modifiers`] with just the secondary key pressed.
pub fn secondary_key(cx: &crate::App) -> Modifiers {
if cx.platform_info().is_mac() {
Modifiers {
platform: true,
..Default::default()
}
}
#[cfg(not(target_os = "macos"))]
{
} else {
Modifiers {
control: true,
..Default::default()
@@ -686,65 +714,60 @@ impl<T: AsKeystroke + ?Sized> AsKeystroke for &T {
}
}
fn display_modifiers(modifiers: &Modifiers, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn display_modifiers(
modifiers: &Modifiers,
os: OperatingSystem,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
if modifiers.control {
#[cfg(target_os = "macos")]
f.write_char('^')?;
#[cfg(not(target_os = "macos"))]
write!(f, "ctrl-")?;
f.write_str(if os == OperatingSystem::Mac {
"^"
} else {
"ctrl-"
})?;
}
if modifiers.alt {
#[cfg(target_os = "macos")]
f.write_char('⌥')?;
#[cfg(not(target_os = "macos"))]
write!(f, "alt-")?;
f.write_str(if os == OperatingSystem::Mac {
"⌥"
} else {
"alt-"
})?;
}
if modifiers.platform {
#[cfg(target_os = "macos")]
f.write_char('⌘')?;
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
f.write_char('❖')?;
#[cfg(target_os = "windows")]
f.write_char('⊞')?;
f.write_str(match os {
OperatingSystem::Mac => "⌘",
OperatingSystem::Windows => "⊞",
OperatingSystem::Linux | OperatingSystem::FreeBsd => "❖",
OperatingSystem::Ios | OperatingSystem::Android | OperatingSystem::Unknown => "cmd-",
})?;
}
if modifiers.shift {
#[cfg(target_os = "macos")]
f.write_char('⇧')?;
#[cfg(not(target_os = "macos"))]
write!(f, "shift-")?;
f.write_str(if os == OperatingSystem::Mac {
"⇧"
} else {
"shift-"
})?;
}
Ok(())
}
fn display_key(key: &str, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn display_key(
key: &str,
os: OperatingSystem,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
let key = match key {
#[cfg(target_os = "macos")]
"backspace" => '⌫',
#[cfg(target_os = "macos")]
"up" => '↑',
#[cfg(target_os = "macos")]
"down" => '↓',
#[cfg(target_os = "macos")]
"left" => '←',
#[cfg(target_os = "macos")]
"right" => '→',
#[cfg(target_os = "macos")]
"tab" => '⇥',
#[cfg(target_os = "macos")]
"escape" => '⎋',
#[cfg(target_os = "macos")]
"shift" => '⇧',
#[cfg(target_os = "macos")]
"control" => '⌃',
#[cfg(target_os = "macos")]
"alt" => '⌥',
#[cfg(target_os = "macos")]
"platform" => '⌘',
"backspace" if os == OperatingSystem::Mac => '⌫',
"up" if os == OperatingSystem::Mac => '↑',
"down" if os == OperatingSystem::Mac => '↓',
"left" if os == OperatingSystem::Mac => '←',
"right" if os == OperatingSystem::Mac => '→',
"tab" if os == OperatingSystem::Mac => '⇥',
"escape" if os == OperatingSystem::Mac => '⎋',
"shift" if os == OperatingSystem::Mac => '⇧',
"control" if os == OperatingSystem::Mac => '⌃',
"alt" if os == OperatingSystem::Mac => '⌥',
"platform" if os == OperatingSystem::Mac => '⌘',
key if key.len() == 1 => key.chars().next().unwrap().to_ascii_uppercase(),
key => return f.write_str(key),
@@ -753,7 +776,7 @@ fn display_key(key: &str, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
}
#[inline]
fn unparse(modifiers: &Modifiers, key: &str) -> String {
fn unparse(modifiers: &Modifiers, key: &str, os: OperatingSystem) -> String {
let mut result = String::new();
if modifiers.function {
result.push_str("fn-");
@@ -765,14 +788,14 @@ fn unparse(modifiers: &Modifiers, key: &str) -> String {
result.push_str("alt-");
}
if modifiers.platform {
#[cfg(target_os = "macos")]
result.push_str("cmd-");
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
result.push_str("super-");
#[cfg(target_os = "windows")]
result.push_str("win-");
result.push_str(match os {
OperatingSystem::Windows => "win-",
OperatingSystem::Linux
| OperatingSystem::FreeBsd
| OperatingSystem::Android
| OperatingSystem::Unknown => "super-",
OperatingSystem::Mac | OperatingSystem::Ios => "cmd-",
});
}
if modifiers.shift {
result.push_str("shift-");
+49
View File
@@ -0,0 +1,49 @@
//! Runtime identity of the host operating system and application target.
//!
//! Host conventions are independent of the backend delivering the application:
//! a browser on macOS follows Mac keyboard conventions without native Mac APIs.
//! Backends provide this identity; consumers read it through the application.
/// The host operating system and the kind of application delivering the UI.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PlatformInfo {
/// The operating system whose input conventions the application follows.
pub os: OperatingSystem,
/// How the application is delivered, independently of its host OS.
pub target: PlatformTarget,
}
/// The host operating system, including when the application runs in a browser.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OperatingSystem {
/// Apple's desktop operating system.
Mac,
/// Microsoft Windows.
Windows,
/// Linux, including browser hosts running ChromeOS.
Linux,
/// FreeBSD.
FreeBsd,
/// iOS and iPadOS.
Ios,
/// Android.
Android,
/// The backend could not identify the host operating system.
Unknown,
}
/// The kind of application delivering the UI, independently of its host OS.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PlatformTarget {
/// A native application, including headless execution.
Native,
/// An application running in a browser.
Web,
}
impl PlatformInfo {
/// Whether the host operating system is macOS.
pub fn is_mac(self) -> bool {
self.os == OperatingSystem::Mac
}
}
+32
View File
@@ -29,6 +29,7 @@ use std::{
/// TestPlatform implements the Platform trait for use in tests.
pub(crate) struct TestPlatform {
pub(crate) platform_info: Cell<crate::PlatformInfo>,
background_executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
@@ -204,6 +205,33 @@ impl TestPlatform {
>,
) -> Rc<Self> {
Rc::new_cyclic(|weak| TestPlatform {
platform_info: Cell::new(crate::PlatformInfo {
os: std::cfg_select! {
target_os = "macos" => { crate::OperatingSystem::Mac }
target_os = "windows" => { crate::OperatingSystem::Windows }
target_os = "linux" => { crate::OperatingSystem::Linux }
target_os = "freebsd" => { crate::OperatingSystem::FreeBsd }
target_os = "ios" => { crate::OperatingSystem::Ios }
target_os = "android" => { crate::OperatingSystem::Android }
target_family = "wasm" => {
// Browser tests must supply the host OS with set_platform_info.
crate::OperatingSystem::Unknown
}
_ => { compile_error!("unsupported test platform operating system") }
},
target: std::cfg_select! {
target_family = "wasm" => { crate::PlatformTarget::Web }
any(
target_os = "macos",
target_os = "windows",
target_os = "linux",
target_os = "freebsd",
target_os = "ios",
target_os = "android"
) => { crate::PlatformTarget::Native }
_ => { compile_error!("unsupported test platform target") }
},
}),
background_executor: executor,
foreground_executor,
#[cfg(any(test, feature = "test-support"))]
@@ -433,6 +461,10 @@ impl TestPlatform {
}
impl Platform for TestPlatform {
fn platform_info(&self) -> crate::PlatformInfo {
self.platform_info.get()
}
fn background_executor(&self) -> BackgroundExecutor {
self.background_executor.clone()
}
+4
View File
@@ -65,6 +65,10 @@ impl VisualTestPlatform {
}
impl Platform for VisualTestPlatform {
fn platform_info(&self) -> crate::PlatformInfo {
self.platform.platform_info()
}
fn background_executor(&self) -> BackgroundExecutor {
self.background_executor.clone()
}
+2 -2
View File
@@ -5615,13 +5615,13 @@ impl Window {
/// Return a key binding string for an action, to display in the UI. Uses the highest precedence
/// binding for the action (last binding added to the keymap).
pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
self.highest_precedence_binding_for_action(action)
.map(|binding| {
binding
.keystrokes()
.iter()
.map(ToString::to_string)
.map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
.collect::<Vec<_>>()
.join(" ")
})
+7
View File
@@ -181,6 +181,13 @@ impl PlatformKeyboardLayout for IosKeyboardLayout {
}
impl Platform for IosPlatform {
fn platform_info(&self) -> gpui::PlatformInfo {
gpui::PlatformInfo {
os: gpui::OperatingSystem::Ios,
target: gpui::PlatformTarget::Native,
}
}
fn on_displays_changed(&self, callback: Box<dyn FnMut()>) {
self.0.displays_changed_callback.set(callback);
}
+11
View File
@@ -548,6 +548,17 @@ impl Drop for LinuxPlatform {
}
impl Platform for LinuxPlatform {
fn platform_info(&self) -> gpui::PlatformInfo {
gpui::PlatformInfo {
os: if cfg!(target_os = "freebsd") {
gpui::OperatingSystem::FreeBsd
} else {
gpui::OperatingSystem::Linux
},
target: gpui::PlatformTarget::Native,
}
}
fn background_executor(&self) -> BackgroundExecutor {
self.with_common(|common| common.background_executor.clone())
}
+13 -3
View File
@@ -347,11 +347,14 @@ impl MacPlatform {
.find_or_first(|binding| {
binding.predicate().is_none_or(|predicate| {
predicate.eval(DEFAULT_CONTEXT.get_or_init(|| {
let mut workspace_context = KeyContext::new_with_defaults();
let mut workspace_context =
KeyContext::new_with_defaults(gpui::OperatingSystem::Mac);
workspace_context.add("Workspace");
let mut pane_context = KeyContext::new_with_defaults();
let mut pane_context =
KeyContext::new_with_defaults(gpui::OperatingSystem::Mac);
pane_context.add("Pane");
let mut editor_context = KeyContext::new_with_defaults();
let mut editor_context =
KeyContext::new_with_defaults(gpui::OperatingSystem::Mac);
editor_context.add("Editor");
pane_context.extend(&editor_context);
@@ -499,6 +502,13 @@ impl MacPlatform {
}
impl Platform for MacPlatform {
fn platform_info(&self) -> gpui::PlatformInfo {
gpui::PlatformInfo {
os: gpui::OperatingSystem::Mac,
target: gpui::PlatformTarget::Native,
}
}
fn background_executor(&self) -> BackgroundExecutor {
self.0.lock().background_executor.clone()
}
+36 -11
View File
@@ -1301,21 +1301,46 @@ fn capslock_from_keyboard_event(event: &web_sys::KeyboardEvent) -> Capslock {
}
pub(crate) fn is_mac_platform(browser_window: &web_sys::Window) -> bool {
let navigator = browser_window.navigator();
// iOS hardware keyboards also use Option for text composition.
matches!(
platform_info(browser_window).os,
gpui::OperatingSystem::Mac | gpui::OperatingSystem::Ios
)
}
pub(crate) fn platform_info(browser_window: &web_sys::Window) -> gpui::PlatformInfo {
let navigator = browser_window.navigator();
let user_agent = navigator.user_agent().unwrap_or_default();
#[allow(deprecated)]
// navigator.platform() is deprecated but navigator.userAgentData is not widely available yet
if let Ok(platform) = navigator.platform() {
if platform.contains("Mac") {
return true;
}
let platform = navigator.platform().unwrap_or_default();
let os = if user_agent.contains("Android") {
gpui::OperatingSystem::Android
} else if user_agent.contains("iPhone")
|| user_agent.contains("iPad")
|| user_agent.contains("iPod")
|| (platform.contains("Mac") && navigator.max_touch_points() > 1)
{
// iPadOS can advertise a desktop Mac user agent.
gpui::OperatingSystem::Ios
} else if platform.contains("Mac") || user_agent.contains("Mac") {
gpui::OperatingSystem::Mac
} else if platform.contains("Win") || user_agent.contains("Windows") {
gpui::OperatingSystem::Windows
} else if platform.contains("FreeBSD") || user_agent.contains("FreeBSD") {
gpui::OperatingSystem::FreeBsd
} else if platform.contains("Linux")
|| user_agent.contains("Linux")
|| user_agent.contains("CrOS")
{
gpui::OperatingSystem::Linux
} else {
gpui::OperatingSystem::Unknown
};
gpui::PlatformInfo {
os,
target: gpui::PlatformTarget::Web,
}
if let Ok(user_agent) = navigator.user_agent() {
return user_agent.contains("Mac");
}
false
}
fn is_modifier_only_key(key: &str) -> bool {
+7
View File
@@ -31,6 +31,7 @@ use wasm_bindgen::prelude::*;
/// through [`gpui::App::text_system`] before opening a window.
pub struct WebPlatform {
browser_window: web_sys::Window,
platform_info: gpui::PlatformInfo,
dispatcher: Arc<WebDispatcher>,
background_executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
@@ -170,6 +171,7 @@ impl WebPlatform {
) -> Self {
let browser_window =
web_sys::window().expect("must be running in a browser window context");
let platform_info = crate::events::platform_info(&browser_window);
let dispatcher = Arc::new(WebDispatcher::new(
browser_window.clone(),
allow_multi_threading,
@@ -194,6 +196,7 @@ impl WebPlatform {
Self {
browser_window,
platform_info,
dispatcher,
background_executor,
foreground_executor,
@@ -304,6 +307,10 @@ async fn initialize_graphics(
}
impl Platform for WebPlatform {
fn platform_info(&self) -> gpui::PlatformInfo {
self.platform_info
}
fn background_executor(&self) -> BackgroundExecutor {
self.background_executor.clone()
}
+7
View File
@@ -529,6 +529,13 @@ fn encode_restart_arguments(arguments: &[OsString]) -> OsString {
}
impl Platform for WindowsPlatform {
fn platform_info(&self) -> gpui::PlatformInfo {
gpui::PlatformInfo {
os: gpui::OperatingSystem::Windows,
target: gpui::PlatformTarget::Native,
}
}
fn background_executor(&self) -> BackgroundExecutor {
self.background_executor.clone()
}
+19 -10
View File
@@ -698,6 +698,7 @@ impl KeymapEditor {
let action_query = self.current_action_query(cx);
let keystroke_query = self.current_keystroke_query(cx);
let exact_match = self.search_mode.exact_match();
let os = cx.platform_info().os;
let timer = cx.background_executor().timer(Duration::from_secs(1));
self.search_query_debounce = Some(cx.background_spawn({
@@ -708,7 +709,7 @@ impl KeymapEditor {
let keystroke_query = keystroke_query
.into_iter()
.map(|keystroke| keystroke.inner().unparse())
.map(|keystroke| keystroke.inner().unparse(os))
.collect::<Vec<String>>()
.join(" ");
@@ -1019,8 +1020,8 @@ impl KeymapEditor {
.detach_and_log_err(cx);
}
fn key_context(&self) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
fn key_context(&self, cx: &App) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("KeymapEditor");
dispatch_context.add("menu");
@@ -1459,12 +1460,14 @@ impl KeymapEditor {
));
let keyboard_mapper = cx.keyboard_mapper().clone();
let deprecated_aliases = cx.deprecated_actions_to_preferred_actions().clone();
let os = cx.platform_info().os;
cx.spawn(async move |_, _| {
remove_keybinding(
to_remove,
&fs,
keyboard_mapper.as_ref(),
&deprecated_aliases,
os,
)
.await
})
@@ -2010,7 +2013,7 @@ impl Render for KeymapEditor {
v_flex()
.id("keymap-editor")
.track_focus(focus_handle)
.key_context(self.key_context())
.key_context(self.key_context(cx))
.on_action(cx.listener(Self::select_next))
.on_action(cx.listener(Self::select_previous))
.on_action(cx.listener(Self::select_first))
@@ -2043,7 +2046,7 @@ impl Render for KeymapEditor {
.child(
h_flex()
.key_context({
let mut context = KeyContext::new_with_defaults();
let mut context = KeyContext::new_with_defaults(cx.platform_info().os);
context.add("BufferSearchBar");
context
})
@@ -2866,6 +2869,7 @@ impl KeybindingEditorModal {
let create = self.creating;
let keyboard_mapper = cx.keyboard_mapper().clone();
let deprecated_aliases = cx.deprecated_actions_to_preferred_actions().clone();
let os = cx.platform_info().os;
let action_name = self
.get_selected_action_name(cx)
@@ -2897,6 +2901,7 @@ impl KeybindingEditorModal {
&fs,
keyboard_mapper.as_ref(),
&deprecated_aliases,
os,
)
.await
{
@@ -2984,14 +2989,14 @@ impl KeybindingEditorModal {
})
}
fn key_context(&self) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults();
fn key_context(&self, cx: &App) -> KeyContext {
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("KeybindEditorModal");
key_context
}
fn key_context_internal(&self, window: &Window, cx: &App) -> KeyContext {
let mut key_context = self.key_context();
let mut key_context = self.key_context(cx);
if self.is_any_editor_showing_completions(window, cx) {
key_context.add("showing_completions");
@@ -3636,6 +3641,7 @@ async fn save_keybinding_update(
fs: &Arc<dyn Fs>,
keyboard_mapper: &dyn PlatformKeyboardMapper,
deprecated_aliases: &HashMap<&'static str, &'static str>,
os: gpui::OperatingSystem,
) -> anyhow::Result<()> {
let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
.await
@@ -3678,7 +3684,7 @@ async fn save_keybinding_update(
}
};
let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry(os);
let updated_keymap_contents = settings::KeymapFile::update_keybinding(
operation,
@@ -3686,6 +3692,7 @@ async fn save_keybinding_update(
tab_size,
keyboard_mapper,
deprecated_aliases,
os,
)
.map_err(|err| err.context("Could not save updated keybinding"))?;
fs.write(
@@ -3709,6 +3716,7 @@ async fn remove_keybinding(
fs: &Arc<dyn Fs>,
keyboard_mapper: &dyn PlatformKeyboardMapper,
deprecated_aliases: &HashMap<&'static str, &'static str>,
os: gpui::OperatingSystem,
) -> anyhow::Result<()> {
let Some(keystrokes) = existing.keystrokes() else {
anyhow::bail!("Cannot remove a keybinding that does not exist");
@@ -3732,13 +3740,14 @@ async fn remove_keybinding(
target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
};
let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry(os);
let updated_keymap_contents = settings::KeymapFile::update_keybinding(
operation,
keymap_contents,
tab_size,
keyboard_mapper,
deprecated_aliases,
os,
)
.context("Failed to update keybinding")?;
fs.write(
@@ -716,7 +716,8 @@ mod tests {
keystroke_input.to_string()
};
let mut keystroke = Keystroke::parse(&keystroke_str)
let os = self.cx.read(|cx| cx.platform_info().os);
let mut keystroke = Keystroke::parse_with_os(&keystroke_str, os)
.unwrap_or_else(|_| panic!("Invalid keystroke: {}", keystroke_input));
// Remove the dummy key if we added it for modifier-only keystrokes
@@ -792,7 +793,8 @@ mod tests {
s.to_string()
};
let mut keystroke = Keystroke::parse(&keystroke_str)?;
let mut keystroke =
Keystroke::parse_with_os(&keystroke_str, gpui::OperatingSystem::Mac)?;
// Remove the dummy key if we added it for modifier-only keystrokes
if s.ends_with('-') && keystroke_str.ends_with("_") {
@@ -812,20 +814,23 @@ mod tests {
"Keystroke count mismatch. Expected: {:?}, Actual: {:?}",
expected_keystrokes
.iter()
.map(|k| k.unparse())
.map(|k| k.unparse(gpui::OperatingSystem::Mac))
.collect::<Vec<_>>(),
actual.iter().map(|k| k.unparse()).collect::<Vec<_>>()
actual
.iter()
.map(|k| k.unparse(gpui::OperatingSystem::Mac))
.collect::<Vec<_>>()
);
for (i, (actual, expected)) in actual.iter().zip(expected_keystrokes.iter()).enumerate()
{
assert_eq!(
actual.unparse(),
expected.unparse(),
actual.unparse(gpui::OperatingSystem::Mac),
expected.unparse(gpui::OperatingSystem::Mac),
"Keystroke {} mismatch. Expected: '{}', Actual: '{}'",
i,
expected.unparse(),
actual.unparse()
expected.unparse(gpui::OperatingSystem::Mac),
actual.unparse(gpui::OperatingSystem::Mac)
);
}
}
@@ -1119,7 +1124,9 @@ mod tests {
}
fn keystrokes_str(ks: &[KeybindingKeystroke]) -> String {
ks.iter().map(|ks| ks.inner().unparse()).join(" ")
ks.iter()
.map(|ks| ks.inner().unparse(gpui::OperatingSystem::Mac))
.join(" ")
}
}
}
@@ -1139,7 +1146,10 @@ mod tests {
KeystrokeInputTestHelper::new(cx)
}
fn init_dispatch_test(cx: &mut TestAppContext, binding: &str) -> KeystrokeInputTestHelper {
fn init_dispatch_test(
cx: &mut TestAppContext,
binding: &'static str,
) -> KeystrokeInputTestHelper {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);
@@ -45,9 +45,14 @@ impl KeyContextView {
let mut possibilities = cx.all_bindings_for_input(&pending);
possibilities.reverse();
this.last_keystrokes = Some(
json!(pending.iter().map(|p| p.unparse()).join(" "))
.to_string()
.into(),
json!(
pending
.iter()
.map(|p| p.unparse(cx.platform_info().os))
.join(" ")
)
.to_string()
.into(),
);
this.context_stack = e.context_stack.clone();
this.last_possibilities = possibilities
@@ -249,7 +254,7 @@ impl Render for KeyContextView {
el.child(
Label::new(format!(
"Waiting for more input: {}",
keystrokes.iter().map(|k| k.unparse()).join(" ")
keystrokes.iter().map(|k| k.unparse(cx.platform_info().os)).join(" ")
))
.ml(px(12.)),
)
+7 -4
View File
@@ -1147,7 +1147,8 @@ mod tests {
let screen_coord = cx
.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx))
.unwrap();
cx.simulate_click(screen_coord, gpui::Modifiers::secondary_key());
let modifiers = cx.read(gpui::Modifiers::secondary_key);
cx.simulate_click(screen_coord, modifiers);
cx.run_until_parked();
assert!(
@@ -1432,7 +1433,7 @@ mod tests {
let modifiers = Modifiers {
shift,
alt: split,
..Modifiers::secondary_key()
..cx.read(Modifiers::secondary_key)
};
let mut expected_requests = Vec::new();
let query = lsp::TextDocumentPositionParams {
@@ -1569,9 +1570,11 @@ mod tests {
.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx))
.expect("click pixel");
if empty_hover {
cx.simulate_mouse_move(position, None, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_mouse_move(position, None, modifiers);
}
cx.simulate_click(position, Modifiers::secondary_key());
let modifiers = cx.read(Modifiers::secondary_key);
cx.simulate_click(position, modifiers);
cx.simulate_modifiers_change(Modifiers::none());
(cx, requests)
}
+1 -1
View File
@@ -306,7 +306,7 @@ impl Render for Onboarding {
div()
.image_cache(gpui::retain_all("onboarding-page"))
.key_context({
let mut ctx = KeyContext::new_with_defaults();
let mut ctx = KeyContext::new_with_defaults(cx.platform_info().os);
ctx.add("Onboarding");
ctx.add("menu");
ctx
+1 -1
View File
@@ -1334,7 +1334,7 @@ impl OutlinePanel {
}
fn dispatch_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("OutlinePanel");
dispatch_context.add("menu");
let identifier = if self.filter_editor.focus_handle(cx).is_focused(window) {
+1 -1
View File
@@ -1431,7 +1431,7 @@ impl<D: PickerDelegate> Picker<D> {
})
})
.on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
this.handle_click(ix, event.modifiers().secondary(), window, cx)
this.handle_click(ix, event.modifiers().secondary(cx), window, cx)
}))
// As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
// and produces right mouse button events. This matches platforms norms
+3 -3
View File
@@ -6522,7 +6522,7 @@ impl ProjectPanel {
project_panel.marked_entries.push(clicked_entry);
}
}
} else if event.modifiers().secondary() {
} else if event.modifiers().secondary(cx) {
if event.click_count() > 1 {
project_panel.split_entry(entry_id, false, None, cx);
} else {
@@ -7199,7 +7199,7 @@ impl ProjectPanel {
}
fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("ProjectPanel");
dispatch_context.add("menu");
@@ -7747,7 +7747,7 @@ impl Render for ProjectPanel {
active_indent_guide: &IndentGuideLayout,
window,
cx| {
if window.modifiers().secondary() {
if window.modifiers().secondary(cx) {
let ix = active_indent_guide.offset.y;
let Some((target_entry, worktree)) = maybe!({
let (worktree_id, entry) =
@@ -5850,7 +5850,7 @@ async fn test_range_selection_drag_moves_entire_folded_directories(cx: &mut Test
// directory, which the range selection must still widen to the whole row.
for (range_selection, source_click_modifiers, copy, (source_path, target_path)) in iproduct!(
[RangeSelection::ShiftClick, RangeSelection::ShiftArrows],
[Modifiers::none(), Modifiers::secondary_key()],
[Modifiers::none(), cx.read(Modifiers::secondary_key)],
[false, true],
[
("project/root/a", "project/root/other"),
+1 -1
View File
@@ -1458,7 +1458,7 @@ impl NotebookEditor {
impl Render for NotebookEditor {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("NotebookEditor");
key_context.set(
"notebook_mode",
+1 -1
View File
@@ -414,7 +414,7 @@ impl Render for BufferSearchBar {
.child(replace_actions)
});
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("BufferSearchBar");
if in_replace {
key_context.add("in_replace");
+1 -1
View File
@@ -5,7 +5,7 @@ use super::TextFinder;
impl Render for TextFinder {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("TextFinder");
v_flex()
+26 -17
View File
@@ -426,7 +426,7 @@ impl KeymapFile {
context,
use_key_equivalents,
action_input_string.map(SharedString::from),
cx.keyboard_mapper().as_ref(),
cx,
) {
Ok(key_binding) => key_binding,
Err(InvalidKeystrokeError { keystroke }) => {
@@ -480,7 +480,7 @@ impl KeymapFile {
key_binding.predicate(),
use_key_equivalents,
key_binding.action_input(),
cx.keyboard_mapper().as_ref(),
cx,
)
.map_err(|InvalidKeystrokeError { keystroke }| {
format!(
@@ -894,6 +894,7 @@ impl KeymapFile {
tab_size: usize,
keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
deprecated_aliases: &HashMap<&'static str, &'static str>,
os: gpui::OperatingSystem,
) -> Result<String> {
// When replacing or removing a non-user binding, we may need to write an unbind entry
// to suppress the original default binding.
@@ -906,7 +907,7 @@ impl KeymapFile {
source,
target,
} if *target_source != KeybindSource::User => {
if target.keystrokes_unparsed() != source.keystrokes_unparsed() {
if target.keystrokes_unparsed(os) != source.keystrokes_unparsed(os) {
suppression_unbind = Some(target.clone());
}
operation = KeybindUpdateOperation::Add {
@@ -944,6 +945,7 @@ impl KeymapFile {
&target_action_value,
keyboard_mapper,
deprecated_aliases,
os,
) else {
anyhow::bail!("Failed to find keybinding to remove");
};
@@ -984,6 +986,7 @@ impl KeymapFile {
&target_action_value,
keyboard_mapper,
deprecated_aliases,
os,
) {
if target.context == source.context {
// if we are only changing the keybinding (common case)
@@ -996,7 +999,7 @@ impl KeymapFile {
binding_location.keystrokes_str,
],
Some(&source_action_value),
Some(&source.keystrokes_unparsed()),
Some(&source.keystrokes_unparsed(os)),
binding_location.index,
tab_size,
);
@@ -1015,7 +1018,7 @@ impl KeymapFile {
binding_location.keystrokes_str,
],
Some(&source_action_value),
Some(&source.keystrokes_unparsed()),
Some(&source.keystrokes_unparsed(os)),
binding_location.index,
tab_size,
);
@@ -1081,7 +1084,7 @@ impl KeymapFile {
let use_key_equivalents = from.and_then(|from| {
let action_value = from.action_value().context("Failed to serialize action value. `use_key_equivalents` on new keybinding may be incorrect.").log_err()?;
let binding_location =
find_binding(&keymap, &from, &action_value, keyboard_mapper, deprecated_aliases)?;
find_binding(&keymap, &from, &action_value, keyboard_mapper, deprecated_aliases, os)?;
Some(keymap.0[binding_location.index].use_key_equivalents)
}).unwrap_or(false);
if use_key_equivalents {
@@ -1091,7 +1094,7 @@ impl KeymapFile {
value.insert("bindings".to_string(), {
let mut bindings = serde_json::Map::new();
let action = keybinding.action_value()?;
bindings.insert(keybinding.keystrokes_unparsed(), action);
bindings.insert(keybinding.keystrokes_unparsed(os), action);
bindings.into()
});
@@ -1111,7 +1114,7 @@ impl KeymapFile {
value.insert("unbind".to_string(), {
let mut unbind = serde_json::Map::new();
unbind.insert(
suppression_unbind.keystrokes_unparsed(),
suppression_unbind.keystrokes_unparsed(os),
suppression_unbind.action_value()?,
);
unbind.into()
@@ -1132,6 +1135,7 @@ impl KeymapFile {
target_action_value: &Value,
keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
deprecated_aliases: &HashMap<&'static str, &'static str>,
os: gpui::OperatingSystem,
) -> Option<BindingLocation<'b>> {
let target_context_parsed =
KeyBindingContextPredicate::parse(target.context.unwrap_or("")).ok();
@@ -1150,6 +1154,7 @@ impl KeymapFile {
target_action_value,
keyboard_mapper,
deprecated_aliases,
os,
|action| &action.0,
) {
return Some(binding_location);
@@ -1163,6 +1168,7 @@ impl KeymapFile {
target_action_value,
keyboard_mapper,
deprecated_aliases,
os,
|action| &action.0,
) {
return Some(binding_location);
@@ -1179,6 +1185,7 @@ impl KeymapFile {
target_action_value: &Value,
keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
deprecated_aliases: &HashMap<&'static str, &'static str>,
os: gpui::OperatingSystem,
action_value: impl Fn(&T) -> &Value,
) -> Option<BindingLocation<'b>> {
let entries = entries?;
@@ -1186,7 +1193,7 @@ impl KeymapFile {
let Ok(keystrokes) = keystrokes_str
.split_whitespace()
.map(|source| {
let keystroke = Keystroke::parse(source)?;
let keystroke = Keystroke::parse_with_os(source, os)?;
Ok(KeybindingKeystroke::new_with_mapper(
keystroke,
false,
@@ -1309,6 +1316,7 @@ pub enum KeybindUpdateOperation<'a> {
impl KeybindUpdateOperation<'_> {
pub fn generate_telemetry(
&self,
os: gpui::OperatingSystem,
) -> (
// The keybind that is created
String,
@@ -1331,10 +1339,10 @@ impl KeybindUpdateOperation<'_> {
};
let new_binding = new_binding
.map(KeybindUpdateTarget::telemetry_string)
.map(|binding| binding.telemetry_string(os))
.unwrap_or("null".to_owned());
let removed_binding = removed_binding
.map(KeybindUpdateTarget::telemetry_string)
.map(|binding| binding.telemetry_string(os))
.unwrap_or("null".to_owned());
let source = source
@@ -1378,26 +1386,26 @@ impl<'a> KeybindUpdateTarget<'a> {
Ok(value)
}
fn keystrokes_unparsed(&self) -> String {
fn keystrokes_unparsed(&self, os: gpui::OperatingSystem) -> String {
let mut keystrokes = String::with_capacity(self.keystrokes.len() * 8);
for keystroke in self.keystrokes {
// The reason use `keystroke.unparse()` instead of `keystroke.inner.unparse()`
// The reason use `keystroke.unparse(os)` instead of `keystroke.inner.unparse(os)`
// here is that, we want the user to use `ctrl-shift-4` instead of `ctrl-$`
// by default on Windows.
keystrokes.push_str(&keystroke.unparse());
keystrokes.push_str(&keystroke.unparse(os));
keystrokes.push(' ');
}
keystrokes.pop();
keystrokes
}
fn telemetry_string(&self) -> String {
fn telemetry_string(&self, os: gpui::OperatingSystem) -> String {
format!(
"action_name: {}, context: {}, action_arguments: {}, keystrokes: {}",
self.action_name,
self.context.unwrap_or("global"),
self.action_arguments.unwrap_or("none"),
self.keystrokes_unparsed()
self.keystrokes_unparsed(os)
)
}
}
@@ -1811,13 +1819,14 @@ mod tests {
4,
&gpui::DummyKeyboardMapper,
&deprecated_aliases,
gpui::OperatingSystem::Mac,
)
.expect("Update succeeded");
pretty_assertions::assert_eq!(expected.to_string(), result);
}
#[track_caller]
fn parse_keystrokes(keystrokes: &str) -> Vec<KeybindingKeystroke> {
fn parse_keystrokes(keystrokes: &'static str) -> Vec<KeybindingKeystroke> {
keystrokes
.split(' ')
.map(|s| {
+1 -1
View File
@@ -3075,7 +3075,7 @@ impl SettingsWindow {
"Focus Navbar"
};
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("NavigationMenu");
key_context.add("menu");
if self.search_bar.focus_handle(cx).is_focused(window) {
+3 -3
View File
@@ -2516,7 +2516,7 @@ impl Sidebar {
})
.on_click(
cx.listener(move |this, event: &gpui::ClickEvent, window, cx| {
if event.modifiers().secondary() {
if event.modifiers().secondary(cx) {
this.activate_or_open_workspace_for_group(&key_for_focus, window, cx);
} else if !this.has_filter_query(cx) {
this.toggle_collapse(&key_for_toggle, window, cx);
@@ -2975,7 +2975,7 @@ impl Sidebar {
let action = h_flex()
.opacity(0.6)
.children(render_modifiers(
&Modifiers::secondary_key(),
&Modifiers::secondary_key(cx),
PlatformStyle::platform(),
None,
Some(TextSize::Default.rems(cx).into()),
@@ -3321,7 +3321,7 @@ impl Sidebar {
}
fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("ThreadsSidebar");
dispatch_context.add("menu");
+3 -3
View File
@@ -675,11 +675,11 @@ impl PickerDelegate for TasksModalDelegate {
if (current_modifiers.alt || self.matches.is_empty()) && !self.prompt.is_empty()
{
let action = picker::ConfirmInput {
secondary: current_modifiers.secondary(),
secondary: current_modifiers.secondary(cx),
}
.boxed_clone();
this.child({
let spawn_oneshot_label = if current_modifiers.secondary() {
let spawn_oneshot_label = if current_modifiers.secondary(cx) {
"Spawn Oneshot Without History"
} else {
"Spawn Oneshot"
@@ -691,7 +691,7 @@ impl PickerDelegate for TasksModalDelegate {
window.dispatch_action(action.boxed_clone(), cx)
})
})
} else if current_modifiers.secondary() {
} else if current_modifiers.secondary(cx) {
this.child({
let label = if is_recent_selected {
"Rerun Without History"
+22 -5
View File
@@ -335,12 +335,20 @@ mod test {
for (lower, upper) in letters_lower.zip(letters_upper) {
assert_eq!(
to_esc_str(
&Keystroke::parse(&format!("ctrl-shift-{}", lower)).unwrap(),
&Keystroke::parse_with_os(
&format!("ctrl-shift-{}", lower),
gpui::OperatingSystem::Mac
)
.unwrap(),
mode,
false
),
to_esc_str(
&Keystroke::parse(&format!("ctrl-{}", upper)).unwrap(),
&Keystroke::parse_with_os(
&format!("ctrl-{}", upper),
gpui::OperatingSystem::Mac
)
.unwrap(),
mode,
false
),
@@ -357,7 +365,11 @@ mod test {
for character in ascii_printable {
assert_eq!(
to_esc_str(
&Keystroke::parse(&format!("alt-{}", character)).unwrap(),
&Keystroke::parse_with_os(
&format!("alt-{}", character),
gpui::OperatingSystem::Mac
)
.unwrap(),
Modes::NONE,
true
)
@@ -375,7 +387,8 @@ mod test {
for key in gpui_keys {
assert_ne!(
to_esc_str(
&Keystroke::parse(&format!("alt-{}", key)).unwrap(),
&Keystroke::parse_with_os(&format!("alt-{}", key), gpui::OperatingSystem::Mac)
.unwrap(),
Modes::NONE,
true
)
@@ -392,7 +405,11 @@ mod test {
for (character, esc_code) in letters_lower.zip(esc_codes) {
assert_eq!(
to_esc_str(
&Keystroke::parse(&format!("ctrl-alt-{}", character)).unwrap(),
&Keystroke::parse_with_os(
&format!("ctrl-alt-{}", character),
gpui::OperatingSystem::Mac
)
.unwrap(),
Modes::NONE,
true
)
+13 -12
View File
@@ -2609,7 +2609,7 @@ impl Terminal {
cx: &mut Context<Self>,
) {
if self.selection_phase == SelectionPhase::Selecting
|| !modifiers.secondary()
|| !modifiers.secondary(cx)
|| !self.last_content.terminal_bounds.bounds.contains(&position)
{
self.clear_hyperlink(cx);
@@ -2743,7 +2743,7 @@ impl Terminal {
);
if e.button == MouseButton::Left
&& e.modifiers.secondary()
&& e.modifiers.secondary(cx)
&& (TerminalSettings::get_global(cx).open_links_in_mouse_mode
|| !self.mouse_mode(e.modifiers.shift, mode))
{
@@ -2877,7 +2877,7 @@ impl Terminal {
.and_then(|cell| cell.hyperlink())
{
cx.open_url(link.uri());
} else if e.modifiers.secondary() {
} else if e.modifiers.secondary(cx) {
self.events
.push_back(InternalEvent::FindHyperlink(position, true));
}
@@ -5254,7 +5254,7 @@ mod tests {
let mouse_down = MouseDownEvent {
button: MouseButton::Left,
position,
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
click_count: 1,
first_mouse: true,
};
@@ -5270,7 +5270,7 @@ mod tests {
let drag_event = MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
};
terminal.mouse_drag(
&drag_event,
@@ -5288,7 +5288,7 @@ mod tests {
let mouse_up = MouseUpEvent {
button: MouseButton::Left,
position,
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
click_count: 1,
};
terminal.mouse_up(&mouse_up, MouseInputMode::ReportToTerminal, cx);
@@ -5348,14 +5348,14 @@ mod tests {
let mouse_down = MouseDownEvent {
button: MouseButton::Left,
position,
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
click_count: 1,
first_mouse: true,
};
let mouse_up = MouseUpEvent {
button: MouseButton::Left,
position,
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
click_count: 1,
};
@@ -5391,7 +5391,7 @@ mod tests {
&MouseMoveEvent {
position: up_position,
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::secondary_key(),
modifiers: Modifiers::secondary_key(cx),
},
MouseInputMode::ReportToTerminal,
cx,
@@ -5671,7 +5671,7 @@ mod tests {
}
fn ctrl_mouse_move_to(&mut self, position: GpuiPoint<Pixels>) {
let modifiers = Modifiers::secondary_key();
let modifiers = Modifiers::secondary_key(self.cx);
let move_event = MouseMoveEvent {
position,
modifiers,
@@ -5718,7 +5718,7 @@ mod tests {
}
fn set_window_secondary_key(&mut self) {
self.window.set_modifiers(Modifiers::secondary_key());
self.window.set_modifiers(Modifiers::secondary_key(self.cx));
}
fn clear_window_secondary_key(&mut self) {
@@ -6025,7 +6025,8 @@ mod tests {
// Existing hovered_word cleared when secondary not held
cx.assert_hovered_word(None);
cx.try_modifiers_change(Modifiers::secondary_key());
let modifiers = Modifiers::secondary_key(cx.cx);
cx.try_modifiers_change(modifiers);
Some(Expected(Wakeups(0), Notifies(2)))
});
update_test_entities(&test_entities, cx, |cx: &mut HyperlinkVisualTestContext| {
+2 -2
View File
@@ -1334,7 +1334,7 @@ impl Element for TerminalElement {
terminal.set_size(dimensions);
terminal.sync(window, cx);
if window.modifiers().secondary()
if window.modifiers().secondary(cx)
&& bounds.contains(&window.mouse_position())
&& let Some(registered_hover) = self.terminal_view.read(cx).hover.as_ref()
{
@@ -1610,7 +1610,7 @@ impl Element for TerminalElement {
mouse_input_mode,
window,
);
if window.modifiers().secondary()
if window.modifiers().secondary(cx)
&& bounds.contains(&window.mouse_position())
&& self.terminal_view.read(cx).hover.is_some()
{
+3 -2
View File
@@ -1072,7 +1072,8 @@ impl TerminalView {
}
fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
if let Some(keystroke) = Keystroke::parse_with_os(&text.0, cx.platform_info().os).log_err()
{
self.clear_bell(cx);
self.blink_manager.update(cx, BlinkManager::pause_blinking);
self.process_keystroke(&keystroke, cx);
@@ -1080,7 +1081,7 @@ impl TerminalView {
}
fn dispatch_context(&self, cx: &App) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("Terminal");
if self.terminal.read(cx).vi_mode_enabled() {
@@ -731,7 +731,7 @@ impl ToolchainSelector {
impl Render for ToolchainSelector {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("ToolchainSelector");
v_flex()
+1 -1
View File
@@ -777,7 +777,7 @@ impl Component for KeyBinding {
}
fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
fn keybinding(input: &str) -> KeyBinding {
fn keybinding(input: &'static str) -> KeyBinding {
let keystrokes: Rc<[KeybindingKeystroke]> = input
.split_whitespace()
.filter_map(|chunk| Keystroke::parse(chunk).ok())
+1 -1
View File
@@ -769,7 +769,7 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
let keystrokes = action
.command
.chars()
.filter_map(|c| Keystroke::parse(&c.to_string()).ok())
.filter_map(|c| Keystroke::parse_with_os(&c.to_string(), cx.platform_info().os).ok())
.collect();
vim.switch_mode(Mode::Normal, true, window, cx);
if let Some(override_rows) = &action.override_rows {
+3 -1
View File
@@ -67,7 +67,9 @@ impl Vim {
Some(Operator::Literal {
prefix: Some(prefix),
}) => {
if let Some(keystroke) = Keystroke::parse(&action.0).ok() {
if let Some(keystroke) =
Keystroke::parse_with_os(&action.0, cx.platform_info().os).ok()
{
window.defer(cx, |window, cx| {
window.dispatch_keystroke(keystroke, cx);
});
+2 -1
View File
@@ -1985,7 +1985,8 @@ mod test {
}
fn dispatch_native_printable_key(cx: &mut VimTestContext, key: char) -> DispatchEventResult {
let keystroke = Keystroke::parse(&key.to_string())
let os = cx.read(|cx| cx.platform_info().os);
let keystroke = Keystroke::parse_with_os(&key.to_string(), os)
.expect("helix jump labels are valid keystrokes")
.with_simulated_ime();
let result = cx.update(|window, cx| {
@@ -261,9 +261,10 @@ impl NeovimBackedTestContext {
}
pub async fn simulate_shared_keystrokes(&mut self, keystroke_texts: &str) {
let os = self.cx.read(|cx| cx.platform_info().os);
for keystroke_text in keystroke_texts.split(' ') {
self.recent_keystrokes.push(keystroke_text.to_string());
self.neovim.send_keystroke(keystroke_text).await;
self.neovim.send_keystroke(keystroke_text, os).await;
}
self.simulate_keystrokes(keystroke_texts);
}
+3 -3
View File
@@ -116,8 +116,8 @@ impl NeovimConnection {
// Sends a keystroke to the neovim process.
#[cfg(feature = "neovim")]
pub async fn send_keystroke(&mut self, keystroke_text: &str) {
let mut keystroke = Keystroke::parse(keystroke_text).unwrap();
pub async fn send_keystroke(&mut self, keystroke_text: &str, os: gpui::OperatingSystem) {
let mut keystroke = Keystroke::parse_with_os(keystroke_text, os).unwrap();
if keystroke.key == "<" {
keystroke.key = "lt".to_string()
@@ -154,7 +154,7 @@ impl NeovimConnection {
}
#[cfg(not(feature = "neovim"))]
pub async fn send_keystroke(&mut self, keystroke_text: &str) {
pub async fn send_keystroke(&mut self, keystroke_text: &str, _os: gpui::OperatingSystem) {
if matches!(self.data.front(), Some(NeovimData::Get { .. })) {
self.data.pop_front();
}
+4 -3
View File
@@ -330,7 +330,8 @@ mod tests {
.split_whitespace()
.map(|keystroke| {
KeybindingKeystroke::from_keystroke(
Keystroke::parse(keystroke).expect("valid test keystroke"),
Keystroke::parse_with_os(keystroke, gpui::OperatingSystem::Mac)
.expect("valid test keystroke"),
)
})
.collect()
@@ -355,7 +356,7 @@ mod tests {
binding
.keystrokes
.iter()
.map(|keystroke| keystroke.inner().unparse())
.map(|keystroke| keystroke.inner().unparse(gpui::OperatingSystem::Mac))
.collect()
}
@@ -483,7 +484,7 @@ mod tests {
),
true,
None,
cx.keyboard_mapper().as_ref(),
cx,
)
.expect("user binding with key equivalents")
.with_meta(KeybindSource::User.meta()),
@@ -460,12 +460,12 @@ mod tests {
]
}
fn binding(keystrokes: &str, action: impl gpui::Action) -> KeyBinding {
fn binding(keystrokes: &'static str, action: impl gpui::Action) -> KeyBinding {
KeyBinding::new(keystrokes, action, Some("PendingKeystrokesIndicatorTest"))
}
/// Binds each keystroke sequence to the action the test view counts.
fn counted_bindings<const N: usize>(keystrokes: [&str; N]) -> [KeyBinding; N] {
fn counted_bindings<const N: usize>(keystrokes: [&'static str; N]) -> [KeyBinding; N] {
keystrokes.map(|keystrokes| binding(keystrokes, zed_actions::dev::OpenKeyContextView))
}
@@ -563,7 +563,7 @@ mod tests {
keystrokes: render_state
.keystrokes
.iter()
.map(|keystroke| keystroke.inner().unparse())
.map(|keystroke| keystroke.inner().unparse(gpui::OperatingSystem::Mac))
.collect(),
generation: render_state.pending_input_generation,
bindings: render_state
@@ -574,7 +574,9 @@ mod tests {
binding
.keystrokes
.iter()
.map(|keystroke| keystroke.inner().unparse())
.map(|keystroke| {
keystroke.inner().unparse(gpui::OperatingSystem::Mac)
})
.collect(),
binding.action_name.to_string(),
)
@@ -778,7 +780,7 @@ mod tests {
assert_eq!(
pending_keystrokes
.iter()
.map(Keystroke::unparse)
.map(|keystroke| keystroke.unparse(gpui::OperatingSystem::Mac))
.collect::<Vec<_>>(),
["j"]
);
@@ -931,7 +933,7 @@ mod tests {
assert_eq!(
window_pending_keystrokes(cx)
.iter()
.map(Keystroke::unparse)
.map(|keystroke| keystroke.unparse(gpui::OperatingSystem::Mac))
.collect::<Vec<_>>(),
["ctrl-b"]
);
+3 -3
View File
@@ -1217,8 +1217,8 @@ impl Dock {
}
}
fn dispatch_context() -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults();
fn dispatch_context(cx: &App) -> KeyContext {
let mut dispatch_context = KeyContext::new_with_defaults(cx.platform_info().os);
dispatch_context.add("Dock");
dispatch_context
@@ -1269,7 +1269,7 @@ impl Dock {
impl Render for Dock {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let dispatch_context = Self::dispatch_context();
let dispatch_context = Self::dispatch_context(cx);
if let Some(entry) = self.visible_entry() {
let position = self.position;
let create_resize_handle = || {
+1 -1
View File
@@ -4418,7 +4418,7 @@ impl Focusable for Pane {
impl Render for Pane {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut key_context = KeyContext::new_with_defaults();
let mut key_context = KeyContext::new_with_defaults(cx.platform_info().os);
key_context.add("Pane");
if self.active_item().is_none() {
key_context.add("EmptyPane");
+2 -2
View File
@@ -3786,7 +3786,7 @@ impl Workspace {
let keystrokes: Vec<Keystroke> = action
.0
.split(' ')
.flat_map(|k| Keystroke::parse(k).log_err())
.flat_map(|k| Keystroke::parse_with_os(k, cx.platform_info().os).log_err())
.map(|k| {
cx.keyboard_mapper()
.map_key_equivalent(k, false)
@@ -8113,7 +8113,7 @@ impl Workspace {
}
pub fn key_context(&self, cx: &App) -> KeyContext {
let mut context = KeyContext::new_with_defaults();
let mut context = KeyContext::new_with_defaults(cx.platform_info().os);
context.add("Workspace");
context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
if let Some(status) = self
+1 -1
View File
@@ -5846,7 +5846,7 @@ mod tests {
gpui::Keymap::new(bindings)
.bindings_for_input(
&[gpui::Keystroke::parse(keystroke).unwrap()],
&[gpui::Keystroke::parse_with_os(keystroke, cx.platform_info().os).unwrap()],
&[gpui::KeyContext::parse(context).unwrap()],
)
.0