Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui_macos: Migrate window and appearance bindings to objc2 (#65933)

Kirill Bulatov10cfb459449a
diff --git a/Cargo.lock b/Cargo.lock
index 0ddb0581b04..c043952a1c1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3206,7 +3206,7 @@ checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c"
dependencies = [
"bitflags 1.3.2",
"block",
- "cocoa-foundation 0.1.2",
+ "cocoa-foundation",
"core-foundation 0.9.4",
"core-graphics 0.23.2",
"foreign-types 0.5.0",
@@ -3214,22 +3214,6 @@ dependencies = [
"objc",
]
-[[package]]
-name = "cocoa"
-version = "0.26.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2"
-dependencies = [
- "bitflags 2.13.1",
- "block",
- "cocoa-foundation 0.2.0",
- "core-foundation 0.10.0",
- "core-graphics 0.24.0",
- "foreign-types 0.5.0",
- "libc",
- "objc",
-]
-
[[package]]
name = "cocoa-foundation"
version = "0.1.2"
@@ -3244,20 +3228,6 @@ dependencies = [
"objc",
]
-[[package]]
-name = "cocoa-foundation"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d"
-dependencies = [
- "bitflags 2.13.1",
- "block",
- "core-foundation 0.10.0",
- "core-graphics-types 0.2.0",
- "libc",
- "objc",
-]
-
[[package]]
name = "codespan-reporting"
version = "0.13.0"
@@ -7637,7 +7607,6 @@ dependencies = [
"accesskit_macos",
"anyhow",
"block2 0.6.2",
- "cocoa 0.26.0",
"collections",
"core-foundation 0.10.0",
"core-foundation-sys",
@@ -7652,7 +7621,6 @@ dependencies = [
"image",
"itertools 0.14.0",
"log",
- "objc",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
"objc2-core-graphics",
@@ -22815,7 +22783,7 @@ version = "0.0.8-zed"
source = "git+https://github.com/zed-industries/scap?rev=4afea48c3b002197176fb19cd0f9b180dd36eaac#4afea48c3b002197176fb19cd0f9b180dd36eaac"
dependencies = [
"anyhow",
- "cocoa 0.25.0",
+ "cocoa",
"core-graphics-helmer-fork",
"log",
"objc",
diff --git a/Cargo.toml b/Cargo.toml
index 4cd3f43ee03..7802328d71d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -595,7 +595,6 @@ ciborium = "0.2"
clap = { version = "4.4", features = ["derive", "wrap_help"] }
clap_complete = "4.4"
clap_complete_nushell = "4.4"
-cocoa = "=0.26.0"
console = "0.16"
console_error_panic_hook = "0.1.7"
const_format = "0.2"
@@ -702,7 +701,6 @@ nbformat = "1.2.0"
nix = "0.30"
notify-rust = "4"
nucleo = { package = "nucleo-matcher", version = "0.3" }
-objc = "0.2"
objc2 = "0.6"
objc2-ui-kit = { version = "0.3.2", default-features = false, features = [
"std",
@@ -744,9 +742,11 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = [
"NSApplication",
"NSButton",
"NSCell",
+ "NSColor",
"NSControl",
"NSCursor",
"NSDocumentController",
+ "NSDragging",
"NSDraggingItem",
"NSEvent",
"NSGraphics",
@@ -763,6 +763,7 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = [
"NSScroller",
"NSTrackingArea",
"NSView",
+ "NSVisualEffectView",
"NSWindow",
"NSWorkspace",
"block2",
diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml
index f136df4b87c..85f6f15ed16 100644
--- a/crates/gpui_macos/Cargo.toml
+++ b/crates/gpui_macos/Cargo.toml
@@ -18,7 +18,7 @@ bench-support = ["gpui/bench-support", "gpui_apple/bench-support"]
test-support = ["gpui/test-support", "gpui_apple/test-support"]
runtime_shaders = ["gpui_apple/runtime_shaders"]
font-kit = ["gpui_apple/font-kit"]
-screen-capture = ["gpui/screen-capture", "dep:objc2-core-graphics", "dep:objc2-core-media", "dep:objc2-screen-capture-kit"]
+screen-capture = ["gpui/screen-capture", "dep:objc2-core-media", "dep:objc2-screen-capture-kit"]
[dependencies]
gpui.workspace = true
@@ -28,7 +28,6 @@ accesskit.workspace = true
accesskit_macos.workspace = true
anyhow.workspace = true
block2.workspace = true
-cocoa.workspace = true
collections.workspace = true
core-foundation.workspace = true
core-foundation-sys.workspace = true
@@ -42,10 +41,9 @@ gpui_util.workspace = true
image.workspace = true
itertools.workspace = true
log.workspace = true
-objc.workspace = true
objc2.workspace = true
objc2-app-kit.workspace = true
-objc2-core-graphics = { workspace = true, optional = true }
+objc2-core-graphics = { workspace = true, features = ["CGColor", "objc2"] }
objc2-core-media = { workspace = true, optional = true }
objc2-core-video = { workspace = true, features = ["CVHostTime"] }
objc2-foundation.workspace = true
diff --git a/crates/gpui_macos/src/gpui_macos.rs b/crates/gpui_macos/src/gpui_macos.rs
index 3d1a3efb0d9..b4ee9e03b37 100644
--- a/crates/gpui_macos/src/gpui_macos.rs
+++ b/crates/gpui_macos/src/gpui_macos.rs
@@ -27,18 +27,13 @@ mod platform;
mod window;
mod window_appearance;
-use cocoa::{
- base::{id, nil},
- foundation::{NSAutoreleasePool, NSNotFound, NSString, NSUInteger},
-};
-
-use objc::runtime::{BOOL, NO, YES};
-use objc2::{rc::Retained, runtime::AnyObject};
-use objc2_foundation::NSString as Objc2NSString;
-use std::{
- ffi::{CStr, c_char},
- ops::Range,
+use objc2::{
+ Encode, Encoding, RefEncode,
+ rc::Retained,
+ runtime::{AnyObject, Bool},
};
+use objc2_foundation::{NSNotFound, NSString, NSUInteger};
+use std::{ffi::CStr, ops::Range};
pub(crate) use display::*;
pub(crate) use display_link::*;
@@ -50,12 +45,12 @@ pub(crate) use window::*;
pub use platform::MacPlatform;
trait BoolExt {
- fn to_objc(self) -> BOOL;
+ fn to_objc(self) -> Bool;
}
impl BoolExt for bool {
- fn to_objc(self) -> BOOL {
- if self { YES } else { NO }
+ fn to_objc(self) -> Bool {
+ Bool::new(self)
}
}
@@ -63,23 +58,10 @@ trait NSStringExt {
unsafe fn to_str(&self) -> &str;
}
-impl NSStringExt for id {
- unsafe fn to_str(&self) -> &str {
- unsafe {
- let cstr = self.UTF8String();
- if cstr.is_null() {
- ""
- } else {
- CStr::from_ptr(cstr as *mut c_char).to_str().unwrap()
- }
- }
- }
-}
-
impl NSStringExt for *mut AnyObject {
unsafe fn to_str(&self) -> &str {
unsafe {
- let Some(string) = self.cast::<Objc2NSString>().as_ref() else {
+ let Some(string) = self.cast::<NSString>().as_ref() else {
return "";
};
let cstr = string.UTF8String();
@@ -113,8 +95,8 @@ impl NSRange {
fn to_range(self) -> Option<Range<usize>> {
if self.is_valid() {
- let start = self.location as usize;
- let end = start + self.length as usize;
+ let start = self.location;
+ let end = start + self.length;
Some(start..end)
} else {
None
@@ -131,23 +113,14 @@ impl From<Range<usize>> for NSRange {
}
}
-unsafe impl objc::Encode for NSRange {
- fn encode() -> objc::Encoding {
- let encoding = format!(
- "{{NSRange={}{}}}",
- NSUInteger::encode().as_str(),
- NSUInteger::encode().as_str()
- );
- unsafe { objc::Encoding::from_str(&encoding) }
- }
+unsafe impl Encode for NSRange {
+ const ENCODING: Encoding = objc2_foundation::NSRange::ENCODING;
}
-/// Allow NSString::alloc use here because it sets autorelease
-#[allow(clippy::disallowed_methods)]
-fn legacy_ns_string(string: &str) -> id {
- unsafe { NSString::alloc(nil).init_str(string).autorelease() }
+unsafe impl RefEncode for NSRange {
+ const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
fn ns_string(string: &str) -> *mut AnyObject {
- Retained::autorelease_ptr(Objc2NSString::from_str(string)).cast()
+ Retained::autorelease_ptr(NSString::from_str(string)).cast()
}
diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
index 8db0cb9002a..9e99dd6e184 100644
--- a/crates/gpui_macos/src/platform.rs
+++ b/crates/gpui_macos/src/platform.rs
@@ -1,6 +1,6 @@
use crate::{
- AppleActivity, AppleDispatcher, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow,
- events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
+ AppleActivity, AppleDispatcher, BoolExt, MacDisplay, MacKeyboardLayout, MacKeyboardMapper,
+ MacWindow, events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
set_active_window_cursor_style,
};
use anyhow::{Context as _, anyhow};
@@ -766,8 +766,8 @@ impl Platform for MacPlatform {
fn window_appearance(&self) -> WindowAppearance {
unsafe {
let app = NSApplication::sharedApplication(self.1);
- let appearance: *mut AnyObject = msg_send![&app, effectiveAppearance];
- crate::window_appearance::window_appearance_from_native(appearance.cast())
+ let appearance: Option<Retained<NSAppearance>> = msg_send![&app, effectiveAppearance];
+ crate::window_appearance::window_appearance_from_native(appearance.as_deref())
}
}
@@ -1497,7 +1497,7 @@ extern "C-unwind" fn validate_menu_item(this: &AnyObject, _: Sel, item: *mut Any
.validate_menu_command
.get_or_insert(callback);
}
- Bool::new(result)
+ result.to_objc()
}
}
diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs
index 654ae09940b..f2208d35ecd 100644
--- a/crates/gpui_macos/src/window.rs
+++ b/crates/gpui_macos/src/window.rs
@@ -2,27 +2,11 @@ use crate::{
BoolExt, MacDisplay, NSRange, NSStringExt, TISCopyCurrentKeyboardInputSource,
TISGetInputSourceProperty, WindowFrameSource, events::platform_input_from_native,
kTISPropertyInputSourceIsASCIICapable, kTISPropertyInputSourceType, kTISTypeKeyboardInputMode,
- legacy_ns_string as ns_string, renderer,
+ ns_string, renderer,
};
#[cfg(any(test, feature = "test-support"))]
use anyhow::Result;
use block2::RcBlock;
-use cocoa::{
- appkit::{
- NSApplication, NSBackingStoreBuffered, NSColor, NSEvent, NSEventModifierFlags, NSEventType,
- NSFilenamesPboardType, NSPasteboard, NSRequestUserAttentionType, NSScreen, NSView,
- NSViewHeightSizable, NSViewWidthSizable, NSVisualEffectBlendingMode,
- NSVisualEffectMaterial, NSVisualEffectState, NSVisualEffectView, NSWindow,
- NSWindowCollectionBehavior, NSWindowOcclusionState, NSWindowOrderingMode,
- NSWindowStyleMask, NSWindowTitleVisibility,
- },
- base::{id, nil},
- foundation::{
- NSArray, NSAutoreleasePool, NSData, NSDictionary, NSFastEnumeration, NSInteger, NSNotFound,
- NSOperatingSystemVersion, NSPoint, NSProcessInfo, NSRect, NSSize, NSString, NSUInteger,
- NSUserDefaults,
- },
-};
use dispatch2::DispatchQueue;
use gpui::{
AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, CursorStyle, ExternalDragPayload,
@@ -39,29 +23,36 @@ use image::RgbaImage;
use core_foundation::base::{CFRelease, CFTypeRef};
use core_foundation_sys::base::CFEqual;
use core_foundation_sys::number::{CFBooleanGetValue, CFBooleanRef};
-use core_graphics::display::{CGDirectDisplayID, CGRect};
+use core_graphics::display::CGDirectDisplayID;
use ctor::ctor;
use futures::channel::oneshot;
use gpui_util::ResultExt;
-use objc::{
- class,
- declare::ClassDecl,
- msg_send,
- runtime::{BOOL, Class, NO, Object, Protocol, Sel, YES},
- sel, sel_impl,
-};
use objc2::{
- AnyThread, MainThreadMarker,
- rc::Retained,
- runtime::{AnyObject as Objc2Object, ProtocolObject},
+ AnyThread, MainThreadMarker, class, msg_send,
+ rc::{Retained, autoreleasepool},
+ runtime::{AnyClass, AnyObject, AnyProtocol, Bool, ClassBuilder, ProtocolObject, Sel},
+ sel,
};
+#[expect(
+ deprecated,
+ reason = "File-drop decoding expects a property-list array of paths; replacing NSFilenamesPboardType requires migrating both registration and decoding to file URLs"
+)]
+use objc2_app_kit::NSFilenamesPboardType;
use objc2_app_kit::{
- NSAlert, NSAlertStyle, NSBeep, NSButton as Objc2NSButton, NSDraggingImageComponent,
- NSDraggingImageComponentIconKey, NSDraggingItem, NSPasteboardWriting, NSTrackingArea,
- NSTrackingAreaOptions, NSView as Objc2NSView, NSWindow as Objc2NSWindow,
- NSWindowButton as Objc2NSWindowButton, NSWorkspace,
+ NSAlert, NSAlertStyle, NSAppearance, NSAutoresizingMaskOptions, NSBackingStoreType, NSBeep,
+ NSButton, NSColor, NSDragOperation, NSDraggingContext, NSDraggingImageComponent,
+ NSDraggingImageComponentIconKey, NSDraggingItem, NSEventModifierFlags, NSEventType,
+ NSPasteboardWriting, NSRequestUserAttentionType, NSScreen, NSTrackingArea,
+ NSTrackingAreaOptions, NSView, NSViewLayerContentsRedrawPolicy, NSVisualEffectBlendingMode,
+ NSVisualEffectMaterial, NSVisualEffectState, NSWindow, NSWindowAnimationBehavior,
+ NSWindowButton, NSWindowCollectionBehavior, NSWindowOcclusionState, NSWindowOrderingMode,
+ NSWindowStyleMask, NSWindowTitleVisibility, NSWorkspace,
+};
+use objc2_core_graphics::CGColor;
+use objc2_foundation::{
+ NSArray, NSInteger, NSNotFound, NSOperatingSystemVersion, NSPoint, NSProcessInfo, NSRect,
+ NSSize, NSString, NSUInteger, NSURL,
};
-use objc2_foundation::{NSPoint as Objc2NSPoint, NSRect as Objc2NSRect, NSURL};
use parking_lot::Mutex;
use raw_window_handle as rwh;
use smallvec::SmallVec;
@@ -81,20 +72,17 @@ use std::{
time::Duration,
};
-const WINDOW_STATE_IVAR: &str = "windowState";
+const WINDOW_STATE_IVAR: &CStr = c"windowState";
static RESTORES_WORKSPACE_AT_LAUNCH_DEFAULT: Once = Once::new();
-static mut WINDOW_CLASS: *const Class = ptr::null();
-static mut PANEL_CLASS: *const Class = ptr::null();
-static mut VIEW_CLASS: *const Class = ptr::null();
-static mut BLURRED_VIEW_CLASS: *const Class = ptr::null();
-static mut WINDOW_STATE_ARCHIVER_DELEGATE_CLASS: *const Class = ptr::null();
-static mut WINDOW_STATE_UNARCHIVER_CLASS: *const Class = ptr::null();
+static mut WINDOW_CLASS: *const AnyClass = ptr::null();
+static mut PANEL_CLASS: *const AnyClass = ptr::null();
+static mut VIEW_CLASS: *const AnyClass = ptr::null();
+static mut BLURRED_VIEW_CLASS: *const AnyClass = ptr::null();
+static mut WINDOW_STATE_ARCHIVER_DELEGATE_CLASS: *const AnyClass = ptr::null();
+static mut WINDOW_STATE_UNARCHIVER_CLASS: *const AnyClass = ptr::null();
-#[allow(non_upper_case_globals)]
-const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
- NSWindowStyleMask::from_bits_retain(1 << 7);
// WindowLevel const value ref: https://docs.rs/core-graphics2/0.4.1/src/core_graphics2/window_level.rs.html
#[allow(non_upper_case_globals)]
const NSNormalWindowLevel: NSInteger = 0;
@@ -102,20 +90,6 @@ const NSNormalWindowLevel: NSInteger = 0;
const NSFloatingWindowLevel: NSInteger = 3;
#[allow(non_upper_case_globals)]
const NSPopUpWindowLevel: NSInteger = 101;
-#[allow(non_upper_case_globals)]
-const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
-#[allow(non_upper_case_globals)]
-const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
-// https://developer.apple.com/documentation/appkit/nsdragoperation
-type NSDragOperation = NSUInteger;
-#[allow(non_upper_case_globals)]
-const NSDragOperationNone: NSDragOperation = 0;
-#[allow(non_upper_case_globals)]
-const NSDragOperationCopy: NSDragOperation = 1;
-#[allow(non_upper_case_globals)]
-const NSDragOperationMove: NSDragOperation = 16;
-const NSDRAGGING_CONTEXT_OUTSIDE_APPLICATION: NSInteger = 0;
-const NSDRAGGING_CONTEXT_WITHIN_APPLICATION: NSInteger = 1;
#[derive(PartialEq)]
pub enum UserTabbingPreference {
Never,
@@ -126,206 +100,206 @@ pub enum UserTabbingPreference {
#[ctor(unsafe)]
unsafe fn build_classes() {
unsafe {
- WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
- PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
+ WINDOW_CLASS = build_window_class(c"GPUIWindow", class!(NSWindow));
+ PANEL_CLASS = build_window_class(c"GPUIPanel", class!(NSPanel));
VIEW_CLASS = {
- let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
+ let mut decl = ClassBuilder::new(c"GPUIView", class!(NSView)).unwrap();
decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
- decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
+ decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(_, Sel));
decl.add_method(
sel!(performKeyEquivalent:),
- handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
+ handle_key_equivalent as extern "C" fn(_, Sel, *mut AnyObject) -> Bool,
);
decl.add_method(
sel!(keyDown:),
- handle_key_down as extern "C" fn(&Object, Sel, id),
+ handle_key_down as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(keyUp:),
- handle_key_up as extern "C" fn(&Object, Sel, id),
+ handle_key_up as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(mouseDown:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(mouseUp:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(rightMouseDown:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(rightMouseUp:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(otherMouseDown:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(otherMouseUp:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(mouseMoved:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(resetCursorRects),
- reset_cursor_rects as extern "C" fn(&Object, Sel),
+ reset_cursor_rects as extern "C" fn(_, Sel),
);
decl.add_method(
sel!(pressureChangeWithEvent:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(mouseExited:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(magnifyWithEvent:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(mouseDragged:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(rightMouseDragged:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(otherMouseDragged:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(scrollWheel:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(swipeWithEvent:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(flagsChanged:),
- handle_view_event as extern "C" fn(&Object, Sel, id),
+ handle_view_event as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(makeBackingLayer),
- make_backing_layer as extern "C" fn(&Object, Sel) -> id,
+ make_backing_layer as extern "C" fn(_, Sel) -> *mut AnyObject,
);
- decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
+ decl.add_protocol(AnyProtocol::get(c"CALayerDelegate").unwrap());
decl.add_method(
sel!(viewDidChangeBackingProperties),
- view_did_change_backing_properties as extern "C" fn(&Object, Sel),
+ view_did_change_backing_properties as extern "C" fn(_, Sel),
);
decl.add_method(
sel!(setFrameSize:),
- set_frame_size as extern "C" fn(&Object, Sel, NSSize),
+ set_frame_size as extern "C" fn(_, Sel, NSSize),
);
decl.add_method(
sel!(displayLayer:),
- display_layer as extern "C" fn(&Object, Sel, id),
+ display_layer as extern "C" fn(_, Sel, *mut AnyObject),
);
- decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
+ decl.add_protocol(AnyProtocol::get(c"NSTextInputClient").unwrap());
decl.add_method(
sel!(validAttributesForMarkedText),
- valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
+ valid_attributes_for_marked_text as extern "C" fn(_, Sel) -> *mut AnyObject,
);
decl.add_method(
sel!(hasMarkedText),
- has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
+ has_marked_text as extern "C" fn(_, Sel) -> Bool,
);
decl.add_method(
sel!(markedRange),
- marked_range as extern "C" fn(&Object, Sel) -> NSRange,
+ marked_range as extern "C" fn(_, Sel) -> NSRange,
);
decl.add_method(
sel!(selectedRange),
- selected_range as extern "C" fn(&Object, Sel) -> NSRange,
+ selected_range as extern "C" fn(_, Sel) -> NSRange,
);
decl.add_method(
sel!(firstRectForCharacterRange:actualRange:),
first_rect_for_character_range
- as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
+ as extern "C" fn(_, Sel, NSRange, *mut NSRange) -> NSRect,
);
decl.add_method(
sel!(insertText:replacementRange:),
- insert_text as extern "C" fn(&Object, Sel, id, NSRange),
+ insert_text as extern "C" fn(_, Sel, *mut AnyObject, NSRange),
);
decl.add_method(
sel!(setMarkedText:selectedRange:replacementRange:),
- set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
+ set_marked_text as extern "C" fn(_, Sel, *mut AnyObject, NSRange, NSRange),
);
- decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
+ decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(_, Sel));
decl.add_method(
sel!(attributedSubstringForProposedRange:actualRange:),
attributed_substring_for_proposed_range
- as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
+ as extern "C" fn(_, Sel, NSRange, *mut NSRange) -> *mut AnyObject,
);
decl.add_method(
sel!(viewDidChangeEffectiveAppearance),
- view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
+ view_did_change_effective_appearance as extern "C" fn(_, Sel),
);
// Suppress beep on keystrokes with modifier keys.
decl.add_method(
sel!(doCommandBySelector:),
- do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
+ do_command_by_selector as extern "C" fn(_, Sel, Sel),
);
decl.add_method(
sel!(acceptsFirstMouse:),
- accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
+ accepts_first_mouse as extern "C" fn(_, Sel, *mut AnyObject) -> Bool,
);
decl.add_method(
sel!(_opaqueRectForWindowMoveWhenInTitlebar),
- opaque_rect_for_window_move_when_in_titlebar
- as extern "C" fn(&Object, Sel) -> NSRect,
+ opaque_rect_for_window_move_when_in_titlebar as extern "C" fn(_, Sel) -> NSRect,
);
decl.add_method(
sel!(characterIndexForPoint:),
- character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> u64,
+ character_index_for_point as extern "C" fn(_, Sel, NSPoint) -> NSUInteger,
);
decl.register()
};
BLURRED_VIEW_CLASS = {
- let mut decl = ClassDecl::new("BlurredView", class!(NSVisualEffectView)).unwrap();
+ let mut decl = ClassBuilder::new(c"BlurredView", class!(NSVisualEffectView)).unwrap();
decl.add_method(
sel!(initWithFrame:),
- blurred_view_init_with_frame as extern "C" fn(&Object, Sel, NSRect) -> id,
+ blurred_view_init_with_frame as extern "C" fn(_, Sel, NSRect) -> *mut AnyObject,
);
decl.add_method(
sel!(updateLayer),
- blurred_view_update_layer as extern "C" fn(&Object, Sel),
+ blurred_view_update_layer as extern "C" fn(_, Sel),
);
decl.register()
};
WINDOW_STATE_ARCHIVER_DELEGATE_CLASS = {
let mut decl =
- ClassDecl::new("GPUIWindowStateArchiverDelegate", class!(NSObject)).unwrap();
+ ClassBuilder::new(c"GPUIWindowStateArchiverDelegate", class!(NSObject)).unwrap();
decl.add_method(
sel!(archiver:willEncodeObject:),
window_state_archiver_will_encode_object
- as extern "C" fn(&Object, Sel, id, id) -> id,
+ as extern "C" fn(_, Sel, *mut AnyObject, *mut AnyObject) -> *mut AnyObject,
);
decl.register()
};
WINDOW_STATE_UNARCHIVER_CLASS = {
let mut decl =
- ClassDecl::new("GPUIWindowStateKeyedUnarchiver", class!(NSKeyedUnarchiver))
+ ClassBuilder::new(c"GPUIWindowStateKeyedUnarchiver", class!(NSKeyedUnarchiver))
.unwrap();
decl.add_method(
sel!(_windowRestorationOptions),
- window_state_unarchiver_restoration_options as extern "C" fn(&Object, Sel) -> id,
+ window_state_unarchiver_restoration_options
+ as extern "C" fn(_, Sel) -> *mut AnyObject,
);
decl.register()
};
@@ -337,21 +311,21 @@ unsafe fn build_classes() {
// succeeds. AppKit still encodes the window frame and its persistent window-management
// identifier, which is what the Space restoration on relaunch keys off.
extern "C" fn window_state_archiver_will_encode_object(
- _this: &Object,
+ _this: &AnyObject,
_sel: Sel,
- _archiver: id,
- object: id,
-) -> id {
+ _archiver: *mut AnyObject,
+ object: *mut AnyObject,
+) -> *mut AnyObject {
// SAFETY: `object` is whatever AppKit hands the delegate during archiving; we only send it
// `isKindOfClass:` with valid class arguments, which is safe for any Objective-C object.
unsafe {
if object.is_null() {
return object;
}
- let is_view: BOOL = msg_send![object, isKindOfClass: class!(NSView)];
- let is_window: BOOL = msg_send![object, isKindOfClass: class!(NSWindow)];
- if is_view == YES || is_window == YES {
- nil
+ let is_view: Bool = msg_send![object, isKindOfClass: class!(NSView)];
+ let is_window: Bool = msg_send![object, isKindOfClass: class!(NSWindow)];
+ if is_view == Bool::YES || is_window == Bool::YES {
+ ptr::null_mut()
} else {
object
}
@@ -362,20 +336,27 @@ extern "C" fn window_state_archiver_will_encode_object(
// Returning a default-initialized `NSWindowRestorationOptions` tells AppKit to restore the
// window to its original Space. This is the macOS 15+ path (FB15644170: the
// `NSWindowRestoresWorkspaceAtLaunch` user default no longer works there).
-extern "C" fn window_state_unarchiver_restoration_options(_this: &Object, _sel: Sel) -> id {
- if !is_macos_version_at_least(NSOperatingSystemVersion::new(15, 0, 0)) {
- return nil;
+extern "C" fn window_state_unarchiver_restoration_options(
+ _this: &AnyObject,
+ _sel: Sel,
+) -> *mut AnyObject {
+ if !is_macos_version_at_least(NSOperatingSystemVersion {
+ majorVersion: 15,
+ minorVersion: 0,
+ patchVersion: 0,
+ }) {
+ return ptr::null_mut();
}
// SAFETY: we look the class up by name and only send it `alloc`/`init`/`autorelease`, all of
// which have the standard `-> id` signature. Returning `nil` when the class is absent is valid.
unsafe {
- match Class::get("NSWindowRestorationOptions") {
+ match AnyClass::get(c"NSWindowRestorationOptions") {
Some(class) => {
- let options: id = msg_send![class, alloc];
- let options: id = msg_send![options, init];
+ let options: *mut AnyObject = msg_send![class, alloc];
+ let options: *mut AnyObject = msg_send![options, init];
msg_send![options, autorelease]
}
- None => nil,
+ None => ptr::null_mut(),
}
}
}
@@ -399,9 +380,9 @@ pub(crate) unsafe fn set_active_window_cursor_style(style: CursorStyle) {
// SAFETY: The caller guarantees AppKit main-thread access. `is_gpui_window` ensures the
// window has our WINDOW_STATE_IVAR before reading it.
unsafe {
- let app = NSApplication::sharedApplication(nil);
- let key_window: id = msg_send![app, keyWindow];
- let main_window: id = msg_send![app, mainWindow];
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let key_window: *mut AnyObject = msg_send![app, keyWindow];
+ let main_window: *mut AnyObject = msg_send![app, mainWindow];
let active_window = if !key_window.is_null() && is_gpui_window(key_window) {
Some(key_window)
} else if !main_window.is_null() && is_gpui_window(main_window) {
@@ -426,127 +407,128 @@ pub(crate) unsafe fn set_active_window_cursor_style(style: CursorStyle) {
}
}
-unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
+unsafe fn build_window_class(name: &CStr, superclass: &AnyClass) -> *const AnyClass {
unsafe {
- let mut decl = ClassDecl::new(name, superclass).unwrap();
+ let mut decl = ClassBuilder::new(name, superclass).unwrap();
decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
- decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
+ decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(_, Sel));
decl.add_method(
sel!(canBecomeMainWindow),
- yes as extern "C" fn(&Object, Sel) -> BOOL,
+ yes as extern "C" fn(_, Sel) -> Bool,
);
decl.add_method(
sel!(canBecomeKeyWindow),
- yes as extern "C" fn(&Object, Sel) -> BOOL,
+ yes as extern "C" fn(_, Sel) -> Bool,
);
decl.add_method(
sel!(windowDidResize:),
- window_did_resize as extern "C" fn(&Object, Sel, id),
+ window_did_resize as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidChangeOcclusionState:),
- window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
+ window_did_change_occlusion_state as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowWillEnterFullScreen:),
- window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
+ window_will_enter_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowWillExitFullScreen:),
- window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
+ window_will_exit_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidFailToExitFullScreen:),
- window_did_fail_to_exit_fullscreen as extern "C" fn(&Object, Sel, id),
+ window_did_fail_to_exit_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidExitFullScreen:),
- window_did_exit_fullscreen as extern "C" fn(&Object, Sel, id),
+ window_did_exit_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidMove:),
- window_did_move as extern "C" fn(&Object, Sel, id),
+ window_did_move as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidChangeScreen:),
- window_did_change_screen as extern "C" fn(&Object, Sel, id),
+ window_did_change_screen as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidBecomeKey:),
- window_did_change_key_status as extern "C" fn(&Object, Sel, id),
+ window_did_change_key_status as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowDidResignKey:),
- window_did_change_key_status as extern "C" fn(&Object, Sel, id),
+ window_did_change_key_status as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(windowShouldClose:),
- window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
+ window_should_close as extern "C" fn(_, Sel, *mut AnyObject) -> Bool,
);
- decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
+ decl.add_method(sel!(close), close_window as extern "C" fn(_, Sel));
decl.add_method(
sel!(draggingEntered:),
- dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
+ dragging_entered as extern "C" fn(_, Sel, *mut AnyObject) -> NSDragOperation,
);
decl.add_method(
sel!(draggingUpdated:),
- dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
+ dragging_updated as extern "C" fn(_, Sel, *mut AnyObject) -> NSDragOperation,
);
decl.add_method(
sel!(draggingExited:),
- dragging_exited as extern "C" fn(&Object, Sel, id),
+ dragging_exited as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(performDragOperation:),
- perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
+ perform_drag_operation as extern "C" fn(_, Sel, *mut AnyObject) -> Bool,
);
decl.add_method(
sel!(concludeDragOperation:),
- conclude_drag_operation as extern "C" fn(&Object, Sel, id),
+ conclude_drag_operation as extern "C" fn(_, Sel, *mut AnyObject),
);
- decl.add_protocol(Protocol::get("NSDraggingSource").unwrap());
+ decl.add_protocol(AnyProtocol::get(c"NSDraggingSource").unwrap());
decl.add_method(
sel!(draggingSession:sourceOperationMaskForDraggingContext:),
dragging_session_source_operation_mask
- as extern "C" fn(&Object, Sel, id, NSInteger) -> NSDragOperation,
+ as extern "C" fn(_, Sel, *mut AnyObject, NSDraggingContext) -> NSDragOperation,
);
decl.add_method(
sel!(draggingSession:endedAtPoint:operation:),
- dragging_session_ended as extern "C" fn(&Object, Sel, id, NSPoint, NSDragOperation),
+ dragging_session_ended
+ as extern "C" fn(_, Sel, *mut AnyObject, NSPoint, NSDragOperation),
);
decl.add_method(
sel!(addTitlebarAccessoryViewController:),
- add_titlebar_accessory_view_controller as extern "C" fn(&Object, Sel, id),
+ add_titlebar_accessory_view_controller as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(moveTabToNewWindow:),
- move_tab_to_new_window as extern "C" fn(&Object, Sel, id),
+ move_tab_to_new_window as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(mergeAllWindows:),
- merge_all_windows as extern "C" fn(&Object, Sel, id),
+ merge_all_windows as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(selectNextTab:),
- select_next_tab as extern "C" fn(&Object, Sel, id),
+ select_next_tab as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(selectPreviousTab:),
- select_previous_tab as extern "C" fn(&Object, Sel, id),
+ select_previous_tab as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.add_method(
sel!(toggleTabBar:),
- toggle_tab_bar as extern "C" fn(&Object, Sel, id),
+ toggle_tab_bar as extern "C" fn(_, Sel, *mut AnyObject),
);
decl.register()
@@ -555,16 +537,16 @@ unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const C
#[derive(Clone, Copy)]
struct TrafficLightFrames {
- titlebar: Objc2NSRect,
- close: Objc2NSRect,
- minimize: Objc2NSRect,
- zoom: Objc2NSRect,
+ titlebar: NSRect,
+ close: NSRect,
+ minimize: NSRect,
+ zoom: NSRect,
}
struct TrafficLightButtons {
- close: Retained<Objc2NSButton>,
- minimize: Retained<Objc2NSButton>,
- zoom: Retained<Objc2NSButton>,
+ close: Retained<NSButton>,
+ minimize: Retained<NSButton>,
+ zoom: Retained<NSButton>,
}
// `NSApplicationPresentationOptions` bits (see `NSApplication.PresentationOptions`).
@@ -596,7 +578,7 @@ unsafe fn push_simple_fullscreen_presentation_options() {
match app_state.as_mut() {
Some(app_state) => app_state.window_count += 1,
None => unsafe {
- let app = NSApplication::sharedApplication(nil);
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let saved_presentation_options: NSUInteger = msg_send![app, presentationOptions];
let _: () = msg_send![
app,
@@ -617,7 +599,7 @@ unsafe fn pop_simple_fullscreen_presentation_options() {
state.window_count = state.window_count.saturating_sub(1);
if state.window_count == 0 {
unsafe {
- let app = NSApplication::sharedApplication(nil);
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let _: () = msg_send![
app,
setPresentationOptions: state.saved_presentation_options
@@ -629,29 +611,29 @@ unsafe fn pop_simple_fullscreen_presentation_options() {
}
unsafe fn apply_simple_fullscreen_plan(
- native_window: id,
- native_view: id,
+ native_window: *mut AnyObject,
+ native_view: *mut AnyObject,
plan: SimpleFullscreenPlan,
) {
unsafe {
match plan {
SimpleFullscreenPlan::Exit(saved) => {
pop_simple_fullscreen_presentation_options();
- native_window.setStyleMask_(saved.style_mask);
- native_window.setFrame_display_(saved.frame, YES);
+ let _: () = msg_send![native_window, setStyleMask: saved.style_mask];
+ let _: () = msg_send![native_window, setFrame: saved.frame, display: Bool::YES];
}
SimpleFullscreenPlan::Enter { screen_frame } => {
push_simple_fullscreen_presentation_options();
- native_window.setStyleMask_(NSWindowStyleMask::NSBorderlessWindowMask);
- native_window.setFrame_display_(screen_frame, YES);
+ let _: () = msg_send![native_window, setStyleMask: NSWindowStyleMask::Borderless];
+ let _: () = msg_send![native_window, setFrame: screen_frame, display: Bool::YES];
}
}
// Changing the style mask makes AppKit resign the window's key status and
// first responder, so keyboard input stops reaching the editor. Re-make the
// window key and restore the GPUI view as first responder.
- native_window.makeKeyAndOrderFront_(nil);
- native_window.makeFirstResponder_(native_view);
+ let _: () = msg_send![native_window, makeKeyAndOrderFront: ptr::null_mut::<AnyObject>()];
+ let _: Bool = msg_send![native_window, makeFirstResponder: native_view];
}
}
@@ -659,9 +641,9 @@ struct MacWindowState {
handle: AnyWindowHandle,
foreground_executor: ForegroundExecutor,
background_executor: BackgroundExecutor,
- native_window: id,
- native_view: NonNull<Object>,
- blurred_view: Option<id>,
+ native_window: *mut AnyObject,
+ native_view: NonNull<AnyObject>,
+ blurred_view: Option<*mut AnyObject>,
background_appearance: WindowBackgroundAppearance,
cursor_style: CursorStyle,
cursor_visible: Arc<AtomicBool>,
@@ -682,7 +664,7 @@ struct MacWindowState {
appearance_changed_callback: Option<Box<dyn FnMut()>>,
input_handler: Option<PlatformInputHandler>,
last_key_equivalent: Option<KeyDownEvent>,
- last_left_mouse_down_event: Option<Retained<Objc2Object>>,
+ last_left_mouse_down_event: Option<Retained<AnyObject>>,
synthetic_drag_counter: usize,
traffic_light_position: Option<Point<Pixels>>,
traffic_light_frames: Option<TrafficLightFrames>,
@@ -711,7 +693,7 @@ struct MacWindowState {
closed: Arc<AtomicBool>,
accesskit_adapter: Option<accesskit_macos::SubclassingAdapter>,
// The parent window if this window is a sheet (Dialog kind)
- sheet_parent: Option<id>,
+ sheet_parent: Option<*mut AnyObject>,
}
impl MacWindowState {
@@ -754,15 +736,15 @@ impl MacWindowState {
let zoom_x = minimize_x + button_width + button_padding;
titlebar_container.setFrame(titlebar_frame);
- buttons.close.setFrameOrigin(Objc2NSPoint::new(
+ buttons.close.setFrameOrigin(NSPoint::new(
traffic_light_position.x.to_f64(),
traffic_light_position.y.to_f64(),
));
- buttons.minimize.setFrameOrigin(Objc2NSPoint::new(
+ buttons.minimize.setFrameOrigin(NSPoint::new(
minimize_x.to_f64(),
traffic_light_position.y.to_f64(),
));
- buttons.zoom.setFrameOrigin(Objc2NSPoint::new(
+ buttons.zoom.setFrameOrigin(NSPoint::new(
zoom_x.to_f64(),
traffic_light_position.y.to_f64(),
));
@@ -787,23 +769,22 @@ impl MacWindowState {
})
}
- fn native_window(&self) -> &Objc2NSWindow {
- // SAFETY: `MacWindow::new` initializes `self.native_window` with the AppKit
- // window for this state. It is either `NSWindow` or `NSPanel`, so borrowing it
- // as `Objc2NSWindow` is valid here.
- unsafe { &*self.native_window.cast::<Objc2NSWindow>() }
+ fn native_window(&self) -> &NSWindow {
+ // SAFETY: `MacWindow::open` initializes this pointer with an `NSWindow` or `NSPanel` instance.
+ // Both types can be borrowed as `NSWindow`.
+ unsafe { &*self.native_window.cast::<NSWindow>() }
}
fn traffic_light_buttons(&self) -> Option<TrafficLightButtons> {
let window = self.native_window();
Some(TrafficLightButtons {
- close: window.standardWindowButton(Objc2NSWindowButton::CloseButton)?,
- minimize: window.standardWindowButton(Objc2NSWindowButton::MiniaturizeButton)?,
- zoom: window.standardWindowButton(Objc2NSWindowButton::ZoomButton)?,
+ close: window.standardWindowButton(NSWindowButton::CloseButton)?,
+ minimize: window.standardWindowButton(NSWindowButton::MiniaturizeButton)?,
+ zoom: window.standardWindowButton(NSWindowButton::ZoomButton)?,
})
}
- fn titlebar_container(close_button: &Objc2NSButton) -> Option<Retained<Objc2NSView>> {
+ fn titlebar_container(close_button: &NSButton) -> Option<Retained<NSView>> {
// SAFETY: `close_button` comes from AppKit's `standardWindowButton(_:)`.
// Although `superview` is unsafe, objc2 returns each result as `Retained<NSView>`.
unsafe {
@@ -835,16 +816,15 @@ impl MacWindowState {
fn start_display_link(&mut self) {
self.stop_display_link();
- unsafe {
- if !self
- .native_window
- .occlusionState()
- .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
- {
- return;
- }
+ if !self
+ .native_window()
+ .occlusionState()
+ .contains(NSWindowOcclusionState::Visible)
+ {
+ return;
}
- let Some(display_id) = display_id_for_screen(unsafe { self.native_window.screen() }) else {
+ let screen: *mut AnyObject = unsafe { msg_send![self.native_window, screen] };
+ let Some(display_id) = display_id_for_screen(screen) else {
// AppKit can temporarily report no screen while displays are being reconfigured.
return;
};
@@ -867,18 +847,18 @@ impl MacWindowState {
size(width.into(), height.into())
}
- unsafe {
- let bounds = self.bounds();
- let screen_size = rect_to_size(self.native_window.screen().visibleFrame());
- bounds.size == screen_size
- }
+ let bounds = self.bounds();
+ let screen_frame = self
+ .native_window()
+ .screen()
+ .map_or_default(|screen| screen.visibleFrame());
+ bounds.size == rect_to_size(screen_frame)
}
fn is_fullscreen(&self) -> bool {
- unsafe {
- let style_mask = self.native_window.styleMask();
- style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
- }
+ self.native_window()
+ .styleMask()
+ .contains(NSWindowStyleMask::FullScreen)
}
fn toggle_simple_fullscreen(&mut self) -> Option<SimpleFullscreenPlan> {
@@ -891,17 +871,14 @@ impl MacWindowState {
if let Some(saved) = self.simple_fullscreen_state.take() {
Some(SimpleFullscreenPlan::Exit(saved))
} else {
- let screen = unsafe { self.native_window.screen() };
- if screen == nil {
- return None;
- }
- let screen_frame = unsafe { NSScreen::frame(screen) };
+ let screen = self.native_window().screen()?;
+ let screen_frame = screen.frame();
let bounds = self.bounds();
self.simple_fullscreen_state = Some(SimpleFullscreenState {
- frame: unsafe { NSWindow::frame(self.native_window) },
+ frame: self.native_window().frame(),
bounds,
- style_mask: unsafe { self.native_window.styleMask() },
+ style_mask: self.native_window().styleMask(),
});
Some(SimpleFullscreenPlan::Enter { screen_frame })
@@ -909,12 +886,11 @@ impl MacWindowState {
}
fn bounds(&self) -> Bounds<Pixels> {
- let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
- let screen = unsafe { NSWindow::screen(self.native_window) };
- if screen == nil {
+ let mut window_frame = self.native_window().frame();
+ let Some(screen) = self.native_window().screen() else {
return Bounds::new(point(px(0.), px(0.)), gpui::DEFAULT_WINDOW_SIZE);
- }
- let screen_frame = unsafe { NSScreen::frame(screen) };
+ };
+ let screen_frame = screen.frame();
// Flip the y coordinate to be top-left origin
window_frame.origin.y =
@@ -933,8 +909,10 @@ impl MacWindowState {
}
fn content_size(&self) -> Size<Pixels> {
- let NSSize { width, height, .. } =
- unsafe { NSView::frame(self.native_window.contentView()) }.size;
+ let NSSize { width, height } = self
+ .native_window()
+ .contentView()
+ .map_or_default(|view| view.frame().size);
size(px(width as f32), px(height as f32))
}
@@ -982,45 +960,41 @@ impl MacWindow {
renderer_context: renderer::Context,
marker: MainThreadMarker,
) -> Self {
- unsafe {
- let pool = NSAutoreleasePool::new(nil);
-
+ autoreleasepool(|_| unsafe {
let allows_automatic_window_tabbing = tabbing_identifier.is_some();
if allows_automatic_window_tabbing {
- let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
+ let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: Bool::YES];
} else {
- let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
+ let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: Bool::NO];
}
let mut style_mask;
if let Some(titlebar) = titlebar.as_ref() {
- style_mask =
- NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSTitledWindowMask;
+ style_mask = NSWindowStyleMask::Closable | NSWindowStyleMask::Titled;
if is_resizable {
- style_mask |= NSWindowStyleMask::NSResizableWindowMask;
+ style_mask |= NSWindowStyleMask::Resizable;
}
if is_minimizable {
- style_mask |= NSWindowStyleMask::NSMiniaturizableWindowMask;
+ style_mask |= NSWindowStyleMask::Miniaturizable;
}
if titlebar.appears_transparent {
- style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
+ style_mask |= NSWindowStyleMask::FullSizeContentView;
}
} else {
- style_mask = NSWindowStyleMask::NSTitledWindowMask
- | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
+ style_mask = NSWindowStyleMask::Titled | NSWindowStyleMask::FullSizeContentView;
}
- let native_window: id = match kind {
+ let native_window: *mut AnyObject = match kind {
WindowKind::Normal => {
msg_send![WINDOW_CLASS, alloc]
}
// `AnchoredPopup` is rejected in `MacPlatform::open_window`, grouped here only
// for exhaustiveness.
WindowKind::PopUp | WindowKind::AnchoredPopup(_) => {
- style_mask |= NSWindowStyleMaskNonactivatingPanel;
+ style_mask |= NSWindowStyleMask::NonactivatingPanel;
msg_send![PANEL_CLASS, alloc]
}
WindowKind::Floating | WindowKind::Dialog => {
@@ -1032,28 +1006,19 @@ impl MacWindow {
.and_then(MacDisplay::find_by_id)
.unwrap_or_else(MacDisplay::primary);
- let mut target_screen = nil;
- let mut screen_frame = None;
-
- let screens = NSScreen::screens(nil);
- let count: u64 = cocoa::foundation::NSArray::count(screens);
- for i in 0..count {
- let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
- let Some(display_id) = display_id_for_screen(screen) else {
- continue;
- };
- let frame = NSScreen::frame(screen);
- if display_id == display.0 {
- screen_frame = Some(frame);
- target_screen = screen;
+ let mut target_screen = None;
+ let screens = NSScreen::screens(marker);
+ for screen in screens.iter() {
+ if display_id_for_screen(Retained::as_ptr(&screen).cast_mut().cast())
+ == Some(display.0)
+ {
+ target_screen = Some(screen);
}
}
-
- let screen_frame = screen_frame.unwrap_or_else(|| {
- let screen = NSScreen::mainScreen(nil);
- target_screen = screen;
- NSScreen::frame(screen)
- });
+ let target_screen = target_screen.or_else(|| NSScreen::mainScreen(marker));
+ let screen_frame = target_screen
+ .as_ref()
+ .map_or_default(|screen| screen.frame());
let window_rect = NSRect::new(
NSPoint::new(
@@ -1067,27 +1032,33 @@ impl MacWindow {
),
);
- let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
- window_rect,
- style_mask,
- NSBackingStoreBuffered,
- NO,
- target_screen,
- );
+ let native_window: *mut AnyObject = msg_send![
+ native_window,
+ initWithContentRect: window_rect,
+ styleMask: style_mask,
+ backing: NSBackingStoreType::Buffered,
+ defer: Bool::NO,
+ screen: target_screen.as_deref()
+ ];
assert!(!native_window.is_null());
+ #[expect(
+ deprecated,
+ reason = "File-drop decoding expects a property-list array of paths; replacing NSFilenamesPboardType requires migrating both registration and decoding to file URLs"
+ )]
let () = msg_send![
native_window,
registerForDraggedTypes:
- NSArray::arrayWithObject(nil, NSFilenamesPboardType)
+ &*NSArray::from_slice(&[NSFilenamesPboardType])
];
let () = msg_send![
native_window,
- setReleasedWhenClosed: NO
+ setReleasedWhenClosed: Bool::NO
];
- let content_view = native_window.contentView();
- let native_view: id = msg_send![VIEW_CLASS, alloc];
- let native_view = NSView::initWithFrame_(native_view, NSView::bounds(content_view));
+ let content_view: *mut AnyObject = msg_send![native_window, contentView];
+ let native_view: *mut AnyObject = msg_send![VIEW_CLASS, alloc];
+ let content_bounds: NSRect = msg_send![content_view, bounds];
+ let native_view: *mut AnyObject = msg_send![native_view, initWithFrame: content_bounds];
assert!(!native_view.is_null());
let state = Arc::new(Mutex::new(MacWindowState {
@@ -1153,15 +1124,19 @@ impl MacWindow {
}));
let mut window = Self(state, marker);
- (*native_window).set_ivar(
- WINDOW_STATE_IVAR,
- Arc::into_raw(window.0.clone()) as *const c_void,
- );
- native_window.setDelegate_(native_window);
- (*native_view).set_ivar(
- WINDOW_STATE_IVAR,
- Arc::into_raw(window.0.clone()) as *const c_void,
- );
+ (*native_window)
+ .class()
+ .instance_variable(WINDOW_STATE_IVAR)
+ .expect("GPUI window state ivar")
+ .load_ptr::<*mut c_void>(&*native_window)
+ .write(Arc::into_raw(window.0.clone()).cast_mut().cast());
+ let _: () = msg_send![native_window, setDelegate: native_window];
+ (*native_view)
+ .class()
+ .instance_variable(WINDOW_STATE_IVAR)
+ .expect("GPUI view state ivar")
+ .load_ptr::<*mut c_void>(&*native_view)
+ .write(Arc::into_raw(window.0.clone()).cast_mut().cast());
if let Some(title) = titlebar
.as_ref()
@@ -1170,54 +1145,57 @@ impl MacWindow {
window.set_title(title);
}
- native_window.setMovable_(is_movable as BOOL);
+ let _: () = msg_send![native_window, setMovable: is_movable.to_objc()];
if let Some(window_min_size) = window_min_size {
- native_window.setContentMinSize_(NSSize {
+ let _: () = msg_send![native_window, setContentMinSize: NSSize {
width: window_min_size.width.to_f64(),
height: window_min_size.height.to_f64(),
- });
+ }];
}
if titlebar.is_none_or(|titlebar| titlebar.appears_transparent) {
- native_window.setTitlebarAppearsTransparent_(YES);
- native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
+ let _: () = msg_send![native_window, setTitlebarAppearsTransparent: Bool::YES];
+ let _: () =
+ msg_send![native_window, setTitleVisibility: NSWindowTitleVisibility::Hidden];
}
- native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
- native_view.setWantsBestResolutionOpenGLSurface_(YES);
+ let _: () = msg_send![native_view, setAutoresizingMask: NSAutoresizingMaskOptions::ViewWidthSizable
+ | NSAutoresizingMaskOptions::ViewHeightSizable];
+ let _: () = msg_send![native_view, setWantsBestResolutionOpenGLSurface: Bool::YES];
// From winit crate: On Mojave, views automatically become layer-backed shortly after
// being added to a native_window. Changing the layer-backedness of a view breaks the
// association between the view and its associated OpenGL context. To work around this,
// on we explicitly make the view layer-backed up front so that AppKit doesn't do it
// itself and break the association with its context.
- native_view.setWantsLayer(YES);
+ let _: () = msg_send![native_view, setWantsLayer: Bool::YES];
let _: () = msg_send![
native_view,
- setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
+ setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawPolicy::DuringViewResize
];
- content_view.addSubview_(native_view.autorelease());
- native_window.makeFirstResponder_(native_view);
+ let native_view: *mut AnyObject = msg_send![native_view, autorelease];
+ let _: () = msg_send![content_view, addSubview: native_view];
+ let _: Bool = msg_send![native_window, makeFirstResponder: native_view];
- let app: id = NSApplication::sharedApplication(nil);
- let main_window: id = msg_send![app, mainWindow];
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let main_window: *mut AnyObject = msg_send![app, mainWindow];
let mut sheet_parent = None;
// SAFETY: This is the live GPUIView (an NSView subclass) added to the
// content view above, and window creation runs on the main thread.
- let tracking_view = &*native_view.cast::<Objc2NSView>();
+ let tracking_view = &*native_view.cast::<NSView>();
match kind {
WindowKind::Normal | WindowKind::Floating => {
if kind == WindowKind::Floating {
// Let the window float keep above normal windows.
- native_window.setLevel_(NSFloatingWindowLevel);
- native_window.setAcceptsMouseMovedEvents_(YES);
+ let _: () = msg_send![native_window, setLevel: NSFloatingWindowLevel];
+ let _: () = msg_send![native_window, setAcceptsMouseMovedEvents: Bool::YES];
} else {
- native_window.setLevel_(NSNormalWindowLevel);
- native_window.setAcceptsMouseMovedEvents_(NO);
+ let _: () = msg_send![native_window, setLevel: NSNormalWindowLevel];
+ let _: () = msg_send![native_window, setAcceptsMouseMovedEvents: Bool::NO];
add_mouse_tracking_area(tracking_view);
}
@@ -1225,7 +1203,7 @@ impl MacWindow {
let tabbing_id = ns_string(tabbing_identifier.as_str());
let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
} else {
- let _: () = msg_send![native_window, setTabbingIdentifier:nil];
+ let _: () = msg_send![native_window, setTabbingIdentifier:ptr::null_mut::<AnyObject>()];
}
}
// `AnchoredPopup` is rejected in `MacPlatform::open_window`, grouped here only
@@ -1233,28 +1211,26 @@ impl MacWindow {
WindowKind::PopUp | WindowKind::AnchoredPopup(_) => {
add_mouse_tracking_area(tracking_view);
- native_window.setLevel_(NSPopUpWindowLevel);
+ let _: () = msg_send![native_window, setLevel: NSPopUpWindowLevel];
let _: () = msg_send![
native_window,
- setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
+ setAnimationBehavior: NSWindowAnimationBehavior::UtilityWindow
];
- native_window.setCollectionBehavior_(
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
- );
+ let _: () = msg_send![native_window, setCollectionBehavior: NSWindowCollectionBehavior::CanJoinAllSpaces
+ | NSWindowCollectionBehavior::FullScreenAuxiliary];
}
WindowKind::Dialog => {
if !main_window.is_null() {
let parent = {
- let active_sheet: id = msg_send![main_window, attachedSheet];
+ let active_sheet: *mut AnyObject =
+ msg_send![main_window, attachedSheet];
if active_sheet.is_null() {
main_window
} else {
active_sheet
}
};
- let _: () =
- msg_send![parent, beginSheet: native_window completionHandler: nil];
+ let _: () = msg_send![parent, beginSheet: native_window, completionHandler: None::<&block2::Block<dyn Fn(NSInteger)>>];
sheet_parent = Some(parent);
}
}
@@ -1264,9 +1240,9 @@ impl MacWindow {
&& !main_window.is_null()
&& main_window != native_window
{
- let main_window_is_fullscreen = main_window
+ let main_window_is_fullscreen = (&*main_window.cast::<NSWindow>())
.styleMask()
- .contains(NSWindowStyleMask::NSFullScreenWindowMask);
+ .contains(NSWindowStyleMask::FullScreen);
let user_tabbing_preference = Self::get_user_tabbing_preference()
.unwrap_or(UserTabbingPreference::InFullScreen);
let should_add_as_tab = user_tabbing_preference == UserTabbingPreference::Always
@@ -1274,49 +1250,49 @@ impl MacWindow {
&& main_window_is_fullscreen;
if should_add_as_tab {
- let main_window_can_tab: BOOL =
+ let main_window_can_tab: Bool =
msg_send![main_window, respondsToSelector: sel!(addTabbedWindow:ordered:)];
- let main_window_visible: BOOL = msg_send![main_window, isVisible];
+ let main_window_visible: Bool = msg_send![main_window, isVisible];
- if main_window_can_tab == YES && main_window_visible == YES {
- let _: () = msg_send![main_window, addTabbedWindow: native_window ordered: NSWindowOrderingMode::NSWindowAbove];
+ if main_window_can_tab == Bool::YES && main_window_visible == Bool::YES {
+ let _: () = msg_send![main_window, addTabbedWindow: native_window, ordered: NSWindowOrderingMode::Above];
// Ensure the window is visible immediately after adding the tab, since the tab bar is updated with a new entry at this point.
// Note: Calling orderFront here can break fullscreen mode (makes fullscreen windows exit fullscreen), so only do this if the main window is not fullscreen.
if !main_window_is_fullscreen {
- let _: () = msg_send![native_window, orderFront: nil];
+ let _: () =
+ msg_send![native_window, orderFront: ptr::null_mut::<AnyObject>()];
}
}
}
}
if focus && show {
- native_window.makeKeyAndOrderFront_(nil);
+ let _: () =
+ msg_send![native_window, makeKeyAndOrderFront: ptr::null_mut::<AnyObject>()];
} else if show {
- native_window.orderFront_(nil);
+ let _: () = msg_send![native_window, orderFront: ptr::null_mut::<AnyObject>()];
}
// Set the initial position of the window to the specified origin.
// Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
// the window position might be incorrect if the main screen (the screen that contains the window that has focus)
// is different from the primary screen.
- NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
+ let _: () = msg_send![native_window, setFrameTopLeftPoint: window_rect.origin];
{
let mut window_state = window.0.lock();
window_state.move_traffic_light();
window_state.sheet_parent = sheet_parent;
}
- pool.drain();
-
window
- }
+ })
}
pub fn active_window() -> Option<AnyWindowHandle> {
unsafe {
- let app = NSApplication::sharedApplication(nil);
- let main_window: id = msg_send![app, mainWindow];
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let main_window: *mut AnyObject = msg_send![app, mainWindow];
if main_window.is_null() {
return None;
}
@@ -1332,13 +1308,13 @@ impl MacWindow {
pub fn ordered_windows() -> Vec<AnyWindowHandle> {
unsafe {
- let app = NSApplication::sharedApplication(nil);
- let windows: id = msg_send![app, orderedWindows];
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let windows: *mut AnyObject = msg_send![app, orderedWindows];
let count: NSUInteger = msg_send![windows, count];
let mut window_handles = Vec::new();
for i in 0..count {
- let window: id = msg_send![windows, objectAtIndex:i];
+ let window: *mut AnyObject = msg_send![windows, objectAtIndex:i];
if msg_send![window, isKindOfClass: WINDOW_CLASS] {
let handle = get_window_state(&*window).lock().handle;
window_handles.push(handle);
@@ -1351,19 +1327,19 @@ impl MacWindow {
pub fn get_user_tabbing_preference() -> Option<UserTabbingPreference> {
unsafe {
- let defaults: id = NSUserDefaults::standardUserDefaults();
+ let defaults: *mut AnyObject = msg_send![class!(NSUserDefaults), standardUserDefaults];
let domain = ns_string("NSGlobalDomain");
let key = ns_string("AppleWindowTabbingMode");
- let dict: id = msg_send![defaults, persistentDomainForName: domain];
- let value: id = if !dict.is_null() {
+ let dict: *mut AnyObject = msg_send![defaults, persistentDomainForName: domain];
+ let value: *mut AnyObject = if !dict.is_null() {
msg_send![dict, objectForKey: key]
} else {
- nil
+ ptr::null_mut::<AnyObject>()
};
let value_str = if !value.is_null() {
- CStr::from_ptr(NSString::UTF8String(value)).to_string_lossy()
+ CStr::from_ptr(msg_send![value, UTF8String]).to_string_lossy()
} else {
"".into()
};
@@ -1394,7 +1370,7 @@ impl Drop for MacWindow {
let sheet_parent = this.sheet_parent.take();
this.frame_source.take();
unsafe {
- this.native_window.setDelegate_(nil);
+ let _: () = msg_send![this.native_window, setDelegate: ptr::null_mut::<AnyObject>()];
}
this.input_handler.take();
// A delivery task queued by `report_visibility` may still run after the
@@ -1406,8 +1382,8 @@ impl Drop for MacWindow {
if let Some(parent) = sheet_parent {
let _: () = msg_send![parent, endSheet: window];
}
- window.close();
- window.autorelease();
+ let _: () = msg_send![window, close];
+ let _: *mut AnyObject = msg_send![window, autorelease];
}
})
.detach();
@@ -1449,10 +1425,10 @@ impl PlatformWindow for MacWindow {
this.foreground_executor
.spawn(async move {
if_window_not_closed(closed, || unsafe {
- window.setContentSize_(NSSize {
+ let _: () = msg_send![window, setContentSize: NSSize {
width: size.width.as_f32() as f64,
height: size.height.as_f32() as f64,
- });
+ }];
})
})
.detach();
@@ -1462,8 +1438,8 @@ impl PlatformWindow for MacWindow {
let native_window = self.0.lock().native_window;
extern "C" fn merge_windows_async(context: *mut std::ffi::c_void) {
unsafe {
- let native_window = context as id;
- let _: () = msg_send![native_window, mergeAllWindows:nil];
+ let native_window = context as *mut AnyObject;
+ let _: () = msg_send![native_window, mergeAllWindows:ptr::null_mut::<AnyObject>()];
}
}
@@ -1477,9 +1453,11 @@ impl PlatformWindow for MacWindow {
let native_window = self.0.lock().native_window;
extern "C" fn move_tab_async(context: *mut std::ffi::c_void) {
unsafe {
- let native_window = context as id;
- let _: () = msg_send![native_window, moveTabToNewWindow:nil];
- let _: () = msg_send![native_window, makeKeyAndOrderFront: nil];
+ let native_window = context as *mut AnyObject;
+ let _: () =
+ msg_send![native_window, moveTabToNewWindow:ptr::null_mut::<AnyObject>()];
+ let _: () =
+ msg_send![native_window, makeKeyAndOrderFront: ptr::null_mut::<AnyObject>()];
}
}
@@ -1492,7 +1470,7 @@ impl PlatformWindow for MacWindow {
fn toggle_window_tab_overview(&self) {
let native_window = self.0.lock().native_window;
unsafe {
- let _: () = msg_send![native_window, toggleTabOverview:nil];
+ let _: () = msg_send![native_window, toggleTabOverview:ptr::null_mut::<AnyObject>()];
}
}
@@ -1501,16 +1479,17 @@ impl PlatformWindow for MacWindow {
unsafe {
let allows_automatic_window_tabbing = tabbing_identifier.is_some();
if allows_automatic_window_tabbing {
- let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
+ let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: Bool::YES];
} else {
- let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
+ let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: Bool::NO];
}
if let Some(tabbing_identifier) = tabbing_identifier {
let tabbing_id = ns_string(tabbing_identifier.as_str());
let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
} else {
- let _: () = msg_send![native_window, setTabbingIdentifier:nil];
+ let _: () =
+ msg_send![native_window, setTabbingIdentifier:ptr::null_mut::<AnyObject>()];
}
}
}
@@ -1528,31 +1507,33 @@ impl PlatformWindow for MacWindow {
// archived bytes are copied into an owned `Vec` before the objects we allocated are
// released, so no pointer into Objective-C memory escapes this block.
unsafe {
- let archiver: id = msg_send![class!(NSKeyedArchiver), alloc];
- let archiver: id = msg_send![archiver, initRequiringSecureCoding: YES];
+ let archiver: *mut AnyObject = msg_send![class!(NSKeyedArchiver), alloc];
+ let archiver: *mut AnyObject =
+ msg_send![archiver, initRequiringSecureCoding: Bool::YES];
if archiver.is_null() {
log::warn!("failed to create an archiver for the native window state");
return None;
}
- let delegate: id = msg_send![WINDOW_STATE_ARCHIVER_DELEGATE_CLASS, new];
+ let delegate: *mut AnyObject = msg_send![WINDOW_STATE_ARCHIVER_DELEGATE_CLASS, new];
let _: () = msg_send![archiver, setDelegate: delegate];
let _: () = msg_send![native_window, encodeRestorableStateWithCoder: archiver];
let _: () = msg_send![archiver, finishEncoding];
// The archiver holds a weak reference to its delegate; clear it before the delegate
// is released below.
- let _: () = msg_send![archiver, setDelegate: nil];
+ let _: () = msg_send![archiver, setDelegate: ptr::null_mut::<AnyObject>()];
- let data: id = msg_send![archiver, encodedData];
- let bytes = if data.is_null() {
+ let data: *mut AnyObject = msg_send![archiver, encodedData];
+ let bytes: *const c_void = if data.is_null() {
ptr::null()
} else {
- data.bytes() as *const u8
+ msg_send![data, bytes]
};
let state = if bytes.is_null() {
log::warn!("the archiver produced no data for the native window state");
None
} else {
- Some(std::slice::from_raw_parts(bytes, data.length() as usize).to_vec())
+ let length: NSUInteger = msg_send![data, length];
+ Some(std::slice::from_raw_parts(bytes.cast::<u8>(), length).to_vec())
};
let _: () = msg_send![delegate, release];
@@ -1571,11 +1552,11 @@ impl PlatformWindow for MacWindow {
// signatures, and the `NSData` only borrows `state` for the duration of this synchronous
// call (it is consumed before `state` could be freed).
unsafe {
- let data = NSData::dataWithBytes_length_(
- nil,
- state.as_ptr() as *const c_void,
- state.len() as u64,
- );
+ let data: *mut AnyObject = msg_send![
+ class!(NSData),
+ dataWithBytes: state.as_ptr().cast::<c_void>(),
+ length: state.len()
+ ];
if data.is_null() {
log::warn!(
"failed to wrap {} bytes of native window state",
@@ -1588,24 +1569,30 @@ impl PlatformWindow for MacWindow {
// the window is restored to its original Space. On macOS 15+ that default is broken
// (FB15644170), and the `_windowRestorationOptions` override on our unarchiver subclass
// handles it instead.
- if !is_macos_version_at_least(NSOperatingSystemVersion::new(15, 0, 0)) {
+ if !is_macos_version_at_least(NSOperatingSystemVersion {
+ majorVersion: 15,
+ minorVersion: 0,
+ patchVersion: 0,
+ }) {
RESTORES_WORKSPACE_AT_LAUNCH_DEFAULT.call_once(|| {
- let defaults: id = NSUserDefaults::standardUserDefaults();
+ let defaults: *mut AnyObject =
+ msg_send![class!(NSUserDefaults), standardUserDefaults];
let key = ns_string("NSWindowRestoresWorkspaceAtLaunch");
- let yes_value: id = msg_send![class!(NSNumber), numberWithBool: YES];
- let dict: id = msg_send![
+ let yes_value: *mut AnyObject =
+ msg_send![class!(NSNumber), numberWithBool: Bool::YES];
+ let dict: *mut AnyObject = msg_send![
class!(NSDictionary),
- dictionaryWithObject: yes_value
+ dictionaryWithObject: yes_value,
forKey: key
];
let _: () = msg_send![defaults, registerDefaults: dict];
});
}
- let unarchiver: id = msg_send![WINDOW_STATE_UNARCHIVER_CLASS, alloc];
- let mut error: id = nil;
- let unarchiver: id =
- msg_send![unarchiver, initForReadingFromData: data error: &mut error];
+ let unarchiver: *mut AnyObject = msg_send![WINDOW_STATE_UNARCHIVER_CLASS, alloc];
+ let mut error: *mut AnyObject = ptr::null_mut::<AnyObject>();
+ let unarchiver: *mut AnyObject =
+ msg_send![unarchiver, initForReadingFromData: data, error: &mut error];
if unarchiver.is_null() {
log::warn!(
"failed to unarchive the native window state: {}",
@@ -1614,7 +1601,7 @@ impl PlatformWindow for MacWindow {
return;
}
let _: () = msg_send![native_window, restoreStateWithCoder: unarchiver];
- let error: id = msg_send![unarchiver, error];
+ let error: *mut AnyObject = msg_send![unarchiver, error];
if !error.is_null() {
log::warn!(
"failed to restore the native window state: {}",
@@ -1637,34 +1624,24 @@ impl PlatformWindow for MacWindow {
fn appearance(&self) -> WindowAppearance {
unsafe {
- let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
- crate::window_appearance::window_appearance_from_native(appearance)
+ let appearance: Option<Retained<NSAppearance>> =
+ msg_send![self.0.lock().native_window, effectiveAppearance];
+ crate::window_appearance::window_appearance_from_native(appearance.as_deref())
}
}
fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
- unsafe {
- let screen = self.0.lock().native_window.screen();
- if screen.is_null() {
- return None;
- }
- let device_description: id = msg_send![screen, deviceDescription];
- let screen_number: id =
- NSDictionary::valueForKey_(device_description, ns_string("NSScreenNumber"));
-
- let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
-
- Some(Rc::new(MacDisplay(screen_number)))
- }
+ let screen: *mut AnyObject = unsafe { msg_send![self.0.lock().native_window, screen] };
+ let display_id = display_id_for_screen(screen)?;
+ Some(Rc::new(MacDisplay(display_id)))
}
fn mouse_position(&self) -> Point<Pixels> {
- let position = unsafe {
- self.0
- .lock()
- .native_window
- .mouseLocationOutsideOfEventStream()
- };
+ let position = self
+ .0
+ .lock()
+ .native_window()
+ .mouseLocationOutsideOfEventStream();
convert_mouse_position(position, self.content_size().height)
}
@@ -1672,11 +1649,11 @@ impl PlatformWindow for MacWindow {
unsafe {
let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
- let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
- let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
- let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
- let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
- let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
+ let control = modifiers.contains(NSEventModifierFlags::Control);
+ let alt = modifiers.contains(NSEventModifierFlags::Option);
+ let shift = modifiers.contains(NSEventModifierFlags::Shift);
+ let command = modifiers.contains(NSEventModifierFlags::Command);
+ let function = modifiers.contains(NSEventModifierFlags::Function);
Modifiers {
control,
@@ -1693,7 +1670,7 @@ impl PlatformWindow for MacWindow {
let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
Capslock {
- on: modifiers.contains(NSEventModifierFlags::NSAlphaShiftKeyMask),
+ on: modifiers.contains(NSEventModifierFlags::CapsLock),
}
}
}
@@ -1713,8 +1690,6 @@ impl PlatformWindow for MacWindow {
detail: Option<&str>,
answers: &[PromptButton],
) -> Option<oneshot::Receiver<usize>> {
- use objc2_foundation::{NSInteger, NSString};
-
// NSAlert's first button keeps Return and Cancel keeps Escape, but the keyboard
// focus (and therefore Space) defaults to Cancel, leaving the middle button of
// prompts like "Save / Don't Save / Cancel" unreachable from the keyboard. Move
@@ -1741,7 +1716,7 @@ impl PlatformWindow for MacWindow {
alert.setInformativeText(detail_text.as_ref());
}
- let mut initial_focus_button: Option<Retained<Objc2NSButton>> = None;
+ let mut initial_focus_button: Option<Retained<NSButton>> = None;
for (ix, answer) in answers.iter().enumerate() {
let title = NSString::from_str(answer.label());
let button = alert.addButtonWithTitle(&title);
@@ -1777,10 +1752,7 @@ impl PlatformWindow for MacWindow {
executor
.spawn(async move {
if !closed.load(Ordering::Acquire) {
- // SAFETY: `native_window` is an Objective-C `NSWindow` pointer
- // owned by the platform window; bridge it into objc2.
- let sheet_window: &Objc2NSWindow =
- unsafe { &*(native_window as *const Objc2NSWindow) };
+ let sheet_window: &NSWindow = unsafe { &*(native_window as *const NSWindow) };
alert.beginSheetModalForWindow_completionHandler(sheet_window, Some(&block));
}
@@ -1799,9 +1771,9 @@ impl PlatformWindow for MacWindow {
executor
.spawn(async move {
if !closed.load(Ordering::Acquire) {
- let window = unsafe { &*window.cast::<Objc2NSWindow>() };
+ let window = unsafe { &*window.cast::<NSWindow>() };
if !window.isVisible() {
- let view = unsafe { &*view.cast::<Objc2NSView>() };
+ let view = unsafe { &*view.cast::<NSView>() };
view.setNeedsDisplay(true);
}
window.makeKeyAndOrderFront(None);
@@ -1819,15 +1791,15 @@ impl PlatformWindow for MacWindow {
executor
.spawn(async move {
unsafe {
- let app = NSApplication::sharedApplication(nil);
- app.requestUserAttention_(NSRequestUserAttentionType::NSInformationalRequest);
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let _: NSInteger = msg_send![app, requestUserAttention: NSRequestUserAttentionType::InformationalRequest];
}
})
.detach();
}
fn is_active(&self) -> bool {
- unsafe { self.0.lock().native_window.isKeyWindow() == YES }
+ self.0.lock().native_window().isKeyWindow()
}
fn visibility(&self) -> WindowVisibility {
@@ -1841,10 +1813,10 @@ impl PlatformWindow for MacWindow {
fn set_title(&mut self, title: &str) {
unsafe {
- let app = NSApplication::sharedApplication(nil);
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let window = self.0.lock().native_window;
let title = ns_string(title);
- let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
+ let _: () = msg_send![app, changeWindowsItem:window, title:title, filename:false];
let _: () = msg_send![window, setTitle: title];
self.0.lock().move_traffic_light();
}
@@ -1852,7 +1824,7 @@ impl PlatformWindow for MacWindow {
fn get_title(&self) -> String {
unsafe {
- let title: id = msg_send![self.0.lock().native_window, title];
+ let title: *mut AnyObject = msg_send![self.0.lock().native_window, title];
if title.is_null() {
"".to_string()
} else {
@@ -1871,34 +1843,35 @@ impl PlatformWindow for MacWindow {
this.renderer.update_transparency(!opaque);
unsafe {
- this.native_window.setOpaque_(opaque as BOOL);
+ let _: () = msg_send![this.native_window, setOpaque: opaque.to_objc()];
let background_color = if opaque {
- NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
+ NSColor::colorWithSRGBRed_green_blue_alpha(0f64, 0f64, 0f64, 1f64)
} else {
// Not using `+[NSColor clearColor]` to avoid broken shadow.
- NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 0.0001)
+ NSColor::colorWithSRGBRed_green_blue_alpha(0f64, 0f64, 0f64, 0.0001)
};
- this.native_window.setBackgroundColor_(background_color);
+ let _: () = msg_send![this.native_window, setBackgroundColor: &*background_color];
if background_appearance != WindowBackgroundAppearance::Blurred {
if let Some(blur_view) = this.blurred_view {
- NSView::removeFromSuperview(blur_view);
+ let _: () = msg_send![blur_view, removeFromSuperview];
this.blurred_view = None;
}
} else if this.blurred_view.is_none() {
- let content_view = this.native_window.contentView();
- let frame = NSView::bounds(content_view);
- let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];
- blur_view = NSView::initWithFrame_(blur_view, frame);
- blur_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
+ let content_view: *mut AnyObject = msg_send![this.native_window, contentView];
+ let frame: NSRect = msg_send![content_view, bounds];
+ let blur_view: *mut AnyObject = msg_send![BLURRED_VIEW_CLASS, alloc];
+ let blur_view: *mut AnyObject = msg_send![blur_view, initWithFrame: frame];
+ let _: () = msg_send![blur_view, setAutoresizingMask: NSAutoresizingMaskOptions::ViewWidthSizable
+ | NSAutoresizingMaskOptions::ViewHeightSizable];
let _: () = msg_send![
content_view,
- addSubview: blur_view
- positioned: NSWindowOrderingMode::NSWindowBelow
- relativeTo: nil
+ addSubview: blur_view,
+ positioned: NSWindowOrderingMode::Below,
+ relativeTo: ptr::null_mut::<AnyObject>()
];
- this.blurred_view = Some(blur_view.autorelease());
+ this.blurred_view = Some(msg_send![blur_view, autorelease]);
}
}
}
@@ -1914,7 +1887,7 @@ impl PlatformWindow for MacWindow {
fn set_edited(&mut self, edited: bool) {
unsafe {
let window = self.0.lock().native_window;
- msg_send![window, setDocumentEdited: edited as BOOL]
+ msg_send![window, setDocumentEdited: edited.to_objc()]
}
// Changing the document edited state resets the traffic light position,
@@ -1940,7 +1913,7 @@ impl PlatformWindow for MacWindow {
this.foreground_executor
.spawn(async move {
unsafe {
- let app = NSApplication::sharedApplication(nil);
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let _: () = msg_send![app, orderFrontCharacterPalette: window];
}
})
@@ -1950,7 +1923,7 @@ impl PlatformWindow for MacWindow {
fn minimize(&self) {
let window = self.0.lock().native_window;
unsafe {
- window.miniaturize_(nil);
+ let _: () = msg_send![window, miniaturize: ptr::null_mut::<AnyObject>()];
}
}
@@ -1961,7 +1934,7 @@ impl PlatformWindow for MacWindow {
this.foreground_executor
.spawn(async move {
if_window_not_closed(closed, || unsafe {
- window.zoom_(nil);
+ let _: () = msg_send![window, zoom: ptr::null_mut::<AnyObject>()];
})
})
.detach();
@@ -1974,7 +1947,7 @@ impl PlatformWindow for MacWindow {
this.foreground_executor
.spawn(async move {
if_window_not_closed(closed, || unsafe {
- window.toggleFullScreen_(nil);
+ let _: () = msg_send![window, toggleFullScreen: ptr::null_mut::<AnyObject>()];
})
})
.detach();
@@ -1993,7 +1966,7 @@ impl PlatformWindow for MacWindow {
let mut lock = state.lock();
(
lock.native_window,
- lock.native_view.as_ptr() as id,
+ lock.native_view.as_ptr(),
lock.toggle_simple_fullscreen(),
)
};
@@ -2014,9 +1987,9 @@ impl PlatformWindow for MacWindow {
let window = this.native_window;
unsafe {
- window
+ (&*window.cast::<NSWindow>())
.styleMask()
- .contains(NSWindowStyleMask::NSFullScreenWindowMask)
+ .contains(NSWindowStyleMask::FullScreen)
}
}
@@ -2069,7 +2042,7 @@ impl PlatformWindow for MacWindow {
fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
unsafe {
- let windows: id = msg_send![self.0.lock().native_window, tabbedWindows];
+ let windows: *mut AnyObject = msg_send![self.0.lock().native_window, tabbedWindows];
if windows.is_null() {
return None;
}
@@ -2077,10 +2050,10 @@ impl PlatformWindow for MacWindow {
let count: NSUInteger = msg_send![windows, count];
let mut result = Vec::new();
for i in 0..count {
- let window: id = msg_send![windows, objectAtIndex:i];
+ let window: *mut AnyObject = msg_send![windows, objectAtIndex:i];
if msg_send![window, isKindOfClass: WINDOW_CLASS] {
let handle = get_window_state(&*window).lock().handle;
- let title: id = msg_send![window, title];
+ let title: *mut AnyObject = msg_send![window, title];
let title = SharedString::from(title.to_str().to_string());
result.push(SystemWindowTab::new(title, handle));
@@ -2093,12 +2066,12 @@ impl PlatformWindow for MacWindow {
fn tab_bar_visible(&self) -> bool {
unsafe {
- let tab_group: id = msg_send![self.0.lock().native_window, tabGroup];
+ let tab_group: *mut AnyObject = msg_send![self.0.lock().native_window, tabGroup];
if tab_group.is_null() {
false
} else {
- let tab_bar_visible: BOOL = msg_send![tab_group, isTabBarVisible];
- tab_bar_visible == YES
+ let tab_bar_visible: Bool = msg_send![tab_group, isTabBarVisible];
+ tab_bar_visible == Bool::YES
}
}
}
@@ -2141,7 +2114,7 @@ impl PlatformWindow for MacWindow {
executor
.spawn(async move {
unsafe {
- let input_context: id =
+ let input_context: *mut AnyObject =
msg_send![class!(NSTextInputContext), currentInputContext];
if input_context.is_null() {
return;
@@ -2163,19 +2136,19 @@ impl PlatformWindow for MacWindow {
.spawn(async move {
if_window_not_closed(closed, || {
unsafe {
- let defaults: id = NSUserDefaults::standardUserDefaults();
+ let defaults: *mut AnyObject = msg_send![class!(NSUserDefaults), standardUserDefaults];
let domain = ns_string("NSGlobalDomain");
let key = ns_string("AppleActionOnDoubleClick");
- let dict: id = msg_send![defaults, persistentDomainForName: domain];
- let action: id = if !dict.is_null() {
+ let dict: *mut AnyObject = msg_send![defaults, persistentDomainForName: domain];
+ let action: *mut AnyObject = if !dict.is_null() {
msg_send![dict, objectForKey: key]
} else {
- nil
+ ptr::null_mut::<AnyObject>()
};
let action_str = if !action.is_null() {
- CStr::from_ptr(NSString::UTF8String(action)).to_string_lossy()
+ CStr::from_ptr(msg_send![action, UTF8String]).to_string_lossy()
} else {
"".into()
};
@@ -2186,30 +2159,30 @@ impl PlatformWindow for MacWindow {
}
"Minimize" => {
if is_minimizable {
- window.miniaturize_(nil);
+ let _: () = msg_send![window, miniaturize: ptr::null_mut::<AnyObject>()];
}
}
"Maximize" => {
if is_resizable {
- window.zoom_(nil);
+ let _: () = msg_send![window, zoom: ptr::null_mut::<AnyObject>()];
}
}
"Fill" => {
if is_resizable {
// Unlike `zoom:`, AppKit's private Fill action honors the system's
// "Tiled windows have margins" setting.
- let responds_to_zoom_fill: BOOL =
+ let responds_to_zoom_fill: Bool =
msg_send![window, respondsToSelector: sel!(_zoomFill:)];
- if responds_to_zoom_fill == YES {
- let _: () = msg_send![window, _zoomFill: nil];
+ if responds_to_zoom_fill == Bool::YES {
+ let _: () = msg_send![window, _zoomFill: ptr::null_mut::<AnyObject>()];
} else {
- window.zoom_(nil);
+ let _: () = msg_send![window, zoom: ptr::null_mut::<AnyObject>()];
}
}
}
_ => {
if is_resizable {
- window.zoom_(nil);
+ let _: () = msg_send![window, zoom: ptr::null_mut::<AnyObject>()];
}
}
}
@@ -2227,8 +2200,8 @@ impl PlatformWindow for MacWindow {
let window = this.native_window;
unsafe {
- let app = NSApplication::sharedApplication(nil);
- let event: id = msg_send![app, currentEvent];
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let event: *mut AnyObject = msg_send![app, currentEvent];
let _: () = msg_send![window, performWindowDragWithEvent: event];
}
}
@@ -2238,8 +2211,6 @@ impl PlatformWindow for MacWindow {
}
fn start_external_drag(&self, payload: &ExternalDragPayload) -> bool {
- use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString};
-
let ExternalDragPayload::Files(paths) = payload;
if paths.entries().is_empty() {
log::warn!("start_external_drag declined: no paths");
@@ -2264,13 +2235,13 @@ impl PlatformWindow for MacWindow {
// native view/window are retained by MacWindowState, copied out under a short lock above,
// and all pointers passed to Objective-C remain valid for their respective calls.
unsafe {
- let event: id = Retained::as_ptr(&last_left_mouse_down_event)
+ let event: *mut AnyObject = Retained::as_ptr(&last_left_mouse_down_event)
.cast_mut()
.cast();
- let dragging_items: id = msg_send![class!(NSMutableArray), array];
+ let dragging_items: *mut AnyObject = msg_send![class!(NSMutableArray), array];
// AppKit keeps this frame's distance from the event's location as the drag image's
// offset from the cursor, so it has to stay anchored on `event`.
- let location: cocoa::foundation::NSPoint = msg_send![event, locationInWindow];
+ let location: NSPoint = msg_send![event, locationInWindow];
let frame = NSRect::new(
NSPoint::new(location.x - 16., location.y - 16.),
NSSize::new(32., 32.),
@@ -2336,10 +2307,10 @@ impl PlatformWindow for MacWindow {
return false;
}
- let session: id = msg_send![
+ let session: *mut AnyObject = msg_send![
native_view,
- beginDraggingSessionWithItems: dragging_items
- event: event
+ beginDraggingSessionWithItems: dragging_items,
+ event: event,
source: native_window
];
@@ -2437,13 +2408,13 @@ impl rwh::HasDisplayHandle for MacWindow {
}
}
-fn get_scale_factor(native_window: id) -> f32 {
+fn get_scale_factor(native_window: *mut AnyObject) -> f32 {
let factor = unsafe {
- let screen: id = msg_send![native_window, screen];
+ let screen: *mut AnyObject = msg_send![native_window, screen];
if screen.is_null() {
return 2.0;
}
- NSScreen::backingScaleFactor(screen) as f32
+ (&*screen.cast::<NSScreen>()).backingScaleFactor() as f32
};
// We are not certain what triggers this, but it seems that sometimes
@@ -2456,16 +2427,20 @@ fn get_scale_factor(native_window: id) -> f32 {
}
/// Returns whether `window` is one of GPUI's managed windows.
-unsafe fn is_gpui_window(window: id) -> bool {
+unsafe fn is_gpui_window(window: *mut AnyObject) -> bool {
unsafe {
msg_send![window, isKindOfClass: WINDOW_CLASS]
|| msg_send![window, isKindOfClass: PANEL_CLASS]
}
}
-unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
+unsafe fn get_window_state(object: &AnyObject) -> Arc<Mutex<MacWindowState>> {
unsafe {
- let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
+ let raw = *object
+ .class()
+ .instance_variable(WINDOW_STATE_IVAR)
+ .expect("GPUI window state ivar")
+ .load::<*mut c_void>(object);
let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
let rc2 = rc1.clone();
mem::forget(rc1);
@@ -2473,32 +2448,36 @@ unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
}
}
-unsafe fn drop_window_state(object: &Object) {
+unsafe fn drop_window_state(object: &AnyObject) {
unsafe {
- let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
+ let raw = *object
+ .class()
+ .instance_variable(WINDOW_STATE_IVAR)
+ .expect("GPUI window state ivar")
+ .load::<*mut c_void>(object);
Arc::from_raw(raw as *mut Mutex<MacWindowState>);
}
}
-extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
- YES
+extern "C" fn yes(_: &AnyObject, _: Sel) -> Bool {
+ Bool::YES
}
-extern "C" fn dealloc_window(this: &Object, _: Sel) {
+extern "C" fn dealloc_window(this: &AnyObject, _: Sel) {
unsafe {
drop_window_state(this);
let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
}
}
-extern "C" fn dealloc_view(this: &Object, _: Sel) {
+extern "C" fn dealloc_view(this: &AnyObject, _: Sel) {
unsafe {
drop_window_state(this);
let _: () = msg_send![super(this, class!(NSView)), dealloc];
}
}
-fn add_mouse_tracking_area(native_view: &Objc2NSView) {
+fn add_mouse_tracking_area(native_view: &NSView) {
let options = NSTrackingAreaOptions::MouseEnteredAndExited
| NSTrackingAreaOptions::MouseMoved
// Track even when another application is active so visible
@@ -2511,7 +2490,7 @@ fn add_mouse_tracking_area(native_view: &Objc2NSView) {
let tracking_area = unsafe {
NSTrackingArea::initWithRect_options_owner_userInfo(
NSTrackingArea::alloc(),
- Objc2NSRect::ZERO,
+ NSRect::ZERO,
options,
Some(native_view),
None,
@@ -2520,7 +2499,7 @@ fn add_mouse_tracking_area(native_view: &Objc2NSView) {
native_view.addTrackingArea(&tracking_area);
}
-extern "C" fn reset_cursor_rects(this: &Object, _: Sel) {
+extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) {
// SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances,
// whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered
// below is a valid NSCursor.
@@ -2530,7 +2509,7 @@ extern "C" fn reset_cursor_rects(this: &Object, _: Sel) {
let window_state = get_window_state(this);
let cursor_style = window_state.lock().cursor_style;
- let cursor: id = match cursor_style {
+ let cursor: *mut AnyObject = match cursor_style {
CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
@@ -2566,20 +2545,24 @@ extern "C" fn reset_cursor_rects(this: &Object, _: Sel) {
CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
};
- let bounds = NSView::bounds(this as *const Object as id);
- let _: () = msg_send![this, addCursorRect: bounds cursor: cursor];
+ let bounds: NSRect = msg_send![this, bounds];
+ let _: () = msg_send![this, addCursorRect: bounds, cursor: cursor];
}
}
-extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
+extern "C" fn handle_key_equivalent(
+ this: &AnyObject,
+ _: Sel,
+ native_event: *mut AnyObject,
+) -> Bool {
handle_key_event(this, native_event, true)
}
-extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
+extern "C" fn handle_key_down(this: &AnyObject, _: Sel, native_event: *mut AnyObject) {
handle_key_event(this, native_event, false);
}
-extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
+extern "C" fn handle_key_up(this: &AnyObject, _: Sel, native_event: *mut AnyObject) {
handle_key_event(this, native_event, false);
}
@@ -2647,23 +2630,27 @@ unsafe fn is_ime_input_source_active() -> bool {
}
}
-extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
+extern "C" fn handle_key_event(
+ this: &AnyObject,
+ native_event: *mut AnyObject,
+ key_equivalent: bool,
+) -> Bool {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
let window_height = lock.content_size().height;
- let event = unsafe { platform_input_from_native(native_event.cast(), Some(window_height)) };
+ let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
let Some(event) = event else {
- return NO;
+ return Bool::NO;
};
- let run_callback = |event: PlatformInput| -> BOOL {
+ let run_callback = |event: PlatformInput| -> Bool {
let mut callback = window_state.as_ref().lock().event_callback.take();
- let handled: BOOL = if let Some(callback) = callback.as_mut() {
- !callback(event).propagate as BOOL
+ let handled: Bool = if let Some(callback) = callback.as_mut() {
+ (!callback(event).propagate).to_objc()
} else {
- NO
+ Bool::NO
};
window_state.as_ref().lock().event_callback = callback;
handled
@@ -2678,7 +2665,7 @@ extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent:
if key_equivalent {
lock.last_key_equivalent = Some(key_down_event.clone());
} else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
- return NO;
+ return Bool::NO;
}
drop(lock);
@@ -2732,15 +2719,19 @@ extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent:
drop(lock);
}
- let handled: BOOL = unsafe {
- let input_context: id = msg_send![this, inputContext];
- msg_send![input_context, handleEvent: native_event]
+ let handled: Bool = unsafe {
+ let input_context: *mut AnyObject = msg_send![this, inputContext];
+ if input_context.is_null() {
+ Bool::NO
+ } else {
+ msg_send![input_context, handleEvent: native_event]
+ }
};
window_state.as_ref().lock().keystroke_for_do_command.take();
if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
- return handled as BOOL;
- } else if handled == YES {
- return YES;
+ return handled.to_objc();
+ } else if handled == Bool::YES {
+ return Bool::YES;
}
let handled = run_callback(PlatformInput::KeyDown(key_down_event));
@@ -2748,8 +2739,8 @@ extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent:
}
let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
- if handled == YES {
- return YES;
+ if handled == Bool::YES {
+ return Bool::YES;
}
if key_down_event.is_held
@@ -2758,24 +2749,28 @@ extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent:
let handled = with_input_handler(this, |input_handler| {
if !input_handler.apple_press_and_hold_enabled() {
input_handler.replace_text_in_range(None, key_char);
- return YES;
+ return Bool::YES;
}
- NO
+ Bool::NO
});
- if handled == Some(YES) {
- return YES;
+ if handled == Some(Bool::YES) {
+ return Bool::YES;
}
}
// Don't send key equivalents to the input handler if there are key modifiers other
// than Function key, or macOS shortcuts like cmd-` will stop working.
if key_equivalent && key_down_event.keystroke.modifiers != Modifiers::function() {
- return NO;
+ return Bool::NO;
}
unsafe {
- let input_context: id = msg_send![this, inputContext];
- msg_send![input_context, handleEvent: native_event]
+ let input_context: *mut AnyObject = msg_send![this, inputContext];
+ if input_context.is_null() {
+ Bool::NO
+ } else {
+ msg_send![input_context, handleEvent: native_event]
+ }
}
}
@@ -2784,29 +2779,28 @@ extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent:
run_callback(event)
}
- _ => NO,
+ _ => Bool::NO,
}
}
-extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
+extern "C" fn handle_view_event(this: &AnyObject, _: Sel, native_event: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let weak_window_state = Arc::downgrade(&window_state);
let mut lock = window_state.as_ref().lock();
let window_height = lock.content_size().height;
- let native_event_type = unsafe { native_event.eventType() };
+ let native_event_type: NSEventType = unsafe { msg_send![native_event, type] };
match native_event_type {
- NSEventType::NSLeftMouseDown => {
+ NSEventType::LeftMouseDown => {
// AppKit owns `native_event` for the callback; retain it so the drag session can still
// be started later, once the pointer leaves the window.
- lock.last_left_mouse_down_event =
- unsafe { Retained::retain(native_event.cast::<Objc2Object>()) };
+ lock.last_left_mouse_down_event = unsafe { Retained::retain(native_event) };
}
- NSEventType::NSLeftMouseUp => {
+ NSEventType::LeftMouseUp => {
lock.last_left_mouse_down_event = None;
}
_ => {}
}
- let event = unsafe { platform_input_from_native(native_event.cast(), Some(window_height)) };
+ let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
if let Some(mut event) = event {
// AppKit unhides the cursor on the next mouse movement; mirror that here.
@@ -2885,8 +2879,10 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
PlatformInput::MouseDown(_) => {
drop(lock);
unsafe {
- let input_context: id = msg_send![this, inputContext];
- msg_send![input_context, handleEvent: native_event]
+ let input_context: *mut AnyObject = msg_send![this, inputContext];
+ if !input_context.is_null() {
+ let _: Bool = msg_send![input_context, handleEvent: native_event];
+ }
}
lock = window_state.as_ref().lock();
}
@@ -2947,12 +2943,10 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
}
fn visibility(state: &MacWindowState) -> WindowVisibility {
- let is_visible = unsafe {
- state
- .native_window
- .occlusionState()
- .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
- };
+ let is_visible = state
+ .native_window()
+ .occlusionState()
+ .contains(NSWindowOcclusionState::Visible);
if is_visible {
WindowVisibility::Visible
} else {
@@ -2992,20 +2986,18 @@ fn report_visibility(window_state: &Arc<Mutex<MacWindowState>>) {
.detach();
}
-extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
+extern "C" fn window_did_change_occlusion_state(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.lock();
- unsafe {
- if lock
- .native_window
- .occlusionState()
- .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
- {
- lock.move_traffic_light();
- lock.start_display_link();
- } else {
- lock.stop_display_link();
- }
+ if lock
+ .native_window()
+ .occlusionState()
+ .contains(NSWindowOcclusionState::Visible)
+ {
+ lock.move_traffic_light();
+ lock.start_display_link();
+ } else {
+ lock.stop_display_link();
}
drop(lock);
// The only visibility source: AppKit posts this for covering, minimizing,
@@ -3013,12 +3005,12 @@ extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
report_visibility(&window_state);
}
-extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
+extern "C" fn window_did_resize(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
window_state.as_ref().lock().move_traffic_light();
}
-extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
+extern "C" fn window_will_enter_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
lock.fullscreen_restore_bounds = lock.bounds();
@@ -3026,39 +3018,47 @@ extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
lock.pre_fullscreen_traffic_light_frames = lock.traffic_light_frames;
lock.restore_traffic_light();
- let min_version = NSOperatingSystemVersion::new(15, 3, 0);
+ let min_version = NSOperatingSystemVersion {
+ majorVersion: 15,
+ minorVersion: 3,
+ patchVersion: 0,
+ };
if is_macos_version_at_least(min_version) {
unsafe {
- lock.native_window.setTitlebarAppearsTransparent_(NO);
+ let _: () = msg_send![lock.native_window, setTitlebarAppearsTransparent: Bool::NO];
}
}
}
-extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
+extern "C" fn window_will_exit_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
lock.is_exiting_fullscreen = true;
- let min_version = NSOperatingSystemVersion::new(15, 3, 0);
+ let min_version = NSOperatingSystemVersion {
+ majorVersion: 15,
+ minorVersion: 3,
+ patchVersion: 0,
+ };
if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
unsafe {
- lock.native_window.setTitlebarAppearsTransparent_(YES);
+ let _: () = msg_send![lock.native_window, setTitlebarAppearsTransparent: Bool::YES];
}
}
lock.move_traffic_light();
}
-extern "C" fn window_did_fail_to_exit_fullscreen(this: &Object, _: Sel, _: id) {
+extern "C" fn window_did_fail_to_exit_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
lock.is_exiting_fullscreen = false;
lock.restore_traffic_light();
}
-extern "C" fn window_did_exit_fullscreen(this: &Object, _: Sel, _: id) {
+extern "C" fn window_did_exit_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
// SAFETY: This method is registered only on GPUI window classes, which initialize
// WINDOW_STATE_IVAR with an Arc<Mutex<MacWindowState>> during window creation.
let window_state = unsafe { get_window_state(this) };
@@ -3071,20 +3071,20 @@ extern "C" fn window_did_exit_fullscreen(this: &Object, _: Sel, _: id) {
}
pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
- unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
+ NSProcessInfo::processInfo().isOperatingSystemAtLeastVersion(version)
}
-fn ns_error_description(error: id) -> String {
+fn ns_error_description(error: *mut AnyObject) -> String {
if error.is_null() {
return "unknown error".to_owned();
}
unsafe {
- let description: id = msg_send![error, localizedDescription];
+ let description: *mut AnyObject = msg_send![error, localizedDescription];
description.to_str().to_owned()
}
}
-extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
+extern "C" fn window_did_move(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
if let Some(mut callback) = lock.moved_callback.take() {
@@ -3100,7 +3100,8 @@ fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
let scale_factor = lock.scale_factor();
let size = lock.content_size();
let drawable_size = size.to_device_pixels(scale_factor);
- if let Some(layer) = lock.renderer.layer() {
+ let layer = lock.renderer.layer_ptr().cast::<AnyObject>();
+ if !layer.is_null() {
unsafe {
let _: () = msg_send![
layer,
@@ -3120,7 +3121,7 @@ fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
};
}
-extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
+extern "C" fn window_did_change_screen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
lock.start_display_link();
@@ -3147,11 +3148,11 @@ fn report_display_change(window_state: &Arc<Mutex<MacWindowState>>) {
.detach();
}
-extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
+extern "C" fn window_did_change_key_status(this: &AnyObject, selector: Sel, _: *mut AnyObject) {
let signal_at = PlatformFrameSignal::capture(scheduler::Instant::now);
let window_state = unsafe { get_window_state(this) };
let lock = window_state.lock();
- let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
+ let is_active = lock.native_window().isKeyWindow();
// AppKit also unhides the cursor on activation changes, so mirror that here.
lock.cursor_visible.store(true, Ordering::Relaxed);
@@ -3234,20 +3235,20 @@ extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id)
.detach();
}
-extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
+extern "C" fn window_should_close(this: &AnyObject, _: Sel, _: *mut AnyObject) -> Bool {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
if let Some(mut callback) = lock.should_close_callback.take() {
drop(lock);
let should_close = callback();
window_state.lock().should_close_callback = Some(callback);
- should_close as BOOL
+ should_close.to_objc()
} else {
- YES
+ Bool::YES
}
}
-extern "C" fn close_window(this: &Object, _: Sel) {
+extern "C" fn close_window(this: &AnyObject, _: Sel) {
unsafe {
let (close_callback, simple_fullscreen_state) = {
let window_state = get_window_state(this);
@@ -3271,18 +3272,18 @@ extern "C" fn close_window(this: &Object, _: Sel) {
}
}
-extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
+extern "C" fn make_backing_layer(this: &AnyObject, _: Sel) -> *mut AnyObject {
let window_state = unsafe { get_window_state(this) };
let window_state = window_state.as_ref().lock();
- window_state.renderer.layer_ptr() as id
+ window_state.renderer.layer_ptr() as *mut AnyObject
}
-extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
+extern "C" fn view_did_change_backing_properties(this: &AnyObject, _: Sel) {
let window_state = unsafe { get_window_state(this) };
update_window_scale_factor(&window_state);
}
-extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
+extern "C" fn set_frame_size(this: &AnyObject, _: Sel, size: NSSize) {
fn convert(value: NSSize) -> Size<Pixels> {
Size {
width: px(value.width as f32),
@@ -3320,7 +3321,7 @@ extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
};
}
-extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
+extern "C" fn display_layer(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let signal_at = PlatformFrameSignal::capture(scheduler::Instant::now);
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.lock();
@@ -3342,7 +3343,7 @@ extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
}
extern "C" fn step(view: *mut c_void) {
- let view = view as id;
+ let view = view as *mut AnyObject;
let window_state = unsafe { get_window_state(&*view) };
let mut lock = window_state.lock();
@@ -3365,25 +3366,25 @@ extern "C" fn step(view: *mut c_void) {
}
}
-extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
+extern "C" fn valid_attributes_for_marked_text(_: &AnyObject, _: Sel) -> *mut AnyObject {
unsafe { msg_send![class!(NSArray), array] }
}
-extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
+extern "C" fn has_marked_text(this: &AnyObject, _: Sel) -> Bool {
let has_marked_text_result =
with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
- has_marked_text_result.is_some() as BOOL
+ has_marked_text_result.is_some().to_objc()
}
-extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
+extern "C" fn marked_range(this: &AnyObject, _: Sel) -> NSRange {
let marked_range_result =
with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
marked_range_result.map_or(NSRange::invalid(), |range| range.into())
}
-extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
+extern "C" fn selected_range(this: &AnyObject, _: Sel) -> NSRange {
let selected_range_result = with_input_handler(this, |input_handler| {
input_handler.selected_text_range(false)
})
@@ -3393,10 +3394,10 @@ extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
}
extern "C" fn first_rect_for_character_range(
- this: &Object,
+ this: &AnyObject,
_: Sel,
range: NSRange,
- _: id,
+ _: *mut NSRange,
) -> NSRect {
let frame = get_frame(this);
with_input_handler(this, |input_handler| {
@@ -3422,25 +3423,29 @@ extern "C" fn first_rect_for_character_range(
)
}
-fn get_frame(this: &Object) -> NSRect {
+fn get_frame(this: &AnyObject) -> NSRect {
unsafe {
let state = get_window_state(this);
let lock = state.lock();
- let mut frame = NSWindow::frame(lock.native_window);
- let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
+ let mut frame = lock.native_window().frame();
+ let content_layout_rect: NSRect = msg_send![lock.native_window, contentLayoutRect];
let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
- if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
+ if !style_mask.contains(NSWindowStyleMask::FullSizeContentView) {
frame.origin.y -= frame.size.height - content_layout_rect.size.height;
}
frame
}
}
-extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
+extern "C" fn insert_text(
+ this: &AnyObject,
+ _: Sel,
+ text: *mut AnyObject,
+ replacement_range: NSRange,
+) {
unsafe {
- let is_attributed_string: BOOL =
- msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
- let text: id = if is_attributed_string == YES {
+ let is_attributed_string: Bool = msg_send![text, isKindOfClass: class!(NSAttributedString)];
+ let text: *mut AnyObject = if is_attributed_string == Bool::YES {
msg_send![text, string]
} else {
text
@@ -3455,16 +3460,15 @@ extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NS
}
extern "C" fn set_marked_text(
- this: &Object,
+ this: &AnyObject,
_: Sel,
- text: id,
+ text: *mut AnyObject,
selected_range: NSRange,
replacement_range: NSRange,
) {
unsafe {
- let is_attributed_string: BOOL =
- msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
- let text: id = if is_attributed_string == YES {
+ let is_attributed_string: Bool = msg_send![text, isKindOfClass: class!(NSAttributedString)];
+ let text: *mut AnyObject = if is_attributed_string == Bool::YES {
msg_send![text, string]
} else {
text
@@ -3477,16 +3481,16 @@ extern "C" fn set_marked_text(
});
}
}
-extern "C" fn unmark_text(this: &Object, _: Sel) {
+extern "C" fn unmark_text(this: &AnyObject, _: Sel) {
with_input_handler(this, |input_handler| input_handler.unmark_text());
}
extern "C" fn attributed_substring_for_proposed_range(
- this: &Object,
+ this: &AnyObject,
_: Sel,
range: NSRange,
- actual_range: *mut c_void,
-) -> id {
+ actual_range: *mut NSRange,
+) -> *mut AnyObject {
with_input_handler(this, |input_handler| {
let range = range.to_range()?;
if range.is_empty() {
@@ -3498,21 +3502,22 @@ extern "C" fn attributed_substring_for_proposed_range(
if let Some(adjusted) = adjusted
&& adjusted != range
{
- unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
+ unsafe { actual_range.write(NSRange::from(adjusted)) };
}
unsafe {
- let string: id = msg_send![class!(NSAttributedString), alloc];
- let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
+ let string: *mut AnyObject = msg_send![class!(NSAttributedString), alloc];
+ let string: *mut AnyObject =
+ msg_send![string, initWithString: ns_string(&selected_text)];
Some(string)
}
})
.flatten()
- .unwrap_or(nil)
+ .unwrap_or(ptr::null_mut::<AnyObject>())
}
// We ignore which selector it asks us to do because the user may have
// bound the shortcut to something else.
-extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
+extern "C" fn do_command_by_selector(this: &AnyObject, _: Sel, _: Sel) {
let state = unsafe { get_window_state(this) };
let mut lock = state.as_ref().lock();
let keystroke = lock.keystroke_for_do_command.take();
@@ -3531,7 +3536,7 @@ extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
state.as_ref().lock().event_callback = event_callback;
}
-extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
+extern "C" fn view_did_change_effective_appearance(this: &AnyObject, _: Sel) {
unsafe {
let state = get_window_state(this);
let appearance_changed_callback = {
@@ -3550,11 +3555,11 @@ extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
}
}
-extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
+extern "C" fn accepts_first_mouse(this: &AnyObject, _: Sel, _: *mut AnyObject) -> Bool {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
lock.first_mouse = true;
- YES
+ Bool::YES
}
// Reports which region of the view AppKit should treat as app-owned titlebar content
@@ -3565,7 +3570,7 @@ extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
// Otherwise we return an empty rect so AppKit's native titlebar dragging keeps working.
// This is independent of `NSWindow.isMovable`, so the Window-menu tiling items stay
// enabled regardless.
-extern "C" fn opaque_rect_for_window_move_when_in_titlebar(this: &Object, _: Sel) -> NSRect {
+extern "C" fn opaque_rect_for_window_move_when_in_titlebar(this: &AnyObject, _: Sel) -> NSRect {
let zero_rect = NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.));
let window_state = unsafe { get_window_state(this) };
let app_owns_titlebar_drag = window_state.as_ref().lock().app_owns_titlebar_drag;
@@ -3576,17 +3581,16 @@ extern "C" fn opaque_rect_for_window_move_when_in_titlebar(this: &Object, _: Sel
}
}
-extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
+extern "C" fn character_index_for_point(this: &AnyObject, _: Sel, position: NSPoint) -> NSUInteger {
let position = screen_point_to_gpui_point(this, position);
with_input_handler(this, |input_handler| {
input_handler.character_index_for_point(position)
})
.flatten()
- .map(|index| index as u64)
- .unwrap_or(NSNotFound as u64)
+ .unwrap_or(NSNotFound as NSUInteger)
}
-fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
+fn screen_point_to_gpui_point(this: &AnyObject, position: NSPoint) -> Point<Pixels> {
let frame = get_frame(this);
let window_x = position.x - frame.origin.x;
let window_y = frame.size.height - (position.y - frame.origin.y);
@@ -3594,12 +3598,16 @@ fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels>
point(px(window_x as f32), px(window_y as f32))
}
-fn is_drag_from_this_window(this: &Object, dragging_info: id) -> bool {
- let source: id = unsafe { msg_send![dragging_info, draggingSource] };
- std::ptr::eq(source as *const Object, this as *const Object)
+fn is_drag_from_this_window(this: &AnyObject, dragging_info: *mut AnyObject) -> bool {
+ let source: *mut AnyObject = unsafe { msg_send![dragging_info, draggingSource] };
+ std::ptr::eq(source as *const AnyObject, this as *const AnyObject)
}
-extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
+extern "C" fn dragging_entered(
+ this: &AnyObject,
+ _: Sel,
+ dragging_info: *mut AnyObject,
+) -> NSDragOperation {
let is_source_window = is_drag_from_this_window(this, dragging_info);
let window_state = unsafe { get_window_state(this) };
let position = drag_event_position(&window_state, dragging_info);
@@ -3608,49 +3616,63 @@ extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDr
&& send_file_drop_event(window_state, event)
{
if is_source_window {
- return NSDragOperationMove;
+ return NSDragOperation::Move;
}
- return NSDragOperationCopy;
+ return NSDragOperation::Copy;
}
- NSDragOperationNone
+ NSDragOperation::None
}
-extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
+extern "C" fn dragging_updated(
+ this: &AnyObject,
+ _: Sel,
+ dragging_info: *mut AnyObject,
+) -> NSDragOperation {
let is_source_window = is_drag_from_this_window(this, dragging_info);
let window_state = unsafe { get_window_state(this) };
let position = drag_event_position(&window_state, dragging_info);
if send_file_drop_event(window_state, FileDropEvent::Pending { position }) {
if is_source_window {
- NSDragOperationMove
+ NSDragOperation::Move
} else {
- NSDragOperationCopy
+ NSDragOperation::Copy
}
} else {
- NSDragOperationNone
+ NSDragOperation::None
}
}
-extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
+extern "C" fn dragging_exited(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
send_file_drop_event(window_state, FileDropEvent::Exited);
}
-extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
+extern "C" fn perform_drag_operation(
+ this: &AnyObject,
+ _: Sel,
+ dragging_info: *mut AnyObject,
+) -> Bool {
let window_state = unsafe { get_window_state(this) };
let position = drag_event_position(&window_state, dragging_info);
send_file_drop_event(window_state, FileDropEvent::Submit { position }).to_objc()
}
-fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
+fn external_paths_from_event(dragging_info: *mut AnyObject) -> Option<ExternalPaths> {
let mut paths = SmallVec::new();
- let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
- let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
- if filenames == nil {
+ let pasteboard: *mut AnyObject = unsafe { msg_send![dragging_info, draggingPasteboard] };
+ if pasteboard.is_null() {
return None;
}
- for file in unsafe { filenames.iter() } {
+ #[expect(
+ deprecated,
+ reason = "File-drop decoding expects a property-list array of paths; replacing NSFilenamesPboardType requires migrating both registration and decoding to file URLs"
+ )]
+ let filenames: *mut NSArray<NSString> =
+ unsafe { msg_send![pasteboard, propertyListForType: NSFilenamesPboardType] };
+ let filenames = unsafe { filenames.as_ref() }?;
+ for file in filenames {
let path = unsafe {
- let f = NSString::UTF8String(file);
+ let f = file.UTF8String();
CStr::from_ptr(f).to_string_lossy().into_owned()
};
paths.push(PathBuf::from(path))
@@ -3658,38 +3680,38 @@ fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths
Some(ExternalPaths(paths))
}
-extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
+extern "C" fn conclude_drag_operation(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
send_file_drop_event(window_state, FileDropEvent::Exited);
}
extern "C" fn dragging_session_source_operation_mask(
- _: &Object,
+ _: &AnyObject,
_: Sel,
- _: id,
- context: NSInteger,
+ _: *mut AnyObject,
+ context: NSDraggingContext,
) -> NSDragOperation {
let operation = match context {
- NSDRAGGING_CONTEXT_OUTSIDE_APPLICATION => NSDragOperationCopy,
- NSDRAGGING_CONTEXT_WITHIN_APPLICATION => NSDragOperationCopy | NSDragOperationMove,
- _ => NSDragOperationCopy | NSDragOperationMove,
+ NSDraggingContext::OutsideApplication => NSDragOperation::Copy,
+ NSDraggingContext::WithinApplication => NSDragOperation::Copy | NSDragOperation::Move,
+ _ => NSDragOperation::Copy | NSDragOperation::Move,
};
log::debug!(
"dragging_session_source_operation_mask: context={}, operation={}",
- context,
- operation
+ context.0,
+ operation.bits()
);
operation
}
extern "C" fn dragging_session_ended(
- this: &Object,
+ this: &AnyObject,
_: Sel,
- _: id,
+ _: *mut AnyObject,
_: NSPoint,
operation: NSDragOperation,
) {
- log::debug!("dragging_session_ended operation={operation}");
+ log::debug!("dragging_session_ended operation={}", operation.bits());
// SAFETY: AppKit invokes this selector on the GPUIWindow instance registered in build_classes,
// which always has WINDOW_STATE_IVAR initialized to the owning MacWindowState.
let window_state = unsafe { get_window_state(this) };
@@ -3770,12 +3792,15 @@ fn send_file_drop_event(
}
}
-fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
+fn drag_event_position(
+ window_state: &Mutex<MacWindowState>,
+ dragging_info: *mut AnyObject,
+) -> Point<Pixels> {
let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
convert_mouse_position(drag_location, window_state.lock().content_size().height)
}
-fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
+fn with_input_handler<F, R>(window: &AnyObject, f: F) -> Option<R>
where
F: FnOnce(&mut PlatformInputHandler) -> R,
{
@@ -3791,69 +3816,82 @@ where
}
}
-fn display_id_for_screen(screen: id) -> Option<CGDirectDisplayID> {
+fn display_id_for_screen(screen: *mut AnyObject) -> Option<CGDirectDisplayID> {
if screen.is_null() {
return None;
}
unsafe {
- let device_description = NSScreen::deviceDescription(screen);
- let screen_number_key: id = ns_string("NSScreenNumber");
- let screen_number = device_description.objectForKey_(screen_number_key);
+ let device_description: *mut AnyObject = msg_send![screen, deviceDescription];
+ if device_description.is_null() {
+ return None;
+ }
+ let screen_number_key: *mut AnyObject = ns_string("NSScreenNumber");
+ let screen_number: *mut AnyObject =
+ msg_send![device_description, objectForKey: screen_number_key];
+ if screen_number.is_null() {
+ return None;
+ }
let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
Some(screen_number as CGDirectDisplayID)
}
}
-extern "C" fn blurred_view_init_with_frame(this: &Object, _: Sel, frame: NSRect) -> id {
+extern "C" fn blurred_view_init_with_frame(
+ this: &AnyObject,
+ _: Sel,
+ frame: NSRect,
+) -> *mut AnyObject {
unsafe {
- let view = msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
+ let view: *mut AnyObject =
+ msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
// A window-background material, whose tint and extra saturation
// `blurred_view_update_layer` strips, leaving only the blur. `Selection`, used before,
// has no `CABackdropLayer` on macOS 27, so nothing behind the window was blurred. (Setting
// a material also avoids the deprecated default, `AppearanceBased`.)
- NSVisualEffectView::setMaterial_(view, NSVisualEffectMaterial::UnderWindowBackground);
+ let _: () = msg_send![view, setMaterial: NSVisualEffectMaterial::UnderWindowBackground];
// The default, but blurring what's behind the window is this view's whole purpose.
- NSVisualEffectView::setBlendingMode_(view, NSVisualEffectBlendingMode::BehindWindow);
- NSVisualEffectView::setState_(view, NSVisualEffectState::Active);
+ let _: () = msg_send![view, setBlendingMode: NSVisualEffectBlendingMode::BehindWindow];
+ let _: () = msg_send![view, setState: NSVisualEffectState::Active];
view
}
}
-extern "C" fn blurred_view_update_layer(this: &Object, _: Sel) {
+extern "C" fn blurred_view_update_layer(this: &AnyObject, _: Sel) {
unsafe {
let _: () = msg_send![super(this, class!(NSVisualEffectView)), updateLayer];
- let layer: id = msg_send![this, layer];
+ let layer: *mut AnyObject = msg_send![this, layer];
if !layer.is_null() {
remove_layer_background(layer);
}
}
}
-unsafe fn remove_layer_background(layer: id) {
+unsafe fn remove_layer_background(layer: *mut AnyObject) {
unsafe {
- let _: () = msg_send![layer, setBackgroundColor:nil];
+ let _: () = msg_send![layer, setBackgroundColor: None::<&CGColor>];
- let class_name: id = msg_send![layer, className];
- if class_name.isEqualToString("CAChameleonLayer") {
+ let class_name: *mut AnyObject = msg_send![layer, className];
+ if msg_send![class_name, isEqualToString: ns_string("CAChameleonLayer")] {
// Remove the desktop tinting effect.
- let _: () = msg_send![layer, setHidden: YES];
+ let _: () = msg_send![layer, setHidden: Bool::YES];
return;
}
- let filters: id = msg_send![layer, filters];
+ let filters: *mut AnyObject = msg_send![layer, filters];
if !filters.is_null() {
// Remove the increased saturation.
// The effect of a `CAFilter` or `CIFilter` is determined by its name, and the
// `description` reflects its name and some parameters. Currently `NSVisualEffectView`
// uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
// `description` will still contain "Saturat" ("... inputSaturation = ...").
- let test_string: id = ns_string("Saturat");
- let count = NSArray::count(filters);
+ let test_string: *mut AnyObject = ns_string("Saturat");
+ let count: NSUInteger = msg_send![filters, count];
for i in 0..count {
- let description: id = msg_send![filters.objectAtIndex(i), description];
- let hit: BOOL = msg_send![description, containsString: test_string];
- if hit == NO {
+ let filter: *mut AnyObject = msg_send![filters, objectAtIndex: i];
+ let description: *mut AnyObject = msg_send![filter, description];
+ let hit: Bool = msg_send![description, containsString: test_string];
+ if hit == Bool::NO {
continue;
}
@@ -3861,42 +3899,46 @@ unsafe fn remove_layer_background(layer: id) {
location: 0,
length: count,
};
- let indices: id = msg_send![class!(NSMutableIndexSet), indexSet];
+ let indices: *mut AnyObject = msg_send![class!(NSMutableIndexSet), indexSet];
let _: () = msg_send![indices, addIndexesInRange: all_indices];
let _: () = msg_send![indices, removeIndex:i];
- let filtered: id = msg_send![filters, objectsAtIndexes: indices];
+ let filtered: *mut AnyObject = msg_send![filters, objectsAtIndexes: indices];
let _: () = msg_send![layer, setFilters: filtered];
break;
}
}
- let sublayers: id = msg_send![layer, sublayers];
+ let sublayers: *mut AnyObject = msg_send![layer, sublayers];
if !sublayers.is_null() {
- let count = NSArray::count(sublayers);
+ let count: NSUInteger = msg_send![sublayers, count];
for i in 0..count {
- let sublayer = sublayers.objectAtIndex(i);
+ let sublayer: *mut AnyObject = msg_send![sublayers, objectAtIndex: i];
remove_layer_background(sublayer);
}
}
}
}
-extern "C" fn add_titlebar_accessory_view_controller(this: &Object, _: Sel, view_controller: id) {
+extern "C" fn add_titlebar_accessory_view_controller(
+ this: &AnyObject,
+ _: Sel,
+ view_controller: *mut AnyObject,
+) {
unsafe {
let _: () = msg_send![super(this, class!(NSWindow)), addTitlebarAccessoryViewController: view_controller];
// Hide the native tab bar and set its height to 0, since we render our own.
- let accessory_view: id = msg_send![view_controller, view];
- let _: () = msg_send![accessory_view, setHidden: YES];
+ let accessory_view: *mut AnyObject = msg_send![view_controller, view];
+ let _: () = msg_send![accessory_view, setHidden: Bool::YES];
let mut frame: NSRect = msg_send![accessory_view, frame];
frame.size.height = 0.0;
let _: () = msg_send![accessory_view, setFrame: frame];
}
}
-extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
+extern "C" fn move_tab_to_new_window(this: &AnyObject, _: Sel, _: *mut AnyObject) {
unsafe {
- let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:nil];
+ let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:ptr::null_mut::<AnyObject>()];
let window_state = get_window_state(this);
let mut lock = window_state.as_ref().lock();
@@ -3908,9 +3950,10 @@ extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
}
}
-extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
+extern "C" fn merge_all_windows(this: &AnyObject, _: Sel, _: *mut AnyObject) {
unsafe {
- let _: () = msg_send![super(this, class!(NSWindow)), mergeAllWindows:nil];
+ let _: () =
+ msg_send![super(this, class!(NSWindow)), mergeAllWindows:ptr::null_mut::<AnyObject>()];
let window_state = get_window_state(this);
let mut lock = window_state.as_ref().lock();
@@ -3922,7 +3965,7 @@ extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
}
}
-extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
+extern "C" fn select_next_tab(this: &AnyObject, _sel: Sel, _id: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
if let Some(mut callback) = lock.select_next_tab_callback.take() {
@@ -3932,7 +3975,7 @@ extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
}
}
-extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
+extern "C" fn select_previous_tab(this: &AnyObject, _sel: Sel, _id: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
if let Some(mut callback) = lock.select_previous_tab_callback.take() {
@@ -3942,9 +3985,10 @@ extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
}
}
-extern "C" fn toggle_tab_bar(this: &Object, _sel: Sel, _id: id) {
+extern "C" fn toggle_tab_bar(this: &AnyObject, _sel: Sel, _id: *mut AnyObject) {
unsafe {
- let _: () = msg_send![super(this, class!(NSWindow)), toggleTabBar:nil];
+ let _: () =
+ msg_send![super(this, class!(NSWindow)), toggleTabBar:ptr::null_mut::<AnyObject>()];
let window_state = get_window_state(this);
let mut lock = window_state.as_ref().lock();
@@ -3963,7 +4007,50 @@ mod tests {
use super::*;
#[test]
- fn display_id_for_screen_returns_none_for_null_screen() {
- assert_eq!(display_id_for_screen(nil), None);
+ fn display_id_for_screen_handles_missing_metadata() {
+ assert_eq!(display_id_for_screen(ptr::null_mut::<AnyObject>()), None);
+ autoreleasepool(|_| unsafe {
+ let mut builder = ClassBuilder::new(c"GPUIDisplayIdTestScreen", class!(NSObject))
+ .expect("test screen class");
+ builder.add_ivar::<*mut AnyObject>(c"deviceDescription");
+ builder.add_method(
+ sel!(deviceDescription),
+ test_screen_device_description as extern "C" fn(_, Sel) -> *mut AnyObject,
+ );
+ let screen: Retained<AnyObject> = msg_send![builder.register(), new];
+ let description = screen
+ .class()
+ .instance_variable(c"deviceDescription")
+ .expect("test screen description ivar")
+ .load_ptr::<*mut AnyObject>(&screen);
+ let screen = Retained::as_ptr(&screen).cast_mut();
+ description.write(ptr::null_mut());
+ assert_eq!(display_id_for_screen(screen), None);
+
+ let dictionary: Retained<AnyObject> = msg_send![class!(NSMutableDictionary), new];
+ description.write(Retained::as_ptr(&dictionary).cast_mut());
+ assert_eq!(display_id_for_screen(screen), None);
+
+ for display_id in [0u32, 42] {
+ let number: Retained<AnyObject> =
+ msg_send![class!(NSNumber), numberWithUnsignedInt: display_id];
+ let _: () = msg_send![
+ &*dictionary,
+ setObject: &*number,
+ forKey: ns_string("NSScreenNumber")
+ ];
+ assert_eq!(display_id_for_screen(screen), Some(display_id));
+ }
+ });
+ }
+
+ extern "C" fn test_screen_device_description(screen: &AnyObject, _: Sel) -> *mut AnyObject {
+ unsafe {
+ *screen
+ .class()
+ .instance_variable(c"deviceDescription")
+ .expect("test screen description ivar")
+ .load::<*mut AnyObject>(screen)
+ }
}
}
diff --git a/crates/gpui_macos/src/window_appearance.rs b/crates/gpui_macos/src/window_appearance.rs
index 02704bb0fc2..60be0d70e1f 100644
--- a/crates/gpui_macos/src/window_appearance.rs
+++ b/crates/gpui_macos/src/window_appearance.rs
@@ -1,28 +1,29 @@
-use cocoa::{
- appkit::{NSAppearanceNameVibrantDark, NSAppearanceNameVibrantLight},
- base::id,
- foundation::NSString,
-};
+use crate::NSStringExt;
use gpui::WindowAppearance;
-use objc::{msg_send, sel, sel_impl};
-use std::ffi::CStr;
+use objc2::{msg_send, rc::Retained, runtime::AnyObject};
+use objc2_app_kit::{NSAppearance, NSAppearanceNameVibrantDark, NSAppearanceNameVibrantLight};
+use objc2_foundation::NSString;
-pub(crate) unsafe fn window_appearance_from_native(appearance: id) -> WindowAppearance {
- let name: id = msg_send![appearance, name];
+pub(crate) fn window_appearance_from_native(appearance: Option<&NSAppearance>) -> WindowAppearance {
+ let Some(appearance) = appearance else {
+ return WindowAppearance::Light;
+ };
unsafe {
- if name == NSAppearanceNameVibrantLight {
+ let name: Option<Retained<NSString>> = msg_send![appearance, name];
+ let Some(name) = name else {
+ return WindowAppearance::Light;
+ };
+ let name_ptr = Retained::as_ptr(&name).cast::<AnyObject>();
+ if name_ptr == std::ptr::from_ref(NSAppearanceNameVibrantLight).cast() {
WindowAppearance::VibrantLight
- } else if name == NSAppearanceNameVibrantDark {
+ } else if name_ptr == std::ptr::from_ref(NSAppearanceNameVibrantDark).cast() {
WindowAppearance::VibrantDark
- } else if name == NSAppearanceNameAqua {
+ } else if name_ptr == NSAppearanceNameAqua {
WindowAppearance::Light
- } else if name == NSAppearanceNameDarkAqua {
+ } else if name_ptr == NSAppearanceNameDarkAqua {
WindowAppearance::Dark
} else {
- println!(
- "unknown appearance: {:?}",
- CStr::from_ptr(name.UTF8String())
- );
+ println!("unknown appearance: {:?}", name_ptr.cast_mut().to_str());
WindowAppearance::Light
}
}
@@ -30,6 +31,6 @@ pub(crate) unsafe fn window_appearance_from_native(appearance: id) -> WindowAppe
#[link(name = "AppKit", kind = "framework")]
unsafe extern "C" {
- pub static NSAppearanceNameAqua: id;
- pub static NSAppearanceNameDarkAqua: id;
+ pub static NSAppearanceNameAqua: *mut AnyObject;
+ pub static NSAppearanceNameDarkAqua: *mut AnyObject;
}