Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions crates/nsh-platform-linux/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -959,13 +959,18 @@ pub(crate) fn choose(surface: &Rc<Surface>, id: u32, role: Option<MenuRole>) {
_ => "selection.select-all",
};
// Once the menu closed and gave the focus back to the field.
// The bindings of the role's key where the focus is come first,
// as when the key is pressed (a focused table copies its
// cells); else the focused widget's own action.
let weak = Rc::downgrade(surface);
glib::idle_add_local_once(move || {
let focus = weak
.upgrade()
.and_then(|s| window(&s))
.and_then(|w| GtkWindowExt::focus(&w));
if let Some(focus) = focus {
let Some(surface) = weak.upgrade() else {
return;
};
if crate::keymap::menu_command(&surface, role) {
return;
}
if let Some(focus) = window(&surface).and_then(|w| GtkWindowExt::focus(&w)) {
let _ = focus.activate_action(name, None);
}
});
Expand Down
53 changes: 49 additions & 4 deletions crates/nsh-platform-linux/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,39 @@ pub(crate) fn clear(surface: &Surface) {
surface.keymap.keymap.borrow_mut().take();
}

/// An Edit menu command chosen in a menu (`role`, Copy): the bindings of
/// its standard key (Ctrl+C) where the focus is decide first, as when the
/// key is pressed, so a focused table copies its cells. Whether one took
/// the command (one passing its key through does not: the focused
/// widget's own action still runs).
pub(crate) fn menu_command(surface: &Surface, role: nsh_core::desktop::MenuRole) -> bool {
menu_keystroke(role).is_some_and(|stroke| press(surface, stroke))
}

/// The keystroke of a menu command's standard shortcut off a Mac (Copy's
/// Ctrl+C); none for a key other than a character's.
fn menu_keystroke(role: nsh_core::desktop::MenuRole) -> Option<Keystroke> {
let shortcut = role.shortcut(false)?;
let nsh_core::desktop::Key::Char(c) = shortcut.key else {
return None;
};
Some(Keystroke {
modifiers: Modifiers {
ctrl: shortcut.ctrl,
alt: shortcut.alt,
shift: shortcut.shift,
cmd: shortcut.meta,
alt_graph: false,
},
key: Key::Char(c),
})
}

/// A key pressed without a GDK event (GTK takes no made-up ones; `nsh test
/// --target linux`): the newest binding of `stroke` that fires where the
/// focus is reports it, as its shortcut's action would. Whether it took
/// the key: false if none fired or the one that did passes it through.
#[cfg(feature = "dev")]
/// --target linux`; a menu command, [`menu_command`]): the newest binding
/// of `stroke` that fires where the focus is reports it, as its shortcut's
/// action would. Whether it took the key: false if none fired or the one
/// that did passes it through.
pub(crate) fn press(surface: &Surface, stroke: Keystroke) -> bool {
let keymap = surface.keymap.keymap.borrow().clone();
let Some(keymap) = keymap else {
Expand Down Expand Up @@ -576,6 +604,23 @@ fn trigger(

#[cfg(test)]
mod tests {

/// An Edit menu command runs the bindings of the key an app writes for
/// it (`mod+c` for Copy, #4177).
#[test]
fn a_menu_command_is_the_key_its_bindings_name() {
use nsh_core::{desktop::MenuRole, keymap::Keystroke, platform::Os};
for (role, keys) in [
(MenuRole::Copy, "mod+c"),
(MenuRole::Cut, "mod+x"),
(MenuRole::Paste, "mod+v"),
(MenuRole::SelectAll, "mod+a"),
] {
let bound = Keystroke::parse(keys, Os::Linux).unwrap();
assert_eq!(super::menu_keystroke(role), Some(bound), "{role:?}");
}
assert_eq!(super::menu_keystroke(MenuRole::About), None);
}
use gtk4 as gtk;
use nsh_core::{
ROOT_ID,
Expand Down
123 changes: 103 additions & 20 deletions crates/nsh-platform-macos/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,35 +78,17 @@ pub(crate) fn pressed(surface: &Rc<Surface>, event: &NSEvent) -> bool {
};
// Before a binding acts: the focus it moves shows (`focus-visible:`).
surface.control(|c| c.set_input_modality(nsh_core::platform::InputModality::Keyboard));
let own = root.ns() != surface.root.ns();
let window_root = root.id();
if crate::window::blocked(surface, own.then_some(&root)) {
return false;
}
crate::input::enter(surface, own.then_some(root));
let Some(editing) = editing(surface, &window) else {
let control = || crate::input::control_activation_target(surface, event).is_some();
let Some((window_root, focus)) = focus_in(surface, &window, root, control) else {
return false;
};
if composing(&window) {
return false;
}
// Return and Space on a focused control fire only the focus' own
// bindings; else the control takes them (`input::key`).
let control = crate::input::control_activation_target(surface, event).is_some();
// A key another layout types no US key for (`keystroke` is none) can
// still type text.
let stroke = keystroke(event);
// The dev host's Cmd+R reloads, whatever the app binds.
if cfg!(feature = "dev") && stroke.is_some_and(|k| k.reloads(Os::MacOs)) {
return false;
}
// Only the bindings of the window the key is in (and JS's) take it.
// A focus a dialog covers has no keys of its own: the dialog's take
// them.
let mut focus = nsh_core::keymap::KeyFocus::default();
focus.editing = editing;
focus.control = control;
focus.covered = crate::input::focus_covered(surface);
let repeat = event.isARepeat();
let found = match stroke {
Some(keystroke) => table.find_with(window_root, keystroke, focus, repeat),
Expand Down Expand Up @@ -137,6 +119,90 @@ pub(crate) fn pressed(surface: &Rc<Surface>, event: &NSEvent) -> bool {
found.consumed()
}

/// The window root and the focus the bindings of a key in `window` are
/// matched for; none when the key is not the surface's (a modal blocks
/// it, the focus is in another surface's views, an input method is
/// composing). `control`: whether the focus is on a control taking Return
/// and Space, asked once the input is in `window`.
fn focus_in(
surface: &Rc<Surface>,
window: &NSWindow,
root: crate::view::NshView,
control: impl FnOnce() -> bool,
) -> Option<(nsh_core::NodeId, nsh_core::keymap::KeyFocus)> {
let own = root.ns() != surface.root.ns();
let window_root = root.id();
if crate::window::blocked(surface, own.then_some(&root)) {
return None;
}
crate::input::enter(surface, own.then_some(root));
let editing = editing(surface, window)?;
if composing(window) {
return None;
}
// Only the bindings of the window the key is in (and JS's) take it.
// A focus a dialog covers has no keys of its own: the dialog's take
// them. Return and Space on a focused control fire only the focus'
// own bindings; else the control takes them (`input::key`).
let mut focus = nsh_core::keymap::KeyFocus::default();
focus.editing = editing;
focus.control = control();
focus.covered = crate::input::focus_covered(surface);
Some((window_root, focus))
}

/// An Edit menu command chosen with the mouse (or by accessibility) in
/// `window`, whose standard shortcut is `stroke` (Copy's Cmd+C): the
/// bindings that key would fire where the focus is decide, as they do when
/// the key is pressed (the monitor runs them before the menu's key
/// equivalent), so a focused table copies its cells. Reports the binding
/// when `fire`; whether one takes the command (one passing its key
/// through does not: the default still runs).
pub(crate) fn command(
surface: &Rc<Surface>,
window: &NSWindow,
stroke: Keystroke,
fire: bool,
) -> bool {
let Some(table) = surface.keymap.table.borrow().clone() else {
return false;
};
let Some(root) = crate::window::root_in(surface, window) else {
return false;
};
let Some((window_root, focus)) = focus_in(surface, window, root, || false) else {
return false;
};
let found = table.find_with(window_root, stroke, focus, false);
if fire && let Some(id) = found.fired() {
surface.event(
ROOT_ID,
EventKind::KeyCommand,
EventPayload::Value(PayloadValue::Number(id as f64)),
);
}
found.consumed()
}

/// The keystroke of a menu command's standard shortcut on a Mac (Copy's
/// Cmd+C).
pub(crate) fn menu_keystroke(role: nsh_core::desktop::MenuRole) -> Option<Keystroke> {
let shortcut = role.shortcut(true)?;
let nsh_core::desktop::Key::Char(c) = shortcut.key else {
return None;
};
Some(Keystroke {
modifiers: Modifiers {
ctrl: shortcut.ctrl,
alt: shortcut.alt,
shift: shortcut.shift,
cmd: shortcut.meta,
alt_graph: false,
},
key: Key::Char(c),
})
}

/// Whether an input method is composing in the focused input client (it has
/// marked text: pinyin, kana). Every key is then the input method's:
/// Backspace deletes a letter of the composition, Return and Space
Expand Down Expand Up @@ -290,6 +356,23 @@ pub(crate) fn function_key_code(n: u8) -> Option<u16> {

#[cfg(test)]
mod tests {

/// An Edit menu command runs the bindings of the key an app writes for
/// it (`mod+c` for Copy, #4177).
#[test]
fn a_menu_command_is_the_key_its_bindings_name() {
use nsh_core::{desktop::MenuRole, keymap::Keystroke, platform::Os};
for (role, keys) in [
(MenuRole::Copy, "mod+c"),
(MenuRole::Cut, "mod+x"),
(MenuRole::Paste, "mod+v"),
(MenuRole::SelectAll, "mod+a"),
] {
let bound = Keystroke::parse(keys, Os::MacOs).unwrap();
assert_eq!(super::menu_keystroke(role), Some(bound), "{role:?}");
}
assert_eq!(super::menu_keystroke(MenuRole::About), None);
}
#[test]
fn function_keys() {
assert_eq!(super::function_key(122), Some(1));
Expand Down
84 changes: 75 additions & 9 deletions crates/nsh-platform-macos/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use std::{

use nsh_core::{
Bounds, EventMask, Matrix, NodeId, PointerEvents, Points, ROOT_ID, ViewKind, ViewProps,
ViewStyle, animation::AnimValues,
ViewStyle, animation::AnimValues, desktop::MenuRole,
};
use objc2::{
AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send,
Expand All @@ -51,9 +51,9 @@ use objc2::{
sel,
};
use objc2_app_kit::{
NSAccessibility, NSDragOperation, NSDraggingDestination, NSDraggingInfo, NSEvent, NSEventType,
NSResponder, NSTrackingArea, NSTrackingAreaOptions, NSView, NSViewLayerContentsRedrawPolicy,
NSWindowOrderingMode,
NSAccessibility, NSApplication, NSDragOperation, NSDraggingDestination, NSDraggingInfo,
NSEvent, NSEventType, NSResponder, NSTrackingArea, NSTrackingAreaOptions, NSView,
NSViewLayerContentsRedrawPolicy, NSWindowOrderingMode,
};
use objc2_core_foundation::{CGAffineTransform, CGFloat, CGPoint, CGRect, CGSize};
use objc2_core_graphics::CGContext;
Expand Down Expand Up @@ -1004,23 +1004,70 @@ define_class!(
self.pointer(event);
}

/// The Edit menu's Copy (Cmd+C): the selected text.
/// The Edit menu's Copy (Cmd+C): what the focused view binds to
/// the key (a table's cells), else the selected text.
#[unsafe(method(copy:))]
fn copy(&self, _sender: Option<&AnyObject>) {
if let Some(surface) = self.input_surface() {
if let Some(surface) = self.input_surface()
&& !self.menu_binding(&surface, MenuRole::Copy, true)
{
crate::text::copy(&surface);
}
}

/// The Edit menu's Select All (Cmd+A): a selectable text's or a
/// selectable view's.
/// The Edit menu's Select All (Cmd+A): what the focused view binds
/// to the key, else a selectable text's or a selectable view's.
#[unsafe(method(selectAll:))]
fn select_all(&self, _sender: Option<&AnyObject>) {
if let Some(surface) = self.input_surface() {
if let Some(surface) = self.input_surface()
&& !self.menu_binding(&surface, MenuRole::SelectAll, true)
{
crate::text::select_all(&surface);
}
}

/// The Edit menu's Cut (Cmd+X): what the focused view binds to the
/// key (an editor's selection); nothing else cuts here.
#[unsafe(method(cut:))]
fn cut(&self, _sender: Option<&AnyObject>) {
if let Some(surface) = self.input_surface() {
self.menu_binding(&surface, MenuRole::Cut, true);
}
}

/// The Edit menu's Paste (Cmd+V): what the focused view binds to the
/// key; nothing else pastes here.
#[unsafe(method(paste:))]
fn paste(&self, _sender: Option<&AnyObject>) {
if let Some(surface) = self.input_surface() {
self.menu_binding(&surface, MenuRole::Paste, true);
}
}

/// Copy is enabled when it copies something: a binding of its key
/// where the focus is, or selected text; Cut and Paste when their
/// key has a binding there.
#[unsafe(method(validateMenuItem:))]
fn validate_menu_item(&self, item: &objc2_app_kit::NSMenuItem) -> objc2::runtime::Bool {
let action = item.action();
let role = if action == Some(sel!(copy:)) {
MenuRole::Copy
} else if action == Some(sel!(cut:)) {
MenuRole::Cut
} else if action == Some(sel!(paste:)) {
MenuRole::Paste
} else {
return objc2::runtime::Bool::YES;
};
let Some(surface) = self.surface().or_else(|| self.ivars().window.borrow().upgrade())
else {
return objc2::runtime::Bool::NO;
};
let acts = (role == MenuRole::Copy && crate::text::can_copy(&surface))
|| self.menu_binding(&surface, role, false);
objc2::runtime::Bool::new(acts)
}

/// AppKit Services can take the selected text as plain text.
#[unsafe(method(validRequestorForSendType:returnType:))]
fn valid_requestor(
Expand Down Expand Up @@ -1620,6 +1667,25 @@ impl ViewObj {
Some(surface)
}

/// An Edit menu command chosen in the menu rather than by its key
/// (Copy's Cmd+C): whether a binding of its key takes it where the
/// focus is, reported when `fire`. A pressed key already ran the
/// bindings in the keyboard monitor before the menu's key equivalent
/// reached here, so a key-down in flight takes nothing.
fn menu_binding(&self, surface: &std::rc::Rc<Surface>, role: MenuRole, fire: bool) -> bool {
let pressed = NSApplication::sharedApplication(self.mtm())
.currentEvent()
.is_some_and(|e| e.r#type() == NSEventType::KeyDown);
if fire && pressed {
return false;
}
let (Some(window), Some(stroke)) = (self.window(), crate::keymap::menu_keystroke(role))
else {
return false;
};
crate::keymap::command(surface, &window, stroke, fire)
}

/// What the root's `hitTest:` returns inside it: a hosted AppKit view
/// nsh's picking lands on (past overlays that let the pointer
/// through), else the root itself. `point` is in the root's
Expand Down
5 changes: 5 additions & 0 deletions crates/nsh-platform-macos/tests/native/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ mod layout_animation_bench;
#[cfg(target_os = "macos")]
mod mask_corners;
#[cfg(target_os = "macos")]
mod menu_copy;
#[cfg(target_os = "macos")]
mod menu_labels;
#[cfg(target_os = "macos")]
mod menu_lifetime;
Expand Down Expand Up @@ -266,6 +268,8 @@ fn main() {
zoom::run();
} else if std::env::var_os("NSH_IME_CHECK_ONLY").is_some() {
ime::run();
} else if std::env::var_os("NSH_MENU_COPY_CHECK_ONLY").is_some() {
menu_copy::run();
} else if std::env::var_os("NSH_IME_KEYMAP_CHECK_ONLY").is_some() {
keymap_ime::run();
} else if std::env::var_os("NSH_KEYBOARD_CHECK_ONLY").is_some() {
Expand Down Expand Up @@ -351,6 +355,7 @@ fn main() {
mask_corners::run();
menu_labels::run();
menu_lifetime::run();
menu_copy::run();
file_panels::run();
web_file_input::run();
tray_owner::run();
Expand Down
Loading
Loading