Файли
openidea/src-tauri/src/macos.rs
T
Onur Ugur 0f0cdd4672 fix(macos): route Cmd+` natively and drop spurious Cmd text insertion (#7436)
On macOS, Cmd+/ and Cmd+` left a character at the caret (`/` and a backtick under ABC, `、` and
`·` under Pinyin), and Cmd+` did not switch project windows: WKWebView's performKeyEquivalent
routed the key through NSTextInputContext before NSMenu. WryWebView's performKeyEquivalent now
dispatches window.next / window.previous for Cmd+` / Cmd+Shift+`, and insertText is dropped for a
Command key-down without marked text. A frontend guard drops text beforeinput events right after
a Command key-down as a fallback.

Closes #7334

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 23:02:11 +08:00

996 рядки
41 KiB
Rust
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
//! macOS project tabs: native window tab groups behind the page's own tab bar.
use crate::background_tab::{self, Return};
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
use objc2::{
MainThreadMarker, msg_send,
rc::Retained,
runtime::{AnyClass, AnyObject, Bool, Imp, ProtocolObject, Sel},
sel,
};
use objc2_app_kit::{
NSAnimationContext, NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSView, NSWindow,
NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask, NSWindowUserTabbingPreference,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue, NSRange, NSRect};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
ffi::{CStr, c_void},
sync::{OnceLock, mpsc::SyncSender},
time::Duration,
};
use tauri::{AppHandle, Manager, WebviewWindow};
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
enum Background<V> {
Pending(u64),
Detached(V),
}
struct BackgroundTabs<V> {
next: u64,
tabs: HashMap<String, Background<V>>,
}
impl<V> Default for BackgroundTabs<V> {
fn default() -> Self {
Self { next: 0, tabs: HashMap::new() }
}
}
impl<V> BackgroundTabs<V> {
/// None when the label already has an entry: a repeated select must not restart the clock.
fn schedule(&mut self, label: &str) -> Option<u64> {
if self.tabs.contains_key(label) {
return None;
}
self.next += 1;
self.tabs.insert(label.to_string(), Background::Pending(self.next));
Some(self.next)
}
fn due(&self, label: &str, generation: u64) -> bool {
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
}
fn detached(&mut self, label: &str, view: V) {
self.tabs.insert(label.to_string(), Background::Detached(view));
}
fn cancel(&mut self, label: &str) {
self.tabs.remove(label);
}
fn view(&self, label: &str) -> Option<&V> {
match self.tabs.get(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
/// Also cancels a pending detach.
fn attach(&mut self, label: &str) -> Option<V> {
match self.tabs.remove(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
}
struct DetachedView {
view: Retained<NSView>,
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
}
impl Drop for DetachedView {
fn drop(&mut self) {
for observer in &self.observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
}
}
thread_local! {
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
}
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
fn read(mtm: MainThreadMarker) -> TabbingPreference {
match NSWindow::userTabbingPreference(mtm) {
NSWindowUserTabbingPreference::Always => TabbingPreference::Always,
NSWindowUserTabbingPreference::InFullScreen => TabbingPreference::InFullScreen,
_ => TabbingPreference::Manually,
}
}
if let Some(mtm) = MainThreadMarker::new() {
return Ok(read(mtm));
}
let (tx, rx) = std::sync::mpsc::sync_channel(1);
app.run_on_main_thread(move || {
let _ = tx.send(read(MainThreadMarker::new().expect("AppKit main thread")));
})
.map_err(|e| IdeError::internal(e.to_string()))?;
rx.recv().map_err(|e| IdeError::internal(e.to_string()))
}
/// Capture before building the new window, which takes focus itself.
pub fn new_project_tab_target(app: &AppHandle, launch: &Launch) -> IdeResult<Option<WebviewWindow>> {
let windows = app.webview_windows();
let active = windows
.values()
.find(|w| w.is_focused().unwrap_or(false))
.cloned()
.or_else(|| app.state::<WindowsState>().last_focused().and_then(|label| windows.get(&label).cloned()));
let active = active.and_then(|w| {
let label = crate::windows::auxiliary_parent(w.label()).unwrap_or(w.label());
windows.get(label).cloned()
});
let active = active.filter(|w| {
let host = app.state::<crate::state::AppState>();
host.project(w.label()).is_ok_and(|p| !p.light) || host.remote_dev.get(w.label()).is_some()
});
let fullscreen = active.as_ref().is_some_and(|w| w.is_fullscreen().unwrap_or(false));
let light_edit = launch.project.is_none() && launch.remote.is_none();
Ok(should_group_new_project(tabbing_preference(app)?, fullscreen, active.is_some(), light_edit)
.then_some(active)
.flatten())
}
/// Runs `f` on the main thread before returning, so it takes effect before what the caller does next.
fn on_main<R: Send + 'static>(window: &WebviewWindow, f: impl FnOnce() -> R + Send + 'static) -> tauri::Result<R> {
if MainThreadMarker::new().is_some() {
return Ok(f());
}
let (tx, rx) = std::sync::mpsc::sync_channel(1);
window.run_on_main_thread(move || {
let _ = tx.send(f());
})?;
rx.recv().map_err(|_| tauri::Error::FailedToReceiveMessage)
}
/// Project tabs are native window tabs, so a group shares one frame and enters full screen as one
/// window, with the system's window buttons on whichever tab is shown. The tab bar is the page's
/// own; AppKit's is hidden, and windows never join a tab group on their own.
pub fn prepare_window_tabbing(mtm: MainThreadMarker) {
NSWindow::setAllowsAutomaticWindowTabbing(false, mtm);
}
fn native(window: &WebviewWindow) -> Option<&'static NSWindow> {
let pointer = window.ns_window().ok()?;
Some(unsafe { &*pointer.cast::<NSWindow>() })
}
/// Whether `window` is the tab its native tab group shows, in one native group with every member
/// of `members` that still has a native window (not mid-merge). Main thread only.
pub fn shown_tab(window: &WebviewWindow, members: &[WebviewWindow]) -> bool {
native(window).is_some_and(|native| {
native.tabGroup().and_then(|g| g.selectedWindow()).is_some_and(|w| std::ptr::eq(Retained::as_ptr(&w), native))
&& members.iter().filter_map(self::native).all(|m| same_group(native, m))
})
}
fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
match (a.tabGroup(), b.tabGroup()) {
(Some(a), Some(b)) => Retained::as_ptr(&a) == Retained::as_ptr(&b),
_ => false,
}
}
fn schedule_detach(window: &WebviewWindow) {
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
if cfg!(debug_assertions) {
return;
}
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
let target = window.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
let window = target.clone();
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
});
}
fn detach_if_background(window: &WebviewWindow, generation: u64) {
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
return;
}
// Selecting a peer for its close dialog can schedule another detach. Keep this
// page attached until its own close guard has answered.
if window.state::<WindowsState>().is_closing(window.label()) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
}
let Some(native) = native(window) else { return };
// A visible window is never a background tab.
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
}
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
schedule_detach(window);
return;
}
let view = (|| {
let group = native.tabGroup()?;
let selected = group.selectedWindow()?;
let background = group.windows().count() > 1
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
&& native.attachedSheet().is_none();
background.then(|| background_tab::web_view(native)).flatten()
})();
let Some(view) = view else {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
};
view.removeFromSuperview();
let target = window.clone();
let observers = background_tab::on_return(native, move |why| {
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
});
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
}
/// Puts a detached web view back and cancels a pending detach.
pub fn attach(window: &WebviewWindow) {
attach_for(window, "select", false);
}
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
return;
};
if let Some(native) = native(window) {
background_tab::put_back(native, &detached.view);
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
}
if from_observer {
// Dropping removes the observer whose block is running; wait until the post returns.
let detached = Cell::new(Some(detached));
let block = block2::RcBlock::new(move || drop(detached.take()));
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
}
}
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
/// `superview()` in wry and are not safe while a tab is detached.
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
let target = window.clone();
window.run_on_main_thread(move || {
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
// the check and the call; wry's with_webview panics on a windowless view.
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
match detached {
Some(view) => f(view as *mut c_void),
None => {
#[allow(clippy::disallowed_methods)]
let _ = target.with_webview(move |w| f(w.inner()));
}
}
})
}
pub fn forget_background(label: &str) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
}
/// Upper bound on waiting for an occluded or freshly re-attached WKWebView to commit a GPU frame
/// before swapping tabs, so a busy WebContent process never makes tab switching feel stuck.
const TAB_PREWARM_TIMEOUT: Duration = Duration::from_millis(80);
struct PendingTabSwitch<W = Retained<NSView>> {
generation: u64,
webview: W,
done: Option<SyncSender<()>>,
}
impl<W> PendingTabSwitch<W> {
fn take_matching(slot: &mut Option<Self>, generation: u64) -> Option<Self> {
if slot.as_ref().is_some_and(|p| p.generation == generation) { slot.take() } else { None }
}
fn finish(mut self, restore: impl FnOnce(&W)) {
restore(&self.webview);
if let Some(done) = self.done.take() {
let _ = done.send(());
}
}
}
enum PrewarmOutcome {
Switched,
Waiting { generation: u64, rx: std::sync::mpsc::Receiver<()> },
}
thread_local! {
static NEXT_SWITCH_GENERATION: Cell<u64> = const { Cell::new(0) };
static PENDING_TAB_SWITCH: RefCell<Option<PendingTabSwitch>> = const { RefCell::new(None) };
}
fn next_switch_generation() -> u64 {
NEXT_SWITCH_GENERATION.with(|slot| {
let next = slot.get().wrapping_add(1);
slot.set(next);
next
})
}
fn without_animation<R>(f: impl FnOnce() -> R) -> R {
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
NSAnimationContext::endGrouping();
}
}
NSAnimationContext::beginGrouping();
let _guard = Guard;
let ctx = NSAnimationContext::currentContext();
ctx.setDuration(0.0);
ctx.setAllowsImplicitAnimation(false);
f()
}
fn frames_differ(a: NSRect, b: NSRect) -> bool {
a.origin.x != b.origin.x
|| a.origin.y != b.origin.y
|| a.size.width != b.size.width
|| a.size.height != b.size.height
}
fn webview_supports_prewarm(webview: &NSView) -> bool {
unsafe {
let has_setter: bool = msg_send![webview, respondsToSelector: sel!(_setWindowOcclusionDetectionEnabled:)];
let has_getter: bool = msg_send![webview, respondsToSelector: sel!(_windowOcclusionDetectionEnabled)];
let has_update: bool = msg_send![webview, respondsToSelector: sel!(_doAfterNextPresentationUpdate:)];
if !(has_setter && has_getter && has_update) {
return false;
}
msg_send![webview, _windowOcclusionDetectionEnabled]
}
}
fn set_window_occlusion_detection_enabled(webview: &NSView, enabled: bool) {
unsafe {
let _: () = msg_send![webview, _setWindowOcclusionDetectionEnabled: enabled];
}
}
/// Restores occlusion detection on any superseded pre-warm and unblocks its caller.
fn cancel_pending_tab_switch() {
let pending = PENDING_TAB_SWITCH.with(|slot| slot.borrow_mut().take());
if let Some(pending) = pending {
pending.finish(|webview| set_window_occlusion_detection_enabled(webview, true));
}
}
fn switch_tab_group_now(members: &[WebviewWindow], anchor: &WebviewWindow, target: &WebviewWindow) {
let Some(shown) = native(target) else { return };
let Some(anchor_window) = native(anchor) else { return };
without_animation(|| {
// Joining into a new tab's desktop window would take the existing group out of full screen.
for member in members.iter().filter(|m| m.label() != anchor.label()) {
if let Some(window) = native(member)
&& !same_group(anchor_window, window)
{
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
}
}
attach(target);
if let Some(group) = shown.tabGroup()
&& group
.selectedWindow()
.is_none_or(|current| !std::ptr::eq(Retained::as_ptr(&current), std::ptr::from_ref(shown)))
{
group.setSelectedWindow(Some(shown));
}
// Hide AppKit's tab bar before ordering front so it cannot flash over our tab strip.
hide_tab_bar(shown);
if !shown.isKeyWindow() {
shown.makeKeyAndOrderFront(None);
}
for member in members {
if member.label() != target.label() {
schedule_detach(member);
}
if let Some(window) = native(member) {
hide_tab_bar(window);
}
}
});
}
fn complete_pending_tab_switch(
generation: u64,
members: &[WebviewWindow],
anchor: &WebviewWindow,
target: &WebviewWindow,
) {
let pending = PENDING_TAB_SWITCH.with(|slot| PendingTabSwitch::take_matching(&mut slot.borrow_mut(), generation));
let Some(pending) = pending else { return };
switch_tab_group_now(members, anchor, target);
// Restore occlusion detection only after `target` is visible on screen so WebKit does not
// bounce `ActivityState::IsVisible` through `false` -> `true`.
pending.finish(|webview| set_window_occlusion_detection_enabled(webview, true));
}
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
///
/// Inactive macOS tabs are occluded (and detached after `DETACH_BACKGROUND_TAB_AFTER`), so WebKit
/// suspends compositing and frees or marks their GPU backing stores volatile. When switching to an
/// occluded tab from off the main thread, re-attach and temporarily wake its WKWebView, waiting for
/// one presentation commit (bounded by `TAB_PREWARM_TIMEOUT`) before swapping windows so the
/// incoming tab paints complete on the first visible frame.
pub fn sync_tab_group(
members: Vec<WebviewWindow>,
anchor: &WebviewWindow,
selected: &WebviewWindow,
) -> tauri::Result<()> {
let anchor = anchor.clone();
let target = selected.clone();
if MainThreadMarker::new().is_some() {
cancel_pending_tab_switch();
switch_tab_group_now(&members, &anchor, &target);
return Ok(());
}
let members_for_setup = members.clone();
let anchor_for_setup = anchor.clone();
let target_for_setup = target.clone();
let outcome = on_main(selected, move || {
cancel_pending_tab_switch();
let Some(shown) = native(&target_for_setup) else { return PrewarmOutcome::Switched };
let Some(anchor_window) = native(&anchor_for_setup) else { return PrewarmOutcome::Switched };
let all_grouped = members_for_setup.iter().all(|m| native(m).is_some_and(|w| same_group(anchor_window, w)));
let occluded = !shown.occlusionState().contains(NSWindowOcclusionState::Visible);
if anchor_for_setup.label() != target_for_setup.label() && all_grouped && occluded {
// Match the currently visible tab's frame first (outside native fullscreen) so both
// re-attached views and WebKit's pre-warm render at the exact post-swap size.
let reference = shown.tabGroup().and_then(|group| group.selectedWindow());
let reference_window: &NSWindow = reference.as_deref().unwrap_or(anchor_window);
let in_fullscreen = reference_window.styleMask().contains(NSWindowStyleMask::FullScreen)
|| shown.styleMask().contains(NSWindowStyleMask::FullScreen);
let reference_frame = reference_window.frame();
if !in_fullscreen && frames_differ(shown.frame(), reference_frame) {
shown.setFrame_display(reference_frame, false);
}
attach(&target_for_setup);
if let Some(webview) = background_tab::web_view(shown)
&& webview_supports_prewarm(&webview)
{
let generation = next_switch_generation();
let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
set_window_occlusion_detection_enabled(&webview, false);
PENDING_TAB_SWITCH.with(|slot| {
*slot.borrow_mut() =
Some(PendingTabSwitch { generation, webview: webview.clone(), done: Some(done_tx) });
});
let cb_members = members_for_setup.clone();
let cb_anchor = anchor_for_setup.clone();
let cb_target = target_for_setup.clone();
let block = block2::RcBlock::new(move || {
complete_pending_tab_switch(generation, &cb_members, &cb_anchor, &cb_target);
});
unsafe {
let _: () = msg_send![&*webview, _doAfterNextPresentationUpdate: &*block];
}
return PrewarmOutcome::Waiting { generation, rx: done_rx };
}
}
switch_tab_group_now(&members_for_setup, &anchor_for_setup, &target_for_setup);
PrewarmOutcome::Switched
})?;
if let PrewarmOutcome::Waiting { generation, rx } = outcome
&& rx.recv_timeout(TAB_PREWARM_TIMEOUT).is_err()
{
on_main(selected, move || {
complete_pending_tab_switch(generation, &members, &anchor, &target);
})?;
}
Ok(())
}
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
let target = window.clone();
on_main(window, move || {
let active =
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
})
.unwrap_or(false)
}
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
on_main(window, move || {
cancel_pending_tab_switch();
let Some(native) = native(&target) else { return };
attach(&target);
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
native.moveTabToNewWindow(None);
}
hide_tab_bar(native);
})
}
/// Hides `windows` together in a single main-thread turn so a closing window or tab group
/// disappears at once instead of flipping through remaining tabs while webviews tear down.
/// Native fullscreen windows are left for AppKit's own Space close transition.
pub fn hide_windows(windows: Vec<WebviewWindow>) {
if windows.is_empty() {
return;
}
let first = windows[0].clone();
let _ = on_main(&first, move || {
cancel_pending_tab_switch();
for window in &windows {
if window.is_fullscreen().unwrap_or(false) {
continue;
}
if let Some(native) = native(window) {
native.orderOut(None);
}
}
});
}
fn has_tab_bar(view: &objc2_app_kit::NSView) -> bool {
let class = view.class().name().to_string_lossy();
class.contains("TabBar") || view.subviews().iter().any(|v| has_tab_bar(&v))
}
/// Hides AppKit's tab bar, which a window shows while its group has more than one tab. It moves to
/// whichever tab is shown and comes back when the group changes, so this runs after each change.
pub fn hide_tab_bar(window: &NSWindow) {
let needs_hide = window
.titlebarAccessoryViewControllers()
.iter()
.any(|accessory| !accessory.isHidden() && has_tab_bar(&accessory.view()));
if !needs_hide {
return;
}
without_animation(|| {
for accessory in window.titlebarAccessoryViewControllers().iter() {
if !accessory.isHidden() && has_tab_bar(&accessory.view()) {
accessory.setHidden(true);
}
}
});
}
type ShouldTerminate = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> usize;
/// `NSApplicationTerminateReply`.
const TERMINATE_CANCEL: usize = 0;
const TERMINATE_NOW: usize = 1;
/// The Dock's Quit, the system's app menu and a logout ask the application delegate whether it
/// may terminate; tao's delegate doesn't answer, so AppKit terminated at once, past the exit,
/// running-process and unsaved-changes prompts. Answer it: cancel, and quit like Cmd+Q does.
pub fn intercept_system_quit(app: &AppHandle) {
let _ = APP.set(app.clone());
let Some(mtm) = MainThreadMarker::new() else { return };
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
unsafe {
let delegate: *mut AnyObject = objc2::msg_send![&*application, delegate];
if delegate.is_null() {
return;
}
let class = objc2::ffi::object_getClass(delegate.cast()) as *mut AnyClass;
let imp: Imp = std::mem::transmute(should_terminate as ShouldTerminate);
let added = objc2::ffi::class_addMethod(class, objc2::sel!(applicationShouldTerminate:), imp, c"Q@:@".as_ptr());
if !added.as_bool() {
tracing::warn!("could not handle applicationShouldTerminate:");
}
}
}
unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) -> usize {
let Some(app) = APP.get() else { return TERMINATE_NOW };
// Our own quit exits through the event loop; a system quit during it goes ahead.
if app.try_state::<WindowsState>().is_none_or(|w| w.quitting()) {
return TERMINATE_NOW;
}
crate::dispatch_menu_action(app, "app.quit");
TERMINATE_CANCEL
}
static APP: OnceLock<AppHandle> = OnceLock::new();
/// Physical macOS key code for the ANSI grave/backtick key (`kVK_ANSI_Grave`).
const KVK_ANSI_GRAVE: u16 = 0x32;
type PerformKeyEquivalent = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> Bool;
type InsertTextReplacementRange = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject, NSRange);
static ORIG_PERFORM_KEY_EQUIVALENT: OnceLock<PerformKeyEquivalent> = OnceLock::new();
static ORIG_INSERT_TEXT: OnceLock<InsertTextReplacementRange> = OnceLock::new();
/// Resolves a native macOS `⌘\`` / `⌘⇧\`` window-cycling shortcut before `WKWebView` hands it to
/// `NSTextInputContext` (which otherwise inserts `` ` `` under ABC or `·` under Pinyin and
/// consumes the event before `NSMenu` can run `window.next` / `window.previous`).
fn native_window_cycle_action(
flags: NSEventModifierFlags,
key_code: u16,
chars_ignoring_modifiers: Option<&str>,
) -> Option<&'static str> {
let primary = NSEventModifierFlags::Command | NSEventModifierFlags::Option | NSEventModifierFlags::Control;
if flags.intersection(primary) != NSEventModifierFlags::Command {
return None;
}
let shift = flags.contains(NSEventModifierFlags::Shift);
let matches_grave = match chars_ignoring_modifiers {
Some("`") => true,
// AppKit's `charactersIgnoringModifiers` still applies Shift (`~` for Shift+`).
Some("~") if shift => true,
// Non-ASCII input sources (e.g. Pinyin `·` / `~`, Russian `ё`) map physical
// `kVK_ANSI_Grave` to non-ASCII characters; ISO layouts put ASCII `<`/`>` there.
Some(s) if key_code == KVK_ANSI_GRAVE && !s.is_empty() && !s.is_ascii() => true,
_ => false,
};
if !matches_grave {
return None;
}
Some(if shift { "window.previous" } else { "window.next" })
}
/// Drops `-[WKWebView insertText:replacementRange:]` when there is no active marked-text
/// composition and the current AppKit event is a Command-modified `KeyDown`.
///
/// On macOS, `⌘` + punctuation (such as `⌘/` under ABC or Pinyin) can still commit `/` or `、`
/// through `NSTextInputClient` even when the frontend keymap handles `keydown` with
/// `preventDefault()`. Clipboard/undo commands use menu actions (`paste:`, `undo:`), and Option /
/// IME typing never holds Command, so legitimate input is untouched.
fn should_drop_webview_insert_text(has_marked_text: bool, current_event_is_cmd_keydown: bool) -> bool {
!has_marked_text && current_event_is_cmd_keydown
}
fn current_event_is_cmd_keydown() -> bool {
let Some(mtm) = MainThreadMarker::new() else { return false };
NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|event| {
event.r#type() == NSEventType::KeyDown && event.modifierFlags().contains(NSEventModifierFlags::Command)
})
}
unsafe extern "C-unwind" fn webview_perform_key_equivalent(
this: *mut AnyObject,
cmd: Sel,
event_ptr: *mut AnyObject,
) -> Bool {
if !event_ptr.is_null() {
let event = unsafe { &*event_ptr.cast::<NSEvent>() };
if event.r#type() == NSEventType::KeyDown {
let chars = event.charactersIgnoringModifiers().map(|s| s.to_string());
if let Some(action) = native_window_cycle_action(event.modifierFlags(), event.keyCode(), chars.as_deref())
&& !native_modal_open()
&& let Some(app) = APP.get()
&& app
.try_state::<crate::menu::MenuState>()
.is_none_or(|m| crate::menu::item_enabled(action, &m.disabled.lock()))
{
crate::dispatch_menu_action(app, action);
return Bool::YES;
}
}
}
match ORIG_PERFORM_KEY_EQUIVALENT.get() {
Some(orig) => unsafe { orig(this, cmd, event_ptr) },
None => Bool::NO,
}
}
unsafe extern "C-unwind" fn webview_insert_text(
this: *mut AnyObject,
cmd: Sel,
string: *mut AnyObject,
range: NSRange,
) {
if !this.is_null() {
let has_marked: Bool = unsafe { msg_send![this, hasMarkedText] };
if should_drop_webview_insert_text(has_marked.as_bool(), current_event_is_cmd_keydown()) {
return;
}
}
if let Some(orig) = ORIG_INSERT_TEXT.get() {
unsafe { orig(this, cmd, string, range) };
}
}
fn is_strict_subclass_of(cls: &AnyClass, ancestor: &AnyClass) -> bool {
let mut current = cls.superclass();
while let Some(super_cls) = current {
if std::ptr::eq(super_cls, ancestor) {
return true;
}
current = super_cls.superclass();
}
false
}
unsafe fn patch_webview_method(
webview_cls: &AnyClass,
selector: Sel,
replacement: Imp,
fallback_encoding: &CStr,
store_orig: impl FnOnce(Imp),
) -> bool {
let Some(method) = webview_cls.instance_method(selector) else {
return false;
};
let existing = method.implementation();
if std::ptr::fn_addr_eq(existing, replacement) {
return true;
}
let encoding = unsafe { objc2::ffi::method_getTypeEncoding(method as *const _ as *mut _) };
let encoding = if encoding.is_null() { fallback_encoding.as_ptr() } else { encoding };
store_orig(existing);
let cls = (webview_cls as *const AnyClass).cast_mut();
let added = unsafe { objc2::ffi::class_addMethod(cls, selector, replacement, encoding) };
if !added.as_bool() {
unsafe { objc2::ffi::class_replaceMethod(cls, selector, replacement, encoding) };
}
true
}
fn patch_webview_class_key_handlers(webview_cls: &AnyClass) -> bool {
// Only patch subclasses of WKWebView (such as WryWebView), never WKWebView itself.
let Some(wk_cls) = AnyClass::get(c"WKWebView") else {
return false;
};
if !is_strict_subclass_of(webview_cls, wk_cls) {
return false;
}
let Some(super_cls) = webview_cls.superclass() else {
return false;
};
let pke_sel = sel!(performKeyEquivalent:);
let insert_sel = sel!(insertText:replacementRange:);
if !super_cls.responds_to(pke_sel) || !super_cls.responds_to(insert_sel) {
return false;
}
unsafe {
let pke_imp: Imp = std::mem::transmute::<PerformKeyEquivalent, Imp>(webview_perform_key_equivalent);
let insert_imp: Imp = std::mem::transmute::<InsertTextReplacementRange, Imp>(webview_insert_text);
let pke_ok = patch_webview_method(webview_cls, pke_sel, pke_imp, c"B@:@", |orig| {
let _ = ORIG_PERFORM_KEY_EQUIVALENT.set(std::mem::transmute::<Imp, PerformKeyEquivalent>(orig));
});
let insert_ok = patch_webview_method(webview_cls, insert_sel, insert_imp, c"v@:@{_NSRange=QQ}", |orig| {
let _ = ORIG_INSERT_TEXT.set(std::mem::transmute::<Imp, InsertTextReplacementRange>(orig));
});
pke_ok && insert_ok
}
}
/// Patches `WryWebView`'s `performKeyEquivalent:` and `insertText:replacementRange:` so `⌘\`` /
/// `⌘⇧\`` switch project windows without typing `` ` `` / `·`, and `⌘` + punctuation shortcuts
/// (such as `⌘/`) do not leave stray `/` or `、` characters at the caret.
pub fn install_webview_key_handlers(window: &WebviewWindow) {
let _ = APP.set(window.app_handle().clone());
let _ = with_web_view(window, |webview| unsafe {
let ptr = webview.cast::<AnyObject>();
if !ptr.is_null() {
patch_webview_class_key_handlers((*ptr).class());
}
});
}
/// Whether AppKit is handling a key press right now. A menu item performed at this point
/// was chosen by its key equivalent: a click, arrow keys plus Return and accessibility
/// presses all run with a non-key current event.
pub fn handling_key_press() -> bool {
let Some(mtm) = MainThreadMarker::new() else { return false };
objc2_app_kit::NSApplication::sharedApplication(mtm)
.currentEvent()
.is_some_and(|event| event.r#type() == objc2_app_kit::NSEventType::KeyDown)
}
/// Native dialogs block the workbench even when their menu event no longer carries a key press.
pub fn native_modal_open() -> bool {
let Some(mtm) = MainThreadMarker::new() else { return false };
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
}
#[cfg(test)]
mod tests {
use super::{
BackgroundTabs, KVK_ANSI_GRAVE, PendingTabSwitch, frames_differ, native_window_cycle_action,
patch_webview_class_key_handlers, should_drop_webview_insert_text,
};
use objc2::runtime::AnyClass;
use objc2_app_kit::NSEventModifierFlags;
use objc2_foundation::{NSPoint, NSRect, NSSize};
#[test]
fn native_window_cycle_matches_abc_and_pinyin_backtick_only() {
let cmd = NSEventModifierFlags::Command;
let cmd_shift = cmd | NSEventModifierFlags::Shift;
let cmd_caps = cmd | NSEventModifierFlags::CapsLock;
// ABC: ⌘` and ⌘⇧` (AppKit reports `~` with Shift on US keyboards).
assert_eq!(native_window_cycle_action(cmd, KVK_ANSI_GRAVE, Some("`")), Some("window.next"));
assert_eq!(native_window_cycle_action(cmd_caps, KVK_ANSI_GRAVE, Some("`")), Some("window.next"));
assert_eq!(native_window_cycle_action(cmd_shift, KVK_ANSI_GRAVE, Some("~")), Some("window.previous"));
assert_eq!(native_window_cycle_action(cmd_shift, KVK_ANSI_GRAVE, Some("`")), Some("window.previous"));
// Pinyin – Simplified: physical kVK_ANSI_Grave produces `·` / `~`.
assert_eq!(native_window_cycle_action(cmd, KVK_ANSI_GRAVE, Some("·")), Some("window.next"));
assert_eq!(native_window_cycle_action(cmd_shift, KVK_ANSI_GRAVE, Some("~")), Some("window.previous"));
// Layouts where `` ` `` sits on another physical key still match by character.
assert_eq!(native_window_cycle_action(cmd, 0x0A, Some("`")), Some("window.next"));
// ISO layouts map key code 0x32 to ASCII `<`/`>` — must not be hijacked.
assert_eq!(native_window_cycle_action(cmd, KVK_ANSI_GRAVE, Some("<")), None);
assert_eq!(native_window_cycle_action(cmd_shift, KVK_ANSI_GRAVE, Some(">")), None);
// Option / Control chords (such as IDEA's ⌘⌥` keymap binding) stay on the JS keymap.
assert_eq!(native_window_cycle_action(cmd | NSEventModifierFlags::Option, KVK_ANSI_GRAVE, Some("`")), None);
assert_eq!(native_window_cycle_action(cmd | NSEventModifierFlags::Control, KVK_ANSI_GRAVE, Some("`")), None);
// Plain typing and ⌘/ are not window-cycling shortcuts.
assert_eq!(native_window_cycle_action(NSEventModifierFlags::empty(), KVK_ANSI_GRAVE, Some("`")), None);
assert_eq!(native_window_cycle_action(NSEventModifierFlags::Shift, KVK_ANSI_GRAVE, Some("~")), None);
assert_eq!(native_window_cycle_action(cmd, 0x2C, Some("/")), None);
assert_eq!(native_window_cycle_action(cmd, 0x2C, Some("、")), None);
}
#[test]
fn insert_text_is_dropped_only_for_non_composing_command_keydown() {
assert!(should_drop_webview_insert_text(false, true));
// Active IME composition flush (marked text present) is preserved.
assert!(!should_drop_webview_insert_text(true, true));
// Normal typing, Option-key typing, and non-KeyDown events are never dropped.
assert!(!should_drop_webview_insert_text(false, false));
assert!(!should_drop_webview_insert_text(true, false));
}
#[test]
fn key_handler_patch_targets_only_wkwebview_subclasses_idempotently() {
use objc2::{runtime::ClassBuilder, sel};
let wk_cls = AnyClass::get(c"WKWebView").expect("WebKit is linked");
let wk_pke = wk_cls.instance_method(sel!(performKeyEquivalent:)).unwrap().implementation();
let wk_insert = wk_cls.instance_method(sel!(insertText:replacementRange:)).unwrap().implementation();
assert!(!patch_webview_class_key_handlers(wk_cls));
assert!(!patch_webview_class_key_handlers(AnyClass::get(c"NSObject").unwrap()));
let sub_cls =
ClassBuilder::new(c"OpenIdeaKeyHandlerTestWebView", wk_cls).expect("unique test subclass").register();
assert!(patch_webview_class_key_handlers(sub_cls));
assert!(patch_webview_class_key_handlers(sub_cls));
// Base WKWebView methods stay untouched; subclass methods are patched.
assert!(std::ptr::fn_addr_eq(
wk_cls.instance_method(sel!(performKeyEquivalent:)).unwrap().implementation(),
wk_pke
));
assert!(std::ptr::fn_addr_eq(
wk_cls.instance_method(sel!(insertText:replacementRange:)).unwrap().implementation(),
wk_insert
));
assert!(!std::ptr::fn_addr_eq(
sub_cls.instance_method(sel!(performKeyEquivalent:)).unwrap().implementation(),
wk_pke
));
assert!(!std::ptr::fn_addr_eq(
sub_cls.instance_method(sel!(insertText:replacementRange:)).unwrap().implementation(),
wk_insert
));
}
#[test]
fn frames_differ_detects_origin_and_size_changes() {
let base = NSRect::new(NSPoint::new(10.0, 20.0), NSSize::new(1200.0, 800.0));
assert!(!frames_differ(base, base));
assert!(frames_differ(base, NSRect::new(NSPoint::new(11.0, 20.0), NSSize::new(1200.0, 800.0))));
assert!(frames_differ(base, NSRect::new(NSPoint::new(10.0, 20.0), NSSize::new(1400.0, 800.0))));
assert!(frames_differ(base, NSRect::new(NSPoint::new(10.0, 20.0), NSSize::new(1200.0, 900.0))));
}
#[test]
fn pending_tab_switch_completes_once_and_ignores_stale_generations() {
let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
let mut slot = Some(PendingTabSwitch { generation: 1, webview: "tab-a", done: Some(tx1) });
// Wrong generation leaves the active switch intact.
assert!(PendingTabSwitch::take_matching(&mut slot, 2).is_none());
assert!(slot.is_some());
// Matching generation takes it once, restores occlusion detection, and signals the waiter.
let mut restored = Vec::new();
let taken = PendingTabSwitch::take_matching(&mut slot, 1).expect("matching generation");
taken.finish(|w| restored.push(*w));
assert_eq!(restored, vec!["tab-a"]);
assert!(rx1.try_recv().is_ok());
// A late timeout or duplicate callback for the same generation is a no-op.
assert!(PendingTabSwitch::take_matching(&mut slot, 1).is_none());
}
#[test]
fn superseding_pending_tab_switch_restores_previous_webview_and_unblocks_waiter() {
let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
let (tx2, rx2) = std::sync::mpsc::sync_channel(1);
let mut slot = Some(PendingTabSwitch { generation: 1, webview: "tab-b", done: Some(tx1) });
// Rapid second switch cancels tab-b before registering tab-c.
let mut restored = Vec::new();
if let Some(prev) = slot.take() {
prev.finish(|w| restored.push(*w));
}
slot = Some(PendingTabSwitch { generation: 2, webview: "tab-c", done: Some(tx2) });
assert_eq!(restored, vec!["tab-b"]);
assert!(rx1.try_recv().is_ok());
// Late presentation callback for tab-b must not touch tab-c.
assert!(PendingTabSwitch::take_matching(&mut slot, 1).is_none());
assert!(rx2.try_recv().is_err());
// tab-c completes normally.
PendingTabSwitch::take_matching(&mut slot, 2).unwrap().finish(|w| restored.push(*w));
assert_eq!(restored, vec!["tab-b", "tab-c"]);
assert!(rx2.try_recv().is_ok());
}
#[test]
fn repeated_schedule_keeps_the_first_generation() {
let mut tabs = BackgroundTabs::<u32>::default();
let first = tabs.schedule("a").unwrap();
assert_eq!(tabs.schedule("a"), None);
assert!(tabs.due("a", first));
}
#[test]
fn attach_cancels_a_pending_detach() {
let mut tabs = BackgroundTabs::<u32>::default();
let generation = tabs.schedule("a").unwrap();
assert_eq!(tabs.attach("a"), None);
assert!(!tabs.due("a", generation));
}
#[test]
fn stale_generation_is_not_due_after_reschedule() {
let mut tabs = BackgroundTabs::<u32>::default();
let stale = tabs.schedule("a").unwrap();
tabs.attach("a");
let fresh = tabs.schedule("a").unwrap();
assert_ne!(stale, fresh);
assert!(!tabs.due("a", stale));
assert!(tabs.due("a", fresh));
}
#[test]
fn view_is_only_there_while_detached() {
let mut tabs = BackgroundTabs::<&'static str>::default();
tabs.schedule("a").unwrap();
assert_eq!(tabs.view("a"), None);
tabs.detached("a", "view");
assert_eq!(tabs.view("a"), Some(&"view"));
tabs.attach("a");
assert_eq!(tabs.view("a"), None);
}
#[test]
fn attach_returns_the_detached_view_once() {
let mut tabs = BackgroundTabs::<&'static str>::default();
let generation = tabs.schedule("a").unwrap();
tabs.detached("a", "view");
assert!(!tabs.due("a", generation));
assert_eq!(tabs.attach("a"), Some("view"));
assert_eq!(tabs.attach("a"), None);
}
}