Skip to content

Commit 996e28d

Browse files
authored
fix(macos): crash sending key event when app has no windows (#1090)
I noticed this when clicking the `Close Window` menu item which sends a `Cmd+W` event to the application. It looks like the window was closed and tao tried to send the event to `keyWindow` which was null. This check also exists on winit: https://github.com/rust-windowing/winit/blob/be1baf164cc80ebc8586f2c528fe854b1dafcb34/src/platform_impl/apple/appkit/app.rs#L36
1 parent c97080c commit 996e28d

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tao": patch
3+
---
4+
5+
Fix crash when sending key event when macOS app has no window opened.

src/platform_impl/macos/app.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44

55
use std::{collections::VecDeque, ffi::CStr};
66

7-
use objc2::runtime::{AnyClass as Class, AnyObject as Object, ClassBuilder as ClassDecl, Sel};
8-
use objc2_app_kit::{self as appkit, NSEvent, NSEventType};
7+
use objc2::runtime::{AnyClass as Class, ClassBuilder as ClassDecl, Sel};
8+
use objc2_app_kit::{self as appkit, NSApplication, NSEvent, NSEventType};
99

10-
use super::{app_state::AppState, event::EventWrapper, ffi::id, util, DEVICE_ID};
10+
use super::{app_state::AppState, event::EventWrapper, util, DEVICE_ID};
1111
use crate::event::{DeviceEvent, ElementState, Event};
1212

1313
pub struct AppClass(pub *const Class);
@@ -29,7 +29,7 @@ lazy_static! {
2929
// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
3030
// Overriding `sendEvent:` like this fixes that. (https://stackoverflow.com/a/15294196)
3131
// Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553)
32-
extern "C" fn send_event(this: &Object, _sel: Sel, event: &NSEvent) {
32+
extern "C" fn send_event(this: &NSApplication, _sel: Sel, event: &NSEvent) {
3333
unsafe {
3434
// For posterity, there are some undocumented event types
3535
// (https://github.com/servo/cocoa-rs/issues/155)
@@ -39,8 +39,11 @@ extern "C" fn send_event(this: &Object, _sel: Sel, event: &NSEvent) {
3939
if event_type == appkit::NSKeyUp
4040
&& util::has_flag(modifier_flags, appkit::NSEventModifierFlags::Command)
4141
{
42-
let key_window: id = msg_send![this, keyWindow];
43-
let _: () = msg_send![key_window, sendEvent: event];
42+
if let Some(key_window) = this.keyWindow() {
43+
key_window.sendEvent(event);
44+
} else {
45+
log::debug!("skip sending CMD keyEvent - app has no keyWindow");
46+
}
4447
} else {
4548
maybe_dispatch_device_event(event);
4649
let superclass = util::superclass(this);

0 commit comments

Comments
 (0)