Initial transition to objc2 (#2452)

* Use objc2

* Use objc2's NSInteger/NSUInteger/NSRange
This commit is contained in:
Mads Marquart 2022-09-02 15:48:02 +02:00 committed by GitHub
parent e0018d0710
commit 112965b4ff
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 394 additions and 480 deletions

View file

@ -8,6 +8,7 @@ And please only add new entries to the top of this list, right below the `# Unre
# Unreleased # Unreleased
- macOS/iOS: Use `objc2` instead of `objc` internally.
- **Breaking:** Bump MSRV from `1.57` to `1.60`. - **Breaking:** Bump MSRV from `1.57` to `1.60`.
- **Breaking:** Split the `platform::unix` module into `platform::x11` and `platform::wayland`. The extension types are similarly renamed. - **Breaking:** Split the `platform::unix` module into `platform::x11` and `platform::wayland`. The extension types are similarly renamed.
- **Breaking:**: Removed deprecated method `platform::unix::WindowExtUnix::is_ready`. - **Breaking:**: Removed deprecated method `platform::unix::WindowExtUnix::is_ready`.

View file

@ -62,12 +62,14 @@ ndk = "0.7.0"
ndk-glue = "0.7.0" ndk-glue = "0.7.0"
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] [target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
objc = "0.2.7" objc = { version = "=0.3.0-beta.3", package = "objc2" }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
cocoa = "0.24" # Branch: objc2
core-foundation = "0.9" # TODO: Use non-git versions before we release
core-graphics = "0.22" cocoa = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "c770e620ba0766fc1d2a9f83327b0fee905eb5cb" }
core-foundation = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "c770e620ba0766fc1d2a9f83327b0fee905eb5cb" }
core-graphics = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "c770e620ba0766fc1d2a9f83327b0fee905eb5cb" }
dispatch = "0.2.0" dispatch = "0.2.0"
[target.'cfg(target_os = "windows")'.dependencies.windows-sys] [target.'cfg(target_os = "windows")'.dependencies.windows-sys]

View file

@ -9,7 +9,8 @@ use std::{
time::Instant, time::Instant,
}; };
use objc::runtime::{BOOL, YES}; use objc::foundation::{NSInteger, NSUInteger};
use objc::runtime::Object;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::{ use crate::{
@ -21,8 +22,8 @@ use crate::{
ffi::{ ffi::{
id, kCFRunLoopCommonModes, CFAbsoluteTimeGetCurrent, CFRelease, CFRunLoopAddTimer, id, kCFRunLoopCommonModes, CFAbsoluteTimeGetCurrent, CFRelease, CFRunLoopAddTimer,
CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate,
CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CGRect, CGSize, NSInteger, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CGRect, CGSize,
NSOperatingSystemVersion, NSUInteger, NSOperatingSystemVersion,
}, },
}, },
window::WindowId as RootWindowId, window::WindowId as RootWindowId,
@ -472,10 +473,7 @@ impl AppState {
// retains window // retains window
pub unsafe fn set_key_window(window: id) { pub unsafe fn set_key_window(window: id) {
bug_assert!( bug_assert!(
{ msg_send![window, isKindOfClass: class!(UIWindow)],
let is_window: BOOL = msg_send![window, isKindOfClass: class!(UIWindow)];
is_window == YES
},
"set_key_window called with an incorrect type" "set_key_window called with an incorrect type"
); );
let mut this = AppState::get_mut(); let mut this = AppState::get_mut();
@ -502,10 +500,7 @@ pub unsafe fn set_key_window(window: id) {
// retains window // retains window
pub unsafe fn queue_gl_or_metal_redraw(window: id) { pub unsafe fn queue_gl_or_metal_redraw(window: id) {
bug_assert!( bug_assert!(
{ msg_send![window, isKindOfClass: class!(UIWindow)],
let is_window: BOOL = msg_send![window, isKindOfClass: class!(UIWindow)];
is_window == YES
},
"set_key_window called with an incorrect type" "set_key_window called with an incorrect type"
); );
let mut this = AppState::get_mut(); let mut this = AppState::get_mut();
@ -582,7 +577,7 @@ pub unsafe fn did_finish_launching() {
let _: () = msg_send![window, setScreen: screen]; let _: () = msg_send![window, setScreen: screen];
let _: () = msg_send![screen, release]; let _: () = msg_send![screen, release];
let controller: id = msg_send![window, rootViewController]; let controller: id = msg_send![window, rootViewController];
let _: () = msg_send![window, setRootViewController:ptr::null::<()>()]; let _: () = msg_send![window, setRootViewController:ptr::null::<Object>()];
let _: () = msg_send![window, setRootViewController: controller]; let _: () = msg_send![window, setRootViewController: controller];
let _: () = msg_send![window, makeKeyAndVisible]; let _: () = msg_send![window, makeKeyAndVisible];
} }
@ -886,8 +881,11 @@ fn get_view_and_screen_frame(window_id: id) -> (id, CGRect) {
let bounds: CGRect = msg_send![window_id, bounds]; let bounds: CGRect = msg_send![window_id, bounds];
let screen: id = msg_send![window_id, screen]; let screen: id = msg_send![window_id, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
let screen_frame: CGRect = let screen_frame: CGRect = msg_send![
msg_send![window_id, convertRect:bounds toCoordinateSpace:screen_space]; window_id,
convertRect: bounds,
toCoordinateSpace: screen_space,
];
(view, screen_frame) (view, screen_frame)
} }
} }
@ -1019,7 +1017,7 @@ pub fn os_capabilities() -> OSCapabilities {
static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| { static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| {
let version: NSOperatingSystemVersion = unsafe { let version: NSOperatingSystemVersion = unsafe {
let process_info: id = msg_send![class!(NSProcessInfo), processInfo]; let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
let atleast_ios_8: BOOL = msg_send![ let atleast_ios_8: bool = msg_send![
process_info, process_info,
respondsToSelector: sel!(operatingSystemVersion) respondsToSelector: sel!(operatingSystemVersion)
]; ];
@ -1030,10 +1028,7 @@ pub fn os_capabilities() -> OSCapabilities {
// has been tested to not even run on macOS 10.15 - Xcode 8 might? // has been tested to not even run on macOS 10.15 - Xcode 8 might?
// //
// The minimum required iOS version is likely to grow in the future. // The minimum required iOS version is likely to grow in the future.
assert!( assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
atleast_ios_8 == YES,
"`winit` requires iOS version 8 or greater"
);
msg_send![process_info, operatingSystemVersion] msg_send![process_info, operatingSystemVersion]
}; };
version.into() version.into()

View file

@ -81,9 +81,10 @@ pub(crate) struct PlatformSpecificEventLoopAttributes {}
impl<T: 'static> EventLoop<T> { impl<T: 'static> EventLoop<T> {
pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> EventLoop<T> { pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> EventLoop<T> {
assert_main_thread!("`EventLoop` can only be created on the main thread on iOS");
static mut SINGLETON_INIT: bool = false; static mut SINGLETON_INIT: bool = false;
unsafe { unsafe {
assert_main_thread!("`EventLoop` can only be created on the main thread on iOS");
assert!( assert!(
!SINGLETON_INIT, !SINGLETON_INIT,
"Only one `EventLoop` is supported on iOS. \ "Only one `EventLoop` is supported on iOS. \

View file

@ -2,6 +2,7 @@
use std::{convert::TryInto, ffi::CString, ops::BitOr, os::raw::*}; use std::{convert::TryInto, ffi::CString, ops::BitOr, os::raw::*};
use objc::foundation::{NSInteger, NSUInteger};
use objc::{runtime::Object, Encode, Encoding}; use objc::{runtime::Object, Encode, Encoding};
use crate::{ use crate::{
@ -17,9 +18,6 @@ pub type CGFloat = f32;
#[cfg(target_pointer_width = "64")] #[cfg(target_pointer_width = "64")]
pub type CGFloat = f64; pub type CGFloat = f64;
pub type NSInteger = isize;
pub type NSUInteger = usize;
#[repr(C)] #[repr(C)]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct NSOperatingSystemVersion { pub struct NSOperatingSystemVersion {
@ -28,6 +26,17 @@ pub struct NSOperatingSystemVersion {
pub patch: NSInteger, pub patch: NSInteger,
} }
unsafe impl Encode for NSOperatingSystemVersion {
const ENCODING: Encoding = Encoding::Struct(
"NSOperatingSystemVersion",
&[
NSInteger::ENCODING,
NSInteger::ENCODING,
NSInteger::ENCODING,
],
);
}
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub struct CGPoint { pub struct CGPoint {
@ -35,6 +44,10 @@ pub struct CGPoint {
pub y: CGFloat, pub y: CGFloat,
} }
unsafe impl Encode for CGPoint {
const ENCODING: Encoding = Encoding::Struct("CGPoint", &[CGFloat::ENCODING, CGFloat::ENCODING]);
}
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub struct CGSize { pub struct CGSize {
@ -51,6 +64,10 @@ impl CGSize {
} }
} }
unsafe impl Encode for CGSize {
const ENCODING: Encoding = Encoding::Struct("CGSize", &[CGFloat::ENCODING, CGFloat::ENCODING]);
}
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub struct CGRect { pub struct CGRect {
@ -65,18 +82,9 @@ impl CGRect {
} }
unsafe impl Encode for CGRect { unsafe impl Encode for CGRect {
fn encode() -> Encoding { const ENCODING: Encoding = Encoding::Struct("CGRect", &[CGPoint::ENCODING, CGSize::ENCODING]);
unsafe {
if cfg!(target_pointer_width = "32") {
Encoding::from_str("{CGRect={CGPoint=ff}{CGSize=ff}}")
} else if cfg!(target_pointer_width = "64") {
Encoding::from_str("{CGRect={CGPoint=dd}{CGSize=dd}}")
} else {
unimplemented!()
}
}
}
} }
#[derive(Debug)] #[derive(Debug)]
#[allow(dead_code)] #[allow(dead_code)]
#[repr(isize)] #[repr(isize)]
@ -88,6 +96,10 @@ pub enum UITouchPhase {
Cancelled, Cancelled,
} }
unsafe impl Encode for UITouchPhase {
const ENCODING: Encoding = NSInteger::ENCODING;
}
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
#[allow(dead_code)] #[allow(dead_code)]
#[repr(isize)] #[repr(isize)]
@ -97,6 +109,10 @@ pub enum UIForceTouchCapability {
Available, Available,
} }
unsafe impl Encode for UIForceTouchCapability {
const ENCODING: Encoding = NSInteger::ENCODING;
}
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
#[allow(dead_code)] #[allow(dead_code)]
#[repr(isize)] #[repr(isize)]
@ -106,6 +122,10 @@ pub enum UITouchType {
Pencil, Pencil,
} }
unsafe impl Encode for UITouchType {
const ENCODING: Encoding = NSInteger::ENCODING;
}
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct UIEdgeInsets { pub struct UIEdgeInsets {
@ -115,14 +135,24 @@ pub struct UIEdgeInsets {
pub right: CGFloat, pub right: CGFloat,
} }
unsafe impl Encode for UIEdgeInsets {
const ENCODING: Encoding = Encoding::Struct(
"UIEdgeInsets",
&[
CGFloat::ENCODING,
CGFloat::ENCODING,
CGFloat::ENCODING,
CGFloat::ENCODING,
],
);
}
#[repr(transparent)] #[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UIUserInterfaceIdiom(NSInteger); pub struct UIUserInterfaceIdiom(NSInteger);
unsafe impl Encode for UIUserInterfaceIdiom { unsafe impl Encode for UIUserInterfaceIdiom {
fn encode() -> Encoding { const ENCODING: Encoding = NSInteger::ENCODING;
NSInteger::encode()
}
} }
impl UIUserInterfaceIdiom { impl UIUserInterfaceIdiom {
@ -162,9 +192,7 @@ impl From<UIUserInterfaceIdiom> for Idiom {
pub struct UIInterfaceOrientationMask(NSUInteger); pub struct UIInterfaceOrientationMask(NSUInteger);
unsafe impl Encode for UIInterfaceOrientationMask { unsafe impl Encode for UIInterfaceOrientationMask {
fn encode() -> Encoding { const ENCODING: Encoding = NSUInteger::ENCODING;
NSUInteger::encode()
}
} }
impl UIInterfaceOrientationMask { impl UIInterfaceOrientationMask {
@ -213,9 +241,7 @@ impl UIInterfaceOrientationMask {
pub struct UIRectEdge(NSUInteger); pub struct UIRectEdge(NSUInteger);
unsafe impl Encode for UIRectEdge { unsafe impl Encode for UIRectEdge {
fn encode() -> Encoding { const ENCODING: Encoding = NSUInteger::ENCODING;
NSUInteger::encode()
}
} }
impl From<ScreenEdge> for UIRectEdge { impl From<ScreenEdge> for UIRectEdge {
@ -241,9 +267,7 @@ impl From<UIRectEdge> for ScreenEdge {
pub struct UIScreenOverscanCompensation(NSInteger); pub struct UIScreenOverscanCompensation(NSInteger);
unsafe impl Encode for UIScreenOverscanCompensation { unsafe impl Encode for UIScreenOverscanCompensation {
fn encode() -> Encoding { const ENCODING: Encoding = NSInteger::ENCODING;
NSInteger::encode()
}
} }
#[allow(dead_code)] #[allow(dead_code)]

View file

@ -63,8 +63,7 @@
// window size/position. // window size/position.
macro_rules! assert_main_thread { macro_rules! assert_main_thread {
($($t:tt)*) => { ($($t:tt)*) => {
let is_main_thread: ::objc::runtime::BOOL = msg_send!(class!(NSThread), isMainThread); if !::objc::foundation::is_main_thread() {
if is_main_thread == ::objc::runtime::NO {
panic!($($t)*); panic!($($t)*);
} }
}; };

View file

@ -4,12 +4,14 @@ use std::{
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
}; };
use objc::foundation::{NSInteger, NSUInteger};
use crate::{ use crate::{
dpi::{PhysicalPosition, PhysicalSize}, dpi::{PhysicalPosition, PhysicalSize},
monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode},
platform_impl::platform::{ platform_impl::platform::{
app_state, app_state,
ffi::{id, nil, CGFloat, CGRect, CGSize, NSInteger, NSUInteger}, ffi::{id, nil, CGFloat, CGRect, CGSize},
}, },
}; };
@ -113,22 +115,14 @@ impl Deref for MonitorHandle {
type Target = Inner; type Target = Inner;
fn deref(&self) -> &Inner { fn deref(&self) -> &Inner {
unsafe { assert_main_thread!("`MonitorHandle` methods can only be run on the main thread on iOS");
assert_main_thread!(
"`MonitorHandle` methods can only be run on the main thread on iOS"
);
}
&self.inner &self.inner
} }
} }
impl DerefMut for MonitorHandle { impl DerefMut for MonitorHandle {
fn deref_mut(&mut self) -> &mut Inner { fn deref_mut(&mut self) -> &mut Inner {
unsafe { assert_main_thread!("`MonitorHandle` methods can only be run on the main thread on iOS");
assert_main_thread!(
"`MonitorHandle` methods can only be run on the main thread on iOS"
);
}
&mut self.inner &mut self.inner
} }
} }
@ -144,9 +138,7 @@ impl Clone for MonitorHandle {
impl Drop for MonitorHandle { impl Drop for MonitorHandle {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { assert_main_thread!("`MonitorHandle` can only be dropped on the main thread on iOS");
assert_main_thread!("`MonitorHandle` can only be dropped on the main thread on iOS");
}
} }
} }
@ -175,8 +167,8 @@ impl fmt::Debug for MonitorHandle {
impl MonitorHandle { impl MonitorHandle {
pub fn retained_new(uiscreen: id) -> MonitorHandle { pub fn retained_new(uiscreen: id) -> MonitorHandle {
assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS");
unsafe { unsafe {
assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS");
let _: id = msg_send![uiscreen, retain]; let _: id = msg_send![uiscreen, retain];
} }
MonitorHandle { MonitorHandle {

View file

@ -1,8 +1,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use objc::{ use objc::{
declare::ClassDecl, declare::ClassBuilder,
runtime::{Class, Object, Sel, BOOL, NO, YES}, runtime::{Bool, Class, Object, Sel},
}; };
use crate::{ use crate::{
@ -66,15 +66,15 @@ macro_rules! add_property {
}; };
#[allow(non_snake_case)] #[allow(non_snake_case)]
extern "C" fn $getter_name($object: &Object, _: Sel) -> $t { extern "C" fn $getter_name($object: &Object, _: Sel) -> $t {
unsafe { *$object.get_ivar::<$t>(VAR_NAME) } unsafe { *$object.ivar::<$t>(VAR_NAME) }
} }
$decl.add_method( $decl.add_method(
sel!($setter_name:), sel!($setter_name:),
setter as extern "C" fn(&mut Object, Sel, $t), setter as extern "C" fn(_, _, _),
); );
$decl.add_method( $decl.add_method(
sel!($getter_name), sel!($getter_name),
$getter_name as extern "C" fn(&Object, Sel) -> $t, $getter_name as extern "C" fn(_, _) -> _,
); );
} }
}; };
@ -93,11 +93,8 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
classes.entry(root_view_class).or_insert_with(move || { classes.entry(root_view_class).or_insert_with(move || {
let uiview_class = class!(UIView); let uiview_class = class!(UIView);
let is_uiview: BOOL = msg_send![root_view_class, isSubclassOfClass: uiview_class]; let is_uiview: bool = msg_send![root_view_class, isSubclassOfClass: uiview_class];
assert_eq!( assert!(is_uiview, "`root_view_class` must inherit from `UIView`");
is_uiview, YES,
"`root_view_class` must inherit from `UIView`"
);
extern "C" fn draw_rect(object: &Object, _: Sel, rect: CGRect) { extern "C" fn draw_rect(object: &Object, _: Sel, rect: CGRect) {
unsafe { unsafe {
@ -126,8 +123,11 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
let window_bounds: CGRect = msg_send![window, bounds]; let window_bounds: CGRect = msg_send![window, bounds];
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
let screen_frame: CGRect = let screen_frame: CGRect = msg_send![
msg_send![object, convertRect:window_bounds toCoordinateSpace:screen_space]; object,
convertRect: window_bounds,
toCoordinateSpace: screen_space,
];
let scale_factor: CGFloat = msg_send![screen, scale]; let scale_factor: CGFloat = msg_send![screen, scale];
let size = crate::dpi::LogicalSize { let size = crate::dpi::LogicalSize {
width: screen_frame.size.width as f64, width: screen_frame.size.width as f64,
@ -156,11 +156,12 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
untrusted_scale_factor: CGFloat, untrusted_scale_factor: CGFloat,
) { ) {
unsafe { unsafe {
let superclass: &'static Class = msg_send![object, superclass]; let superclass: &'static Class = msg_send![&*object, superclass];
let _: () = msg_send![ let _: () = msg_send![
super(object, superclass), super(&mut *object, superclass),
setContentScaleFactor: untrusted_scale_factor setContentScaleFactor: untrusted_scale_factor
]; ];
let object = &*object; // Immutable for rest of method
let window: id = msg_send![object, window]; let window: id = msg_send![object, window];
// `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow // `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow
@ -185,7 +186,7 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
let screen_frame: CGRect = let screen_frame: CGRect =
msg_send![object, convertRect:bounds toCoordinateSpace:screen_space]; msg_send![object, convertRect: bounds, toCoordinateSpace: screen_space];
let size = crate::dpi::LogicalSize { let size = crate::dpi::LogicalSize {
width: screen_frame.size.width as _, width: screen_frame.size.width as _,
height: screen_frame.size.height as _, height: screen_frame.size.height as _,
@ -280,37 +281,31 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
} }
} }
let mut decl = ClassDecl::new(&format!("WinitUIView{}", ID), root_view_class) let mut decl = ClassBuilder::new(&format!("WinitUIView{}", ID), root_view_class)
.expect("Failed to declare class `WinitUIView`"); .expect("Failed to declare class `WinitUIView`");
ID += 1; ID += 1;
decl.add_method( decl.add_method(sel!(drawRect:), draw_rect as extern "C" fn(_, _, _));
sel!(drawRect:), decl.add_method(sel!(layoutSubviews), layout_subviews as extern "C" fn(_, _));
draw_rect as extern "C" fn(&Object, Sel, CGRect),
);
decl.add_method(
sel!(layoutSubviews),
layout_subviews as extern "C" fn(&Object, Sel),
);
decl.add_method( decl.add_method(
sel!(setContentScaleFactor:), sel!(setContentScaleFactor:),
set_content_scale_factor as extern "C" fn(&mut Object, Sel, CGFloat), set_content_scale_factor as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(touchesBegan:withEvent:), sel!(touchesBegan:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), handle_touches as extern "C" fn(_, _, _, _),
); );
decl.add_method( decl.add_method(
sel!(touchesMoved:withEvent:), sel!(touchesMoved:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), handle_touches as extern "C" fn(_, _, _, _),
); );
decl.add_method( decl.add_method(
sel!(touchesEnded:withEvent:), sel!(touchesEnded:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), handle_touches as extern "C" fn(_, _, _, _),
); );
decl.add_method( decl.add_method(
sel!(touchesCancelled:withEvent:), sel!(touchesCancelled:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), handle_touches as extern "C" fn(_, _, _, _),
); );
decl.register() decl.register()
@ -325,19 +320,19 @@ unsafe fn get_view_controller_class() -> &'static Class {
let uiviewcontroller_class = class!(UIViewController); let uiviewcontroller_class = class!(UIViewController);
extern "C" fn should_autorotate(_: &Object, _: Sel) -> BOOL { extern "C" fn should_autorotate(_: &Object, _: Sel) -> Bool {
YES Bool::YES
} }
let mut decl = ClassDecl::new("WinitUIViewController", uiviewcontroller_class) let mut decl = ClassBuilder::new("WinitUIViewController", uiviewcontroller_class)
.expect("Failed to declare class `WinitUIViewController`"); .expect("Failed to declare class `WinitUIViewController`");
decl.add_method( decl.add_method(
sel!(shouldAutorotate), sel!(shouldAutorotate),
should_autorotate as extern "C" fn(&Object, Sel) -> BOOL, should_autorotate as extern "C" fn(_, _) -> _,
); );
add_property! { add_property! {
decl, decl,
prefers_status_bar_hidden: BOOL, prefers_status_bar_hidden: Bool,
setPrefersStatusBarHidden: |object| { setPrefersStatusBarHidden: |object| {
unsafe { unsafe {
let _: () = msg_send![object, setNeedsStatusBarAppearanceUpdate]; let _: () = msg_send![object, setNeedsStatusBarAppearanceUpdate];
@ -347,7 +342,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
} }
add_property! { add_property! {
decl, decl,
prefers_home_indicator_auto_hidden: BOOL, prefers_home_indicator_auto_hidden: Bool,
setPrefersHomeIndicatorAutoHidden: setPrefersHomeIndicatorAutoHidden:
os_capabilities.home_indicator_hidden, os_capabilities.home_indicator_hidden,
OSCapabilities::home_indicator_hidden_err_msg; OSCapabilities::home_indicator_hidden_err_msg;
@ -412,15 +407,15 @@ unsafe fn get_window_class() -> &'static Class {
} }
} }
let mut decl = ClassDecl::new("WinitUIWindow", uiwindow_class) let mut decl = ClassBuilder::new("WinitUIWindow", uiwindow_class)
.expect("Failed to declare class `WinitUIWindow`"); .expect("Failed to declare class `WinitUIWindow`");
decl.add_method( decl.add_method(
sel!(becomeKeyWindow), sel!(becomeKeyWindow),
become_key_window as extern "C" fn(&Object, Sel), become_key_window as extern "C" fn(_, _),
); );
decl.add_method( decl.add_method(
sel!(resignKeyWindow), sel!(resignKeyWindow),
resign_key_window as extern "C" fn(&Object, Sel), resign_key_window as extern "C" fn(_, _),
); );
CLASS = Some(decl.register()); CLASS = Some(decl.register());
@ -440,7 +435,7 @@ pub(crate) unsafe fn create_view(
assert!(!view.is_null(), "Failed to create `UIView` instance"); assert!(!view.is_null(), "Failed to create `UIView` instance");
let view: id = msg_send![view, initWithFrame: frame]; let view: id = msg_send![view, initWithFrame: frame];
assert!(!view.is_null(), "Failed to initialize `UIView` instance"); assert!(!view.is_null(), "Failed to initialize `UIView` instance");
let _: () = msg_send![view, setMultipleTouchEnabled: YES]; let _: () = msg_send![view, setMultipleTouchEnabled: Bool::YES];
if let Some(scale_factor) = platform_attributes.scale_factor { if let Some(scale_factor) = platform_attributes.scale_factor {
let _: () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat]; let _: () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat];
} }
@ -466,21 +461,14 @@ pub(crate) unsafe fn create_view_controller(
!view_controller.is_null(), !view_controller.is_null(),
"Failed to initialize `UIViewController` instance" "Failed to initialize `UIViewController` instance"
); );
let status_bar_hidden = if platform_attributes.prefers_status_bar_hidden { let status_bar_hidden = Bool::new(platform_attributes.prefers_status_bar_hidden);
YES
} else {
NO
};
let idiom = event_loop::get_idiom(); let idiom = event_loop::get_idiom();
let supported_orientations = UIInterfaceOrientationMask::from_valid_orientations_idiom( let supported_orientations = UIInterfaceOrientationMask::from_valid_orientations_idiom(
platform_attributes.valid_orientations, platform_attributes.valid_orientations,
idiom, idiom,
); );
let prefers_home_indicator_hidden = if platform_attributes.prefers_home_indicator_hidden { let prefers_home_indicator_hidden =
YES Bool::new(platform_attributes.prefers_home_indicator_hidden);
} else {
NO
};
let edges: UIRectEdge = platform_attributes let edges: UIRectEdge = platform_attributes
.preferred_screen_edges_deferring_system_gestures .preferred_screen_edges_deferring_system_gestures
.into(); .into();
@ -545,11 +533,11 @@ pub(crate) unsafe fn create_window(
} }
pub fn create_delegate_class() { pub fn create_delegate_class() {
extern "C" fn did_finish_launching(_: &mut Object, _: Sel, _: id, _: id) -> BOOL { extern "C" fn did_finish_launching(_: &mut Object, _: Sel, _: id, _: id) -> Bool {
unsafe { unsafe {
app_state::did_finish_launching(); app_state::did_finish_launching();
} }
YES Bool::YES
} }
extern "C" fn did_become_active(_: &Object, _: Sel, _: id) { extern "C" fn did_become_active(_: &Object, _: Sel, _: id) {
@ -574,8 +562,8 @@ pub fn create_delegate_class() {
if window == nil { if window == nil {
break; break;
} }
let is_winit_window: BOOL = msg_send![window, isKindOfClass: class!(WinitUIWindow)]; let is_winit_window = msg_send![window, isKindOfClass: class!(WinitUIWindow)];
if is_winit_window == YES { if is_winit_window {
events.push(EventWrapper::StaticEvent(Event::WindowEvent { events.push(EventWrapper::StaticEvent(Event::WindowEvent {
window_id: RootWindowId(window.into()), window_id: RootWindowId(window.into()),
event: WindowEvent::Destroyed, event: WindowEvent::Destroyed,
@ -588,35 +576,35 @@ pub fn create_delegate_class() {
} }
let ui_responder = class!(UIResponder); let ui_responder = class!(UIResponder);
let mut decl = let mut decl = ClassBuilder::new("AppDelegate", ui_responder)
ClassDecl::new("AppDelegate", ui_responder).expect("Failed to declare class `AppDelegate`"); .expect("Failed to declare class `AppDelegate`");
unsafe { unsafe {
decl.add_method( decl.add_method(
sel!(application:didFinishLaunchingWithOptions:), sel!(application:didFinishLaunchingWithOptions:),
did_finish_launching as extern "C" fn(&mut Object, Sel, id, id) -> BOOL, did_finish_launching as extern "C" fn(_, _, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(applicationDidBecomeActive:), sel!(applicationDidBecomeActive:),
did_become_active as extern "C" fn(&Object, Sel, id), did_become_active as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(applicationWillResignActive:), sel!(applicationWillResignActive:),
will_resign_active as extern "C" fn(&Object, Sel, id), will_resign_active as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(applicationWillEnterForeground:), sel!(applicationWillEnterForeground:),
will_enter_foreground as extern "C" fn(&Object, Sel, id), will_enter_foreground as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(applicationDidEnterBackground:), sel!(applicationDidEnterBackground:),
did_enter_background as extern "C" fn(&Object, Sel, id), did_enter_background as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(applicationWillTerminate:), sel!(applicationWillTerminate:),
will_terminate as extern "C" fn(&Object, Sel, id), will_terminate as extern "C" fn(_, _, _),
); );
decl.register(); decl.register();

View file

@ -3,7 +3,7 @@ use std::{
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
}; };
use objc::runtime::{Class, Object, BOOL, NO, YES}; use objc::runtime::{Class, Object};
use raw_window_handle::{RawDisplayHandle, RawWindowHandle, UiKitDisplayHandle, UiKitWindowHandle}; use raw_window_handle::{RawDisplayHandle, RawWindowHandle, UiKitDisplayHandle, UiKitWindowHandle};
use crate::{ use crate::{
@ -51,14 +51,7 @@ impl Inner {
} }
pub fn set_visible(&self, visible: bool) { pub fn set_visible(&self, visible: bool) {
match visible { unsafe { msg_send![self.window, setHidden: !visible] }
true => unsafe {
let _: () = msg_send![self.window, setHidden: NO];
},
false => unsafe {
let _: () = msg_send![self.window, setHidden: YES];
},
}
} }
pub fn is_visible(&self) -> Option<bool> { pub fn is_visible(&self) -> Option<bool> {
@ -350,9 +343,7 @@ pub struct Window {
impl Drop for Window { impl Drop for Window {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { assert_main_thread!("`Window::drop` can only be run on the main thread on iOS");
assert_main_thread!("`Window::drop` can only be run on the main thread on iOS");
}
} }
} }
@ -363,18 +354,14 @@ impl Deref for Window {
type Target = Inner; type Target = Inner;
fn deref(&self) -> &Inner { fn deref(&self) -> &Inner {
unsafe { assert_main_thread!("`Window` methods can only be run on the main thread on iOS");
assert_main_thread!("`Window` methods can only be run on the main thread on iOS");
}
&self.inner &self.inner
} }
} }
impl DerefMut for Window { impl DerefMut for Window {
fn deref_mut(&mut self) -> &mut Inner { fn deref_mut(&mut self) -> &mut Inner {
unsafe { assert_main_thread!("`Window` methods can only be run on the main thread on iOS");
assert_main_thread!("`Window` methods can only be run on the main thread on iOS");
}
&mut self.inner &mut self.inner
} }
} }
@ -429,10 +416,9 @@ impl Window {
let gl_or_metal_backed = { let gl_or_metal_backed = {
let view_class: *const Class = msg_send![view, class]; let view_class: *const Class = msg_send![view, class];
let layer_class: *const Class = msg_send![view_class, layerClass]; let layer_class: *const Class = msg_send![view_class, layerClass];
let is_metal: BOOL = let is_metal = msg_send![layer_class, isSubclassOfClass: class!(CAMetalLayer)];
msg_send![layer_class, isSubclassOfClass: class!(CAMetalLayer)]; let is_gl = msg_send![layer_class, isSubclassOfClass: class!(CAEAGLLayer)];
let is_gl: BOOL = msg_send![layer_class, isSubclassOfClass: class!(CAEAGLLayer)]; is_metal || is_gl
is_metal == YES || is_gl == YES
}; };
let view_controller = let view_controller =
@ -463,7 +449,7 @@ impl Window {
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
let screen_frame: CGRect = let screen_frame: CGRect =
msg_send![view, convertRect:bounds toCoordinateSpace:screen_space]; msg_send![view, convertRect: bounds, toCoordinateSpace: screen_space];
let size = crate::dpi::LogicalSize { let size = crate::dpi::LogicalSize {
width: screen_frame.size.width as _, width: screen_frame.size.width as _,
height: screen_frame.size.height as _, height: screen_frame.size.height as _,
@ -527,10 +513,9 @@ impl Inner {
pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
unsafe { unsafe {
let prefers_home_indicator_hidden = if hidden { YES } else { NO };
let _: () = msg_send![ let _: () = msg_send![
self.view_controller, self.view_controller,
setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden setPrefersHomeIndicatorAutoHidden: hidden,
]; ];
} }
} }
@ -547,11 +532,7 @@ impl Inner {
pub fn set_prefers_status_bar_hidden(&self, hidden: bool) { pub fn set_prefers_status_bar_hidden(&self, hidden: bool) {
unsafe { unsafe {
let status_bar_hidden = if hidden { YES } else { NO }; let _: () = msg_send![self.view_controller, setPrefersStatusBarHidden: hidden,];
let _: () = msg_send![
self.view_controller,
setPrefersStatusBarHidden: status_bar_hidden
];
} }
} }
} }
@ -567,7 +548,11 @@ impl Inner {
let screen: id = msg_send![self.window, screen]; let screen: id = msg_send![self.window, screen];
if !screen.is_null() { if !screen.is_null() {
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
msg_send![self.window, convertRect:rect toCoordinateSpace:screen_space] msg_send![
self.window,
convertRect: rect,
toCoordinateSpace: screen_space,
]
} else { } else {
rect rect
} }
@ -578,7 +563,11 @@ impl Inner {
let screen: id = msg_send![self.window, screen]; let screen: id = msg_send![self.window, screen];
if !screen.is_null() { if !screen.is_null() {
let screen_space: id = msg_send![screen, coordinateSpace]; let screen_space: id = msg_send![screen, coordinateSpace];
msg_send![self.window, convertRect:rect fromCoordinateSpace:screen_space] msg_send![
self.window,
convertRect: rect,
fromCoordinateSpace: screen_space,
]
} else { } else {
rect rect
} }

View file

@ -5,7 +5,7 @@ use cocoa::{
base::id, base::id,
}; };
use objc::{ use objc::{
declare::ClassDecl, declare::ClassBuilder,
runtime::{Class, Object, Sel}, runtime::{Class, Object, Sel},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -19,12 +19,9 @@ unsafe impl Sync for AppClass {}
pub static APP_CLASS: Lazy<AppClass> = Lazy::new(|| unsafe { pub static APP_CLASS: Lazy<AppClass> = Lazy::new(|| unsafe {
let superclass = class!(NSApplication); let superclass = class!(NSApplication);
let mut decl = ClassDecl::new("WinitApp", superclass).unwrap(); let mut decl = ClassBuilder::new("WinitApp", superclass).unwrap();
decl.add_method( decl.add_method(sel!(sendEvent:), send_event as extern "C" fn(_, _, _));
sel!(sendEvent:),
send_event as extern "C" fn(&Object, Sel, id),
);
AppClass(decl.register()) AppClass(decl.register())
}); });

View file

@ -5,7 +5,7 @@ use std::{
use cocoa::base::id; use cocoa::base::id;
use objc::{ use objc::{
declare::ClassDecl, declare::ClassBuilder,
runtime::{Class, Object, Sel}, runtime::{Class, Object, Sel},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -25,18 +25,18 @@ unsafe impl Sync for AppDelegateClass {}
pub static APP_DELEGATE_CLASS: Lazy<AppDelegateClass> = Lazy::new(|| unsafe { pub static APP_DELEGATE_CLASS: Lazy<AppDelegateClass> = Lazy::new(|| unsafe {
let superclass = class!(NSResponder); let superclass = class!(NSResponder);
let mut decl = ClassDecl::new("WinitAppDelegate", superclass).unwrap(); let mut decl = ClassBuilder::new("WinitAppDelegate", superclass).unwrap();
decl.add_class_method(sel!(new), new as extern "C" fn(&Class, Sel) -> id); decl.add_class_method(sel!(new), new as extern "C" fn(_, _) -> _);
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _));
decl.add_method( decl.add_method(
sel!(applicationDidFinishLaunching:), sel!(applicationDidFinishLaunching:),
did_finish_launching as extern "C" fn(&Object, Sel, id), did_finish_launching as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(applicationWillTerminate:), sel!(applicationWillTerminate:),
will_terminate as extern "C" fn(&Object, Sel, id), will_terminate as extern "C" fn(_, _, _),
); );
decl.add_ivar::<*mut c_void>(AUX_DELEGATE_STATE_NAME); decl.add_ivar::<*mut c_void>(AUX_DELEGATE_STATE_NAME);
@ -46,7 +46,7 @@ pub static APP_DELEGATE_CLASS: Lazy<AppDelegateClass> = Lazy::new(|| unsafe {
/// Safety: Assumes that Object is an instance of APP_DELEGATE_CLASS /// Safety: Assumes that Object is an instance of APP_DELEGATE_CLASS
pub unsafe fn get_aux_state_mut(this: &Object) -> RefMut<'_, AuxDelegateState> { pub unsafe fn get_aux_state_mut(this: &Object) -> RefMut<'_, AuxDelegateState> {
let ptr: *mut c_void = *this.get_ivar(AUX_DELEGATE_STATE_NAME); let ptr: *mut c_void = *this.ivar(AUX_DELEGATE_STATE_NAME);
// Watch out that this needs to be the correct type // Watch out that this needs to be the correct type
(*(ptr as *mut RefCell<AuxDelegateState>)).borrow_mut() (*(ptr as *mut RefCell<AuxDelegateState>)).borrow_mut()
} }
@ -69,7 +69,7 @@ extern "C" fn new(class: &Class, _: Sel) -> id {
extern "C" fn dealloc(this: &Object, _: Sel) { extern "C" fn dealloc(this: &Object, _: Sel) {
unsafe { unsafe {
let state_ptr: *mut c_void = *(this.get_ivar(AUX_DELEGATE_STATE_NAME)); let state_ptr: *mut c_void = *(this.ivar(AUX_DELEGATE_STATE_NAME));
// As soon as the box is constructed it is immediately dropped, releasing the underlying // As soon as the box is constructed it is immediately dropped, releasing the underlying
// memory // memory
drop(Box::from_raw(state_ptr as *mut RefCell<AuxDelegateState>)); drop(Box::from_raw(state_ptr as *mut RefCell<AuxDelegateState>));

View file

@ -18,8 +18,9 @@ use cocoa::{
foundation::NSSize, foundation::NSSize,
}; };
use objc::{ use objc::{
foundation::is_main_thread,
rc::autoreleasepool, rc::autoreleasepool,
runtime::{Object, BOOL, NO, YES}, runtime::{Bool, Object},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -288,7 +289,7 @@ impl AppState {
let ns_app = NSApp(); let ns_app = NSApp();
window_activation_hack(ns_app); window_activation_hack(ns_app);
// TODO: Consider allowing the user to specify they don't want their application activated // TODO: Consider allowing the user to specify they don't want their application activated
ns_app.activateIgnoringOtherApps_(YES); ns_app.activateIgnoringOtherApps_(Bool::YES.as_raw());
}; };
HANDLER.set_ready(); HANDLER.set_ready();
HANDLER.waker().start(); HANDLER.waker().start();
@ -361,16 +362,14 @@ impl AppState {
} }
pub fn queue_event(wrapper: EventWrapper) { pub fn queue_event(wrapper: EventWrapper) {
let is_main_thread: BOOL = unsafe { msg_send!(class!(NSThread), isMainThread) }; if !is_main_thread() {
if is_main_thread == NO {
panic!("Event queued from different thread: {:#?}", wrapper); panic!("Event queued from different thread: {:#?}", wrapper);
} }
HANDLER.events().push_back(wrapper); HANDLER.events().push_back(wrapper);
} }
pub fn queue_events(mut wrappers: VecDeque<EventWrapper>) { pub fn queue_events(mut wrappers: VecDeque<EventWrapper>) {
let is_main_thread: BOOL = unsafe { msg_send!(class!(NSThread), isMainThread) }; if !is_main_thread() {
if is_main_thread == NO {
panic!("Events queued from different thread: {:#?}", wrappers); panic!("Events queued from different thread: {:#?}", wrappers);
} }
HANDLER.events().append(&mut wrappers); HANDLER.events().append(&mut wrappers);
@ -403,7 +402,7 @@ impl AppState {
unsafe { unsafe {
let app: id = NSApp(); let app: id = NSApp();
autoreleasepool(|| { autoreleasepool(|_| {
let _: () = msg_send![app, stop: nil]; let _: () = msg_send![app, stop: nil];
// To stop event loop immediately, we need to post some event here. // To stop event loop immediately, we need to post some event here.
post_dummy_event(app); post_dummy_event(app);
@ -443,7 +442,7 @@ unsafe fn window_activation_hack(ns_app: id) {
// And call `makeKeyAndOrderFront` if it was called on the window in `UnownedWindow::new` // And call `makeKeyAndOrderFront` if it was called on the window in `UnownedWindow::new`
// This way we preserve the user's desired initial visiblity status // This way we preserve the user's desired initial visiblity status
// TODO: Also filter on the type/"level" of the window, and maybe other things? // TODO: Also filter on the type/"level" of the window, and maybe other things?
if ns_window.isVisible() == YES { if Bool::from_raw(ns_window.isVisible()).as_bool() {
trace!("Activating visible window"); trace!("Activating visible window");
ns_window.makeKeyAndOrderFront_(nil); ns_window.makeKeyAndOrderFront_(nil);
} else { } else {

View file

@ -13,9 +13,10 @@ use std::{
use cocoa::{ use cocoa::{
appkit::{NSApp, NSEventModifierFlags, NSEventSubtype, NSEventType::NSApplicationDefined}, appkit::{NSApp, NSEventModifierFlags, NSEventSubtype, NSEventType::NSApplicationDefined},
base::{id, nil, BOOL, NO, YES}, base::{id, nil},
foundation::{NSInteger, NSPoint, NSTimeInterval}, foundation::{NSPoint, NSTimeInterval},
}; };
use objc::foundation::is_main_thread;
use objc::rc::autoreleasepool; use objc::rc::autoreleasepool;
use raw_window_handle::{AppKitDisplayHandle, RawDisplayHandle}; use raw_window_handle::{AppKitDisplayHandle, RawDisplayHandle};
@ -144,8 +145,7 @@ impl Default for PlatformSpecificEventLoopAttributes {
impl<T> EventLoop<T> { impl<T> EventLoop<T> {
pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Self { pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Self {
let delegate = unsafe { let delegate = unsafe {
let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); if !is_main_thread() {
if is_main_thread == NO {
panic!("On macOS, `EventLoop` must be created on the main thread!"); panic!("On macOS, `EventLoop` must be created on the main thread!");
} }
@ -161,7 +161,7 @@ impl<T> EventLoop<T> {
aux_state.activation_policy = attributes.activation_policy; aux_state.activation_policy = attributes.activation_policy;
aux_state.default_menu = attributes.default_menu; aux_state.default_menu = attributes.default_menu;
autoreleasepool(|| { autoreleasepool(|_| {
let _: () = msg_send![app, setDelegate:*delegate]; let _: () = msg_send![app, setDelegate:*delegate];
}); });
@ -209,7 +209,7 @@ impl<T> EventLoop<T> {
self._callback = Some(Rc::clone(&callback)); self._callback = Some(Rc::clone(&callback));
let exit_code = autoreleasepool(|| unsafe { let exit_code = autoreleasepool(|_| unsafe {
let app = NSApp(); let app = NSApp();
assert_ne!(app, nil); assert_ne!(app, nil);
@ -246,13 +246,13 @@ pub unsafe fn post_dummy_event(target: id) {
location: NSPoint::new(0.0, 0.0) location: NSPoint::new(0.0, 0.0)
modifierFlags: NSEventModifierFlags::empty() modifierFlags: NSEventModifierFlags::empty()
timestamp: 0 as NSTimeInterval timestamp: 0 as NSTimeInterval
windowNumber: 0 as NSInteger windowNumber: 0isize
context: nil context: nil
subtype: NSEventSubtype::NSWindowExposedEventType subtype: NSEventSubtype::NSWindowExposedEventType
data1: 0 as NSInteger data1: 0isize
data2: 0 as NSInteger data2: 0isize
]; ];
let _: () = msg_send![target, postEvent: dummy_event atStart: YES]; let _: () = msg_send![target, postEvent: dummy_event, atStart: true];
} }
/// Catches panics that happen inside `f` and when a panic /// Catches panics that happen inside `f` and when a panic

View file

@ -4,10 +4,7 @@
use std::ffi::c_void; use std::ffi::c_void;
use cocoa::{ use cocoa::base::id;
base::id,
foundation::{NSInteger, NSUInteger},
};
use core_foundation::{ use core_foundation::{
array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef, array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef,
}; };
@ -15,34 +12,10 @@ use core_graphics::{
base::CGError, base::CGError,
display::{CGDirectDisplayID, CGDisplayConfigRef}, display::{CGDirectDisplayID, CGDisplayConfigRef},
}; };
use objc::foundation::{NSInteger, NSUInteger};
pub const NSNotFound: NSInteger = NSInteger::max_value(); pub const NSNotFound: NSInteger = NSInteger::max_value();
#[repr(C)]
pub struct NSRange {
pub location: NSUInteger,
pub length: NSUInteger,
}
impl NSRange {
#[inline]
pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange {
NSRange { location, length }
}
}
unsafe impl objc::Encode for NSRange {
fn encode() -> objc::Encoding {
let encoding = format!(
// TODO: Verify that this is correct
"{{NSRange={}{}}}",
NSUInteger::encode().as_str(),
NSUInteger::encode().as_str(),
);
unsafe { objc::Encoding::from_str(&encoding) }
}
}
pub trait NSMutableAttributedString: Sized { pub trait NSMutableAttributedString: Sized {
unsafe fn alloc(_: Self) -> id { unsafe fn alloc(_: Self) -> id {
msg_send![class!(NSMutableAttributedString), alloc] msg_send![class!(NSMutableAttributedString), alloc]

View file

@ -13,7 +13,7 @@ struct KeyEquivalent<'a> {
} }
pub fn initialize() { pub fn initialize() {
autoreleasepool(|| unsafe { autoreleasepool(|_| unsafe {
let menubar = IdRef::new(NSMenu::new(nil)); let menubar = IdRef::new(NSMenu::new(nil));
let app_menu_item = IdRef::new(NSMenuItem::new(nil)); let app_menu_item = IdRef::new(NSMenuItem::new(nil));
menubar.addItem_(*app_menu_item); menubar.addItem_(*app_menu_item);

View file

@ -75,7 +75,7 @@ impl Window {
attributes: WindowAttributes, attributes: WindowAttributes,
pl_attribs: PlatformSpecificWindowBuilderAttributes, pl_attribs: PlatformSpecificWindowBuilderAttributes,
) -> Result<Self, RootOsError> { ) -> Result<Self, RootOsError> {
let (window, _delegate) = autoreleasepool(|| UnownedWindow::new(attributes, pl_attribs))?; let (window, _delegate) = autoreleasepool(|_| UnownedWindow::new(attributes, pl_attribs))?;
Ok(Window { window, _delegate }) Ok(Window { window, _delegate })
} }
} }

View file

@ -8,7 +8,6 @@ use crate::{
use cocoa::{ use cocoa::{
appkit::NSScreen, appkit::NSScreen,
base::{id, nil}, base::{id, nil},
foundation::NSUInteger,
}; };
use core_foundation::{ use core_foundation::{
array::{CFArrayGetCount, CFArrayGetValueAtIndex}, array::{CFArrayGetCount, CFArrayGetValueAtIndex},
@ -16,6 +15,7 @@ use core_foundation::{
string::CFString, string::CFString,
}; };
use core_graphics::display::{CGDirectDisplayID, CGDisplay, CGDisplayBounds}; use core_graphics::display::{CGDirectDisplayID, CGDisplay, CGDisplayBounds};
use objc::foundation::NSUInteger;
#[derive(Clone)] #[derive(Clone)]
pub struct VideoMode { pub struct VideoMode {

View file

@ -9,8 +9,9 @@ use cocoa::{
foundation::{NSPoint, NSSize, NSString}, foundation::{NSPoint, NSSize, NSString},
}; };
use dispatch::Queue; use dispatch::Queue;
use objc::foundation::is_main_thread;
use objc::rc::autoreleasepool; use objc::rc::autoreleasepool;
use objc::runtime::{BOOL, NO, YES}; use objc::runtime::Bool;
use crate::{ use crate::{
dpi::LogicalSize, dpi::LogicalSize,
@ -55,8 +56,7 @@ pub unsafe fn set_style_mask_async(ns_window: id, ns_view: id, mask: NSWindowSty
}); });
} }
pub unsafe fn set_style_mask_sync(ns_window: id, ns_view: id, mask: NSWindowStyleMask) { pub unsafe fn set_style_mask_sync(ns_window: id, ns_view: id, mask: NSWindowStyleMask) {
let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); if is_main_thread() {
if is_main_thread != NO {
set_style_mask(ns_window, ns_view, mask); set_style_mask(ns_window, ns_view, mask);
} else { } else {
let ns_window = MainThreadSafe(ns_window); let ns_window = MainThreadSafe(ns_window);
@ -97,7 +97,7 @@ pub unsafe fn set_level_async(ns_window: id, level: ffi::NSWindowLevel) {
pub unsafe fn set_ignore_mouse_events(ns_window: id, ignore: bool) { pub unsafe fn set_ignore_mouse_events(ns_window: id, ignore: bool) {
let ns_window = MainThreadSafe(ns_window); let ns_window = MainThreadSafe(ns_window);
Queue::main().exec_async(move || { Queue::main().exec_async(move || {
ns_window.setIgnoresMouseEvents_(if ignore { YES } else { NO }); ns_window.setIgnoresMouseEvents_(Bool::from(ignore).as_raw());
}); });
} }
@ -186,7 +186,7 @@ pub unsafe fn set_maximized_async(
} else { } else {
shared_state_lock.saved_standard_frame() shared_state_lock.saved_standard_frame()
}; };
ns_window.setFrame_display_(new_rect, NO); ns_window.setFrame_display_(new_rect, Bool::NO.as_raw());
} }
} }
}); });
@ -229,7 +229,7 @@ pub unsafe fn set_title_async(ns_window: id, title: String) {
pub unsafe fn close_async(ns_window: IdRef) { pub unsafe fn close_async(ns_window: IdRef) {
let ns_window = MainThreadSafe(ns_window); let ns_window = MainThreadSafe(ns_window);
Queue::main().exec_async(move || { Queue::main().exec_async(move || {
autoreleasepool(move || { autoreleasepool(move |_| {
ns_window.close(); ns_window.close();
}); });
}); });

View file

@ -3,7 +3,7 @@ use cocoa::{
base::{id, nil}, base::{id, nil},
foundation::{NSDictionary, NSPoint, NSString}, foundation::{NSDictionary, NSPoint, NSString},
}; };
use objc::{runtime::Sel, runtime::NO}; use objc::runtime::Sel;
use std::cell::RefCell; use std::cell::RefCell;
use crate::window::CursorIcon; use crate::window::CursorIcon;
@ -147,10 +147,11 @@ pub unsafe fn invisible_cursor() -> id {
CURSOR_OBJECT.with(|cursor_obj| { CURSOR_OBJECT.with(|cursor_obj| {
if *cursor_obj.borrow() == nil { if *cursor_obj.borrow() == nil {
// Create a cursor from `CURSOR_BYTES` // Create a cursor from `CURSOR_BYTES`
let cursor_data: id = msg_send![class!(NSData), let cursor_data: id = msg_send![
dataWithBytesNoCopy:CURSOR_BYTES as *const [u8] class!(NSData),
length:CURSOR_BYTES.len() dataWithBytesNoCopy: CURSOR_BYTES.as_ptr(),
freeWhenDone:NO length: CURSOR_BYTES.len(),
freeWhenDone: false,
]; ];
let ns_image: id = msg_send![class!(NSImage), alloc]; let ns_image: id = msg_send![class!(NSImage), alloc];

View file

@ -9,10 +9,11 @@ use std::os::raw::c_uchar;
use cocoa::{ use cocoa::{
appkit::{CGFloat, NSApp, NSWindowStyleMask}, appkit::{CGFloat, NSApp, NSWindowStyleMask},
base::{id, nil}, base::{id, nil},
foundation::{NSPoint, NSRect, NSString, NSUInteger}, foundation::{NSPoint, NSRect, NSString},
}; };
use core_graphics::display::CGDisplay; use core_graphics::display::CGDisplay;
use objc::runtime::{Class, Object, BOOL, NO}; use objc::foundation::{NSRange, NSUInteger};
use objc::runtime::{Class, Object};
use crate::dpi::LogicalPosition; use crate::dpi::LogicalPosition;
use crate::platform_impl::platform::ffi; use crate::platform_impl::platform::ffi;
@ -28,7 +29,7 @@ where
bitset & flag == flag bitset & flag == flag
} }
pub const EMPTY_RANGE: ffi::NSRange = ffi::NSRange { pub const EMPTY_RANGE: NSRange = NSRange {
location: ffi::NSNotFound as NSUInteger, location: ffi::NSNotFound as NSUInteger,
length: 0, length: 0,
}; };
@ -172,8 +173,8 @@ pub unsafe fn toggle_style_mask(window: id, view: id, mask: NSWindowStyleMask, o
/// ///
/// Safety: Assumes that `string` is an instance of `NSAttributedString` or `NSString` /// Safety: Assumes that `string` is an instance of `NSAttributedString` or `NSString`
pub unsafe fn id_to_string_lossy(string: id) -> String { pub unsafe fn id_to_string_lossy(string: id) -> String {
let has_attr: BOOL = msg_send![string, isKindOfClass: class!(NSAttributedString)]; let has_attr = msg_send![string, isKindOfClass: class!(NSAttributedString)];
let characters = if has_attr != NO { let characters = if has_attr {
// This is a *mut NSAttributedString // This is a *mut NSAttributedString
msg_send![string, string] msg_send![string, string]
} else { } else {

View file

@ -12,11 +12,12 @@ use std::{
use cocoa::{ use cocoa::{
appkit::{NSApp, NSEvent, NSEventModifierFlags, NSEventPhase, NSView, NSWindow}, appkit::{NSApp, NSEvent, NSEventModifierFlags, NSEventPhase, NSView, NSWindow},
base::{id, nil}, base::{id, nil},
foundation::{NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger}, foundation::{NSPoint, NSRect, NSSize, NSString},
}; };
use objc::{ use objc::{
declare::ClassDecl, declare::ClassBuilder,
runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES}, foundation::{NSInteger, NSRange, NSUInteger},
runtime::{Bool, Class, Object, Protocol, Sel},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -124,7 +125,7 @@ pub fn new_view(ns_window: id) -> (IdRef, Weak<Mutex<CursorState>>) {
} }
pub unsafe fn set_ime_position(ns_view: id, position: LogicalPosition<f64>) { pub unsafe fn set_ime_position(ns_view: id, position: LogicalPosition<f64>) {
let state_ptr: *mut c_void = *(*ns_view).get_mut_ivar("winitState"); let state_ptr: *mut c_void = *(*ns_view).ivar_mut("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
state.ime_position = position; state.ime_position = position;
let input_context: id = msg_send![ns_view, inputContext]; let input_context: id = msg_send![ns_view, inputContext];
@ -132,7 +133,7 @@ pub unsafe fn set_ime_position(ns_view: id, position: LogicalPosition<f64>) {
} }
pub unsafe fn set_ime_allowed(ns_view: id, ime_allowed: bool) { pub unsafe fn set_ime_allowed(ns_view: id, ime_allowed: bool) {
let state_ptr: *mut c_void = *(*ns_view).get_mut_ivar("winitState"); let state_ptr: *mut c_void = *(*ns_view).ivar_mut("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
if state.ime_allowed == ime_allowed { if state.ime_allowed == ime_allowed {
return; return;
@ -141,7 +142,7 @@ pub unsafe fn set_ime_allowed(ns_view: id, ime_allowed: bool) {
if state.ime_allowed { if state.ime_allowed {
return; return;
} }
let marked_text_ref: &mut id = (*ns_view).get_mut_ivar("markedText"); let marked_text_ref: &mut id = (*ns_view).ivar_mut("markedText");
// Clear markedText // Clear markedText
let _: () = msg_send![*marked_text_ref, release]; let _: () = msg_send![*marked_text_ref, release];
@ -164,170 +165,135 @@ unsafe impl Sync for ViewClass {}
static VIEW_CLASS: Lazy<ViewClass> = Lazy::new(|| unsafe { static VIEW_CLASS: Lazy<ViewClass> = Lazy::new(|| unsafe {
let superclass = class!(NSView); let superclass = class!(NSView);
let mut decl = ClassDecl::new("WinitView", superclass).unwrap(); let mut decl = ClassBuilder::new("WinitView", superclass).unwrap();
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _));
decl.add_method( decl.add_method(
sel!(initWithWinit:), sel!(initWithWinit:),
init_with_winit as extern "C" fn(&Object, Sel, *mut c_void) -> id, init_with_winit as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(viewDidMoveToWindow), sel!(viewDidMoveToWindow),
view_did_move_to_window as extern "C" fn(&Object, Sel), view_did_move_to_window as extern "C" fn(_, _),
);
decl.add_method(
sel!(drawRect:),
draw_rect as extern "C" fn(&Object, Sel, NSRect),
); );
decl.add_method(sel!(drawRect:), draw_rect as extern "C" fn(_, _, _));
decl.add_method( decl.add_method(
sel!(acceptsFirstResponder), sel!(acceptsFirstResponder),
accepts_first_responder as extern "C" fn(&Object, Sel) -> BOOL, accepts_first_responder as extern "C" fn(_, _) -> _,
);
decl.add_method(
sel!(touchBar),
touch_bar as extern "C" fn(&Object, Sel) -> BOOL,
); );
decl.add_method(sel!(touchBar), touch_bar as extern "C" fn(_, _) -> _);
decl.add_method( decl.add_method(
sel!(resetCursorRects), sel!(resetCursorRects),
reset_cursor_rects as extern "C" fn(&Object, Sel), reset_cursor_rects as extern "C" fn(_, _),
); );
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// NSTextInputClient // NSTextInputClient
decl.add_method( decl.add_method(
sel!(hasMarkedText), sel!(hasMarkedText),
has_marked_text as extern "C" fn(&Object, Sel) -> BOOL, has_marked_text as extern "C" fn(_, _) -> _,
);
decl.add_method(
sel!(markedRange),
marked_range as extern "C" fn(&Object, Sel) -> NSRange,
); );
decl.add_method(sel!(markedRange), marked_range as extern "C" fn(_, _) -> _);
decl.add_method( decl.add_method(
sel!(selectedRange), sel!(selectedRange),
selected_range as extern "C" fn(&Object, Sel) -> NSRange, selected_range as extern "C" fn(_, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(setMarkedText:selectedRange:replacementRange:), sel!(setMarkedText:selectedRange:replacementRange:),
set_marked_text as extern "C" fn(&mut Object, Sel, id, NSRange, NSRange), set_marked_text as extern "C" fn(_, _, _, _, _),
); );
decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel)); decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(_, _));
decl.add_method( decl.add_method(
sel!(validAttributesForMarkedText), sel!(validAttributesForMarkedText),
valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id, valid_attributes_for_marked_text as extern "C" fn(_, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(attributedSubstringForProposedRange:actualRange:), sel!(attributedSubstringForProposedRange:actualRange:),
attributed_substring_for_proposed_range attributed_substring_for_proposed_range as extern "C" fn(_, _, _, _) -> _,
as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
); );
decl.add_method( decl.add_method(
sel!(insertText:replacementRange:), sel!(insertText:replacementRange:),
insert_text as extern "C" fn(&Object, Sel, id, NSRange), insert_text as extern "C" fn(_, _, _, _),
); );
decl.add_method( decl.add_method(
sel!(characterIndexForPoint:), sel!(characterIndexForPoint:),
character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> NSUInteger, character_index_for_point as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(firstRectForCharacterRange:actualRange:), sel!(firstRectForCharacterRange:actualRange:),
first_rect_for_character_range first_rect_for_character_range as extern "C" fn(_, _, _, _) -> _,
as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> NSRect,
); );
decl.add_method( decl.add_method(
sel!(doCommandBySelector:), sel!(doCommandBySelector:),
do_command_by_selector as extern "C" fn(&Object, Sel, Sel), do_command_by_selector as extern "C" fn(_, _, _),
); );
// ------------------------------------------------------------------ // ------------------------------------------------------------------
decl.add_method(sel!(keyDown:), key_down as extern "C" fn(&Object, Sel, id)); decl.add_method(sel!(keyDown:), key_down as extern "C" fn(_, _, _));
decl.add_method(sel!(keyUp:), key_up as extern "C" fn(&Object, Sel, id)); decl.add_method(sel!(keyUp:), key_up as extern "C" fn(_, _, _));
decl.add_method( decl.add_method(sel!(flagsChanged:), flags_changed as extern "C" fn(_, _, _));
sel!(flagsChanged:), decl.add_method(sel!(insertTab:), insert_tab as extern "C" fn(_, _, _));
flags_changed as extern "C" fn(&Object, Sel, id),
);
decl.add_method(
sel!(insertTab:),
insert_tab as extern "C" fn(&Object, Sel, id),
);
decl.add_method( decl.add_method(
sel!(insertBackTab:), sel!(insertBackTab:),
insert_back_tab as extern "C" fn(&Object, Sel, id), insert_back_tab as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(sel!(mouseDown:), mouse_down as extern "C" fn(_, _, _));
sel!(mouseDown:), decl.add_method(sel!(mouseUp:), mouse_up as extern "C" fn(_, _, _));
mouse_down as extern "C" fn(&Object, Sel, id),
);
decl.add_method(sel!(mouseUp:), mouse_up as extern "C" fn(&Object, Sel, id));
decl.add_method( decl.add_method(
sel!(rightMouseDown:), sel!(rightMouseDown:),
right_mouse_down as extern "C" fn(&Object, Sel, id), right_mouse_down as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(rightMouseUp:), sel!(rightMouseUp:),
right_mouse_up as extern "C" fn(&Object, Sel, id), right_mouse_up as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(otherMouseDown:), sel!(otherMouseDown:),
other_mouse_down as extern "C" fn(&Object, Sel, id), other_mouse_down as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(otherMouseUp:), sel!(otherMouseUp:),
other_mouse_up as extern "C" fn(&Object, Sel, id), other_mouse_up as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(mouseMoved:),
mouse_moved as extern "C" fn(&Object, Sel, id),
);
decl.add_method(
sel!(mouseDragged:),
mouse_dragged as extern "C" fn(&Object, Sel, id),
); );
decl.add_method(sel!(mouseMoved:), mouse_moved as extern "C" fn(_, _, _));
decl.add_method(sel!(mouseDragged:), mouse_dragged as extern "C" fn(_, _, _));
decl.add_method( decl.add_method(
sel!(rightMouseDragged:), sel!(rightMouseDragged:),
right_mouse_dragged as extern "C" fn(&Object, Sel, id), right_mouse_dragged as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(otherMouseDragged:), sel!(otherMouseDragged:),
other_mouse_dragged as extern "C" fn(&Object, Sel, id), other_mouse_dragged as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(mouseEntered:),
mouse_entered as extern "C" fn(&Object, Sel, id),
);
decl.add_method(
sel!(mouseExited:),
mouse_exited as extern "C" fn(&Object, Sel, id),
);
decl.add_method(
sel!(scrollWheel:),
scroll_wheel as extern "C" fn(&Object, Sel, id),
); );
decl.add_method(sel!(mouseEntered:), mouse_entered as extern "C" fn(_, _, _));
decl.add_method(sel!(mouseExited:), mouse_exited as extern "C" fn(_, _, _));
decl.add_method(sel!(scrollWheel:), scroll_wheel as extern "C" fn(_, _, _));
decl.add_method( decl.add_method(
sel!(magnifyWithEvent:), sel!(magnifyWithEvent:),
magnify_with_event as extern "C" fn(&Object, Sel, id), magnify_with_event as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(rotateWithEvent:), sel!(rotateWithEvent:),
rotate_with_event as extern "C" fn(&Object, Sel, id), rotate_with_event as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(pressureChangeWithEvent:), sel!(pressureChangeWithEvent:),
pressure_change_with_event as extern "C" fn(&Object, Sel, id), pressure_change_with_event as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(_wantsKeyDownForEvent:), sel!(_wantsKeyDownForEvent:),
wants_key_down_for_event as extern "C" fn(&Object, Sel, id) -> BOOL, wants_key_down_for_event as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(cancelOperation:), sel!(cancelOperation:),
cancel_operation as extern "C" fn(&Object, Sel, id), cancel_operation as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(frameDidChange:), sel!(frameDidChange:),
frame_did_change as extern "C" fn(&Object, Sel, id), frame_did_change as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(acceptsFirstMouse:), sel!(acceptsFirstMouse:),
accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL, accepts_first_mouse as extern "C" fn(_, _, _) -> _,
); );
decl.add_ivar::<*mut c_void>("winitState"); decl.add_ivar::<*mut c_void>("winitState");
decl.add_ivar::<id>("markedText"); decl.add_ivar::<id>("markedText");
@ -338,9 +304,9 @@ static VIEW_CLASS: Lazy<ViewClass> = Lazy::new(|| unsafe {
extern "C" fn dealloc(this: &Object, _sel: Sel) { extern "C" fn dealloc(this: &Object, _sel: Sel) {
unsafe { unsafe {
let marked_text: id = *this.get_ivar("markedText"); let marked_text: id = *this.ivar("markedText");
let _: () = msg_send![marked_text, release]; let _: () = msg_send![marked_text, release];
let state: *mut c_void = *this.get_ivar("winitState"); let state: *mut c_void = *this.ivar("winitState");
drop(Box::from_raw(state as *mut ViewState)); drop(Box::from_raw(state as *mut ViewState));
} }
} }
@ -353,7 +319,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
let marked_text = let marked_text =
<id as NSMutableAttributedString>::init(NSMutableAttributedString::alloc(nil)); <id as NSMutableAttributedString>::init(NSMutableAttributedString::alloc(nil));
(*this).set_ivar("markedText", marked_text); (*this).set_ivar("markedText", marked_text);
let _: () = msg_send![this, setPostsFrameChangedNotifications: YES]; let _: () = msg_send![this, setPostsFrameChangedNotifications: true];
let notification_center: &Object = let notification_center: &Object =
msg_send![class!(NSNotificationCenter), defaultCenter]; msg_send![class!(NSNotificationCenter), defaultCenter];
@ -364,7 +330,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
notification_center, notification_center,
addObserver: this addObserver: this
selector: sel!(frameDidChange:) selector: sel!(frameDidChange:)
name: frame_did_change_notification_name name: *frame_did_change_notification_name
object: this object: this
]; ];
@ -378,7 +344,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
extern "C" fn view_did_move_to_window(this: &Object, _sel: Sel) { extern "C" fn view_did_move_to_window(this: &Object, _sel: Sel) {
trace_scope!("viewDidMoveToWindow"); trace_scope!("viewDidMoveToWindow");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
if let Some(tracking_rect) = state.tracking_rect.take() { if let Some(tracking_rect) = state.tracking_rect.take() {
@ -386,11 +352,12 @@ extern "C" fn view_did_move_to_window(this: &Object, _sel: Sel) {
} }
let rect: NSRect = msg_send![this, visibleRect]; let rect: NSRect = msg_send![this, visibleRect];
let tracking_rect: NSInteger = msg_send![this, let tracking_rect: NSInteger = msg_send![
addTrackingRect:rect this,
owner:this addTrackingRect: rect,
userData:ptr::null_mut::<c_void>() owner: this,
assumeInside:NO userData: ptr::null_mut::<c_void>(),
assumeInside: false
]; ];
state.tracking_rect = Some(tracking_rect); state.tracking_rect = Some(tracking_rect);
} }
@ -399,7 +366,7 @@ extern "C" fn view_did_move_to_window(this: &Object, _sel: Sel) {
extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) { extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) {
trace_scope!("frameDidChange:"); trace_scope!("frameDidChange:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
if let Some(tracking_rect) = state.tracking_rect.take() { if let Some(tracking_rect) = state.tracking_rect.take() {
@ -407,11 +374,12 @@ extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) {
} }
let rect: NSRect = msg_send![this, visibleRect]; let rect: NSRect = msg_send![this, visibleRect];
let tracking_rect: NSInteger = msg_send![this, let tracking_rect: NSInteger = msg_send![
addTrackingRect:rect this,
owner:this addTrackingRect: rect,
userData:ptr::null_mut::<c_void>() owner: this,
assumeInside:NO userData: ptr::null_mut::<c_void>(),
assumeInside: false,
]; ];
state.tracking_rect = Some(tracking_rect); state.tracking_rect = Some(tracking_rect);
@ -430,7 +398,7 @@ extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) {
extern "C" fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) { extern "C" fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) {
trace_scope!("drawRect:"); trace_scope!("drawRect:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
AppState::handle_redraw(WindowId(get_window_id(state.ns_window))); AppState::handle_redraw(WindowId(get_window_id(state.ns_window)));
@ -440,23 +408,23 @@ extern "C" fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) {
} }
} }
extern "C" fn accepts_first_responder(_this: &Object, _sel: Sel) -> BOOL { extern "C" fn accepts_first_responder(_this: &Object, _sel: Sel) -> Bool {
trace_scope!("acceptsFirstResponder"); trace_scope!("acceptsFirstResponder");
YES Bool::YES
} }
// This is necessary to prevent a beefy terminal error on MacBook Pros: // This is necessary to prevent a beefy terminal error on MacBook Pros:
// IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem // IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem
// TODO: Add an API extension for using `NSTouchBar` // TODO: Add an API extension for using `NSTouchBar`
extern "C" fn touch_bar(_this: &Object, _sel: Sel) -> BOOL { extern "C" fn touch_bar(_this: &Object, _sel: Sel) -> Bool {
trace_scope!("touchBar"); trace_scope!("touchBar");
NO Bool::NO
} }
extern "C" fn reset_cursor_rects(this: &Object, _sel: Sel) { extern "C" fn reset_cursor_rects(this: &Object, _sel: Sel) {
trace_scope!("resetCursorRects"); trace_scope!("resetCursorRects");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let bounds: NSRect = msg_send![this, bounds]; let bounds: NSRect = msg_send![this, bounds];
@ -473,18 +441,18 @@ extern "C" fn reset_cursor_rects(this: &Object, _sel: Sel) {
} }
} }
extern "C" fn has_marked_text(this: &Object, _sel: Sel) -> BOOL { extern "C" fn has_marked_text(this: &Object, _sel: Sel) -> Bool {
trace_scope!("hasMarkedText"); trace_scope!("hasMarkedText");
unsafe { unsafe {
let marked_text: id = *this.get_ivar("markedText"); let marked_text: id = *this.ivar("markedText");
(marked_text.length() > 0) as BOOL Bool::new(marked_text.length() > 0)
} }
} }
extern "C" fn marked_range(this: &Object, _sel: Sel) -> NSRange { extern "C" fn marked_range(this: &Object, _sel: Sel) -> NSRange {
trace_scope!("markedRange"); trace_scope!("markedRange");
unsafe { unsafe {
let marked_text: id = *this.get_ivar("markedText"); let marked_text: id = *this.ivar("markedText");
let length = marked_text.length(); let length = marked_text.length();
if length > 0 { if length > 0 {
NSRange::new(0, length) NSRange::new(0, length)
@ -516,13 +484,13 @@ extern "C" fn set_marked_text(
trace_scope!("setMarkedText:selectedRange:replacementRange:"); trace_scope!("setMarkedText:selectedRange:replacementRange:");
unsafe { unsafe {
// Get pre-edit text // Get pre-edit text
let marked_text_ref: &mut id = this.get_mut_ivar("markedText"); let marked_text_ref: &mut id = this.ivar_mut("markedText");
// Update markedText // Update markedText
let _: () = msg_send![(*marked_text_ref), release]; let _: () = msg_send![*marked_text_ref, release];
let marked_text = NSMutableAttributedString::alloc(nil); let marked_text = NSMutableAttributedString::alloc(nil);
let has_attr: BOOL = msg_send![string, isKindOfClass: class!(NSAttributedString)]; let has_attr = msg_send![string, isKindOfClass: class!(NSAttributedString)];
if has_attr != NO { if has_attr {
marked_text.initWithAttributedString(string); marked_text.initWithAttributedString(string);
} else { } else {
marked_text.initWithString(string); marked_text.initWithString(string);
@ -530,7 +498,7 @@ extern "C" fn set_marked_text(
*marked_text_ref = marked_text; *marked_text_ref = marked_text;
// Update ViewState with new marked text // Update ViewState with new marked text
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let preedit_string = id_to_string_lossy(string); let preedit_string = id_to_string_lossy(string);
@ -568,7 +536,7 @@ extern "C" fn set_marked_text(
extern "C" fn unmark_text(this: &Object, _sel: Sel) { extern "C" fn unmark_text(this: &Object, _sel: Sel) {
trace_scope!("unmarkText"); trace_scope!("unmarkText");
unsafe { unsafe {
let marked_text: id = *this.get_ivar("markedText"); let marked_text: id = *this.ivar("markedText");
let mutable_string = marked_text.mutableString(); let mutable_string = marked_text.mutableString();
let s: id = msg_send![class!(NSString), new]; let s: id = msg_send![class!(NSString), new];
let _: () = msg_send![mutable_string, setString: s]; let _: () = msg_send![mutable_string, setString: s];
@ -576,7 +544,7 @@ extern "C" fn unmark_text(this: &Object, _sel: Sel) {
let input_context: id = msg_send![this, inputContext]; let input_context: id = msg_send![this, inputContext];
let _: () = msg_send![input_context, discardMarkedText]; let _: () = msg_send![input_context, discardMarkedText];
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent { AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent {
window_id: WindowId(get_window_id(state.ns_window)), window_id: WindowId(get_window_id(state.ns_window)),
@ -619,7 +587,7 @@ extern "C" fn first_rect_for_character_range(
) -> NSRect { ) -> NSRect {
trace_scope!("firstRectForCharacterRange:actualRange:"); trace_scope!("firstRectForCharacterRange:actualRange:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let content_rect = let content_rect =
NSWindow::contentRectForFrameRect_(state.ns_window, NSWindow::frame(state.ns_window)); NSWindow::contentRectForFrameRect_(state.ns_window, NSWindow::frame(state.ns_window));
@ -638,7 +606,7 @@ extern "C" fn first_rect_for_character_range(
extern "C" fn insert_text(this: &Object, _sel: Sel, string: id, _replacement_range: NSRange) { extern "C" fn insert_text(this: &Object, _sel: Sel, string: id, _replacement_range: NSRange) {
trace_scope!("insertText:replacementRange:"); trace_scope!("insertText:replacementRange:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let string = id_to_string_lossy(string); let string = id_to_string_lossy(string);
@ -663,7 +631,7 @@ extern "C" fn do_command_by_selector(this: &Object, _sel: Sel, _command: Sel) {
// Basically, we're sent this message whenever a keyboard event that doesn't generate a "human // Basically, we're sent this message whenever a keyboard event that doesn't generate a "human
// readable" character happens, i.e. newlines, tabs, and Ctrl+C. // readable" character happens, i.e. newlines, tabs, and Ctrl+C.
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
// We shouldn't forward any character from just commited text, since we'll end up sending // We shouldn't forward any character from just commited text, since we'll end up sending
@ -675,8 +643,8 @@ extern "C" fn do_command_by_selector(this: &Object, _sel: Sel, _command: Sel) {
state.forward_key_to_app = true; state.forward_key_to_app = true;
let has_marked_text: BOOL = msg_send![this, hasMarkedText]; let has_marked_text = msg_send![this, hasMarkedText];
if has_marked_text == NO && state.ime_state == ImeState::Preedit { if has_marked_text && state.ime_state == ImeState::Preedit {
// Leave preedit so that we also report the keyup for this key // Leave preedit so that we also report the keyup for this key
state.ime_state = ImeState::Enabled; state.ime_state = ImeState::Enabled;
} }
@ -754,7 +722,7 @@ fn update_potentially_stale_modifiers(state: &mut ViewState, event: id) {
extern "C" fn key_down(this: &Object, _sel: Sel, event: id) { extern "C" fn key_down(this: &Object, _sel: Sel, event: id) {
trace_scope!("keyDown:"); trace_scope!("keyDown:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let window_id = WindowId(get_window_id(state.ns_window)); let window_id = WindowId(get_window_id(state.ns_window));
@ -837,7 +805,7 @@ extern "C" fn key_down(this: &Object, _sel: Sel, event: id) {
extern "C" fn key_up(this: &Object, _sel: Sel, event: id) { extern "C" fn key_up(this: &Object, _sel: Sel, event: id) {
trace_scope!("keyUp:"); trace_scope!("keyUp:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let scancode = get_scancode(event) as u32; let scancode = get_scancode(event) as u32;
@ -870,7 +838,7 @@ extern "C" fn key_up(this: &Object, _sel: Sel, event: id) {
extern "C" fn flags_changed(this: &Object, _sel: Sel, event: id) { extern "C" fn flags_changed(this: &Object, _sel: Sel, event: id) {
trace_scope!("flagsChanged:"); trace_scope!("flagsChanged:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let mut events = VecDeque::with_capacity(4); let mut events = VecDeque::with_capacity(4);
@ -956,7 +924,7 @@ extern "C" fn insert_back_tab(this: &Object, _sel: Sel, _sender: id) {
extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) { extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
trace_scope!("cancelOperation:"); trace_scope!("cancelOperation:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let scancode = 0x2f; let scancode = 0x2f;
@ -988,7 +956,7 @@ extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: ElementState) { fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: ElementState) {
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
update_potentially_stale_modifiers(state, event); update_potentially_stale_modifiers(state, event);
@ -1045,7 +1013,7 @@ extern "C" fn other_mouse_up(this: &Object, _sel: Sel, event: id) {
fn mouse_motion(this: &Object, event: id) { fn mouse_motion(this: &Object, event: id) {
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
// We have to do this to have access to the `NSView` trait... // We have to do this to have access to the `NSView` trait...
@ -1107,7 +1075,7 @@ extern "C" fn other_mouse_dragged(this: &Object, _sel: Sel, event: id) {
extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) { extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) {
trace_scope!("mouseEntered:"); trace_scope!("mouseEntered:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let enter_event = Event::WindowEvent { let enter_event = Event::WindowEvent {
@ -1124,7 +1092,7 @@ extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) {
extern "C" fn mouse_exited(this: &Object, _sel: Sel, _event: id) { extern "C" fn mouse_exited(this: &Object, _sel: Sel, _event: id) {
trace_scope!("mouseExited:"); trace_scope!("mouseExited:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let window_event = Event::WindowEvent { let window_event = Event::WindowEvent {
@ -1144,12 +1112,12 @@ extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) {
mouse_motion(this, event); mouse_motion(this, event);
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let delta = { let delta = {
let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY()); let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY());
if event.hasPreciseScrollingDeltas() == YES { if Bool::from_raw(event.hasPreciseScrollingDeltas()).as_bool() {
let delta = LogicalPosition::new(x, y).to_physical(state.get_scale_factor()); let delta = LogicalPosition::new(x, y).to_physical(state.get_scale_factor());
MouseScrollDelta::PixelDelta(delta) MouseScrollDelta::PixelDelta(delta)
} else { } else {
@ -1184,7 +1152,7 @@ extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) {
event: DeviceEvent::MouseWheel { delta }, event: DeviceEvent::MouseWheel { delta },
}; };
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
update_potentially_stale_modifiers(state, event); update_potentially_stale_modifiers(state, event);
@ -1208,7 +1176,7 @@ extern "C" fn magnify_with_event(this: &Object, _sel: Sel, event: id) {
trace_scope!("magnifyWithEvent:"); trace_scope!("magnifyWithEvent:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let delta = event.magnification(); let delta = event.magnification();
@ -1237,7 +1205,7 @@ extern "C" fn rotate_with_event(this: &Object, _sel: Sel, event: id) {
trace_scope!("rotateWithEvent:"); trace_scope!("rotateWithEvent:");
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let delta = event.rotation(); let delta = event.rotation();
@ -1268,7 +1236,7 @@ extern "C" fn pressure_change_with_event(this: &Object, _sel: Sel, event: id) {
mouse_motion(this, event); mouse_motion(this, event);
unsafe { unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
let state = &mut *(state_ptr as *mut ViewState); let state = &mut *(state_ptr as *mut ViewState);
let pressure = event.pressure(); let pressure = event.pressure();
@ -1290,12 +1258,12 @@ extern "C" fn pressure_change_with_event(this: &Object, _sel: Sel, event: id) {
// Allows us to receive Ctrl-Tab and Ctrl-Esc. // Allows us to receive Ctrl-Tab and Ctrl-Esc.
// Note that this *doesn't* help with any missing Cmd inputs. // Note that this *doesn't* help with any missing Cmd inputs.
// https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816 // https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816
extern "C" fn wants_key_down_for_event(_this: &Object, _sel: Sel, _event: id) -> BOOL { extern "C" fn wants_key_down_for_event(_this: &Object, _sel: Sel, _event: id) -> Bool {
trace_scope!("_wantsKeyDownForEvent:"); trace_scope!("_wantsKeyDownForEvent:");
YES Bool::YES
} }
extern "C" fn accepts_first_mouse(_this: &Object, _sel: Sel, _event: id) -> BOOL { extern "C" fn accepts_first_mouse(_this: &Object, _sel: Sel, _event: id) -> Bool {
trace_scope!("acceptsFirstMouse:"); trace_scope!("acceptsFirstMouse:");
YES Bool::YES
} }

View file

@ -42,13 +42,14 @@ use cocoa::{
NSRequestUserAttentionType, NSScreen, NSView, NSWindow, NSWindowButton, NSWindowStyleMask, NSRequestUserAttentionType, NSScreen, NSView, NSWindow, NSWindowButton, NSWindowStyleMask,
}, },
base::{id, nil}, base::{id, nil},
foundation::{NSDictionary, NSPoint, NSRect, NSSize, NSUInteger}, foundation::{NSDictionary, NSPoint, NSRect, NSSize},
}; };
use core_graphics::display::{CGDisplay, CGDisplayMode}; use core_graphics::display::{CGDisplay, CGDisplayMode};
use objc::{ use objc::{
declare::ClassDecl, declare::ClassBuilder,
foundation::{is_main_thread, NSUInteger},
rc::autoreleasepool, rc::autoreleasepool,
runtime::{Class, Object, Sel, BOOL, NO, YES}, runtime::{Bool, Class, Object, Sel},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -119,9 +120,9 @@ unsafe fn create_view(
// macos 10.14 and `true` after 10.15, we should set it to `YES` or `NO` to avoid // macos 10.14 and `true` after 10.15, we should set it to `YES` or `NO` to avoid
// always the default system value in favour of the user's code // always the default system value in favour of the user's code
if !pl_attribs.disallow_hidpi { if !pl_attribs.disallow_hidpi {
ns_view.setWantsBestResolutionOpenGLSurface_(YES); ns_view.setWantsBestResolutionOpenGLSurface_(Bool::YES.as_raw());
} else { } else {
ns_view.setWantsBestResolutionOpenGLSurface_(NO); ns_view.setWantsBestResolutionOpenGLSurface_(Bool::NO.as_raw());
} }
// On Mojave, views automatically become layer-backed shortly after being added to // On Mojave, views automatically become layer-backed shortly after being added to
@ -130,7 +131,7 @@ unsafe fn create_view(
// explicitly make the view layer-backed up front so that AppKit doesn't do it // explicitly make the view layer-backed up front so that AppKit doesn't do it
// itself and break the association with its context. // itself and break the association with its context.
if f64::floor(appkit::NSAppKitVersionNumber) > appkit::NSAppKitVersionNumber10_12 { if f64::floor(appkit::NSAppKitVersionNumber) > appkit::NSAppKitVersionNumber10_12 {
ns_view.setWantsLayer(YES); ns_view.setWantsLayer(Bool::YES.as_raw());
} }
(ns_view, cursor_state) (ns_view, cursor_state)
@ -141,7 +142,7 @@ fn create_window(
attrs: &WindowAttributes, attrs: &WindowAttributes,
pl_attrs: &PlatformSpecificWindowBuilderAttributes, pl_attrs: &PlatformSpecificWindowBuilderAttributes,
) -> Option<IdRef> { ) -> Option<IdRef> {
autoreleasepool(|| unsafe { autoreleasepool(|_| unsafe {
let screen = match attrs.fullscreen { let screen = match attrs.fullscreen {
Some(Fullscreen::Borderless(Some(RootMonitorHandle { inner: ref monitor }))) Some(Fullscreen::Borderless(Some(RootMonitorHandle { inner: ref monitor })))
| Some(Fullscreen::Exclusive(RootVideoMode { | Some(Fullscreen::Exclusive(RootVideoMode {
@ -208,17 +209,17 @@ fn create_window(
frame, frame,
masks, masks,
appkit::NSBackingStoreBuffered, appkit::NSBackingStoreBuffered,
NO, Bool::NO.as_raw(),
)); ));
ns_window.non_nil().map(|ns_window| { ns_window.non_nil().map(|ns_window| {
let title = util::ns_string_id_ref(&attrs.title); let title = util::ns_string_id_ref(&attrs.title);
ns_window.setReleasedWhenClosed_(NO); ns_window.setReleasedWhenClosed_(Bool::NO.as_raw());
ns_window.setTitle_(*title); ns_window.setTitle_(*title);
ns_window.setAcceptsMouseMovedEvents_(YES); ns_window.setAcceptsMouseMovedEvents_(Bool::YES.as_raw());
if pl_attrs.titlebar_transparent { if pl_attrs.titlebar_transparent {
ns_window.setTitlebarAppearsTransparent_(YES); ns_window.setTitlebarAppearsTransparent_(Bool::YES.as_raw());
} }
if pl_attrs.title_hidden { if pl_attrs.title_hidden {
ns_window.setTitleVisibility_(appkit::NSWindowTitleVisibility::NSWindowTitleHidden); ns_window.setTitleVisibility_(appkit::NSWindowTitleVisibility::NSWindowTitleHidden);
@ -231,18 +232,15 @@ fn create_window(
NSWindowButton::NSWindowZoomButton, NSWindowButton::NSWindowZoomButton,
] { ] {
let button = ns_window.standardWindowButton_(*titlebar_button); let button = ns_window.standardWindowButton_(*titlebar_button);
let _: () = msg_send![button, setHidden: YES]; let _: () = msg_send![button, setHidden: true];
} }
} }
if pl_attrs.movable_by_window_background { if pl_attrs.movable_by_window_background {
ns_window.setMovableByWindowBackground_(YES); ns_window.setMovableByWindowBackground_(Bool::YES.as_raw());
} }
if attrs.always_on_top { if attrs.always_on_top {
let _: () = msg_send![ let _: () = msg_send![*ns_window, setLevel: ffi::kCGFloatingWindowLevelKey];
*ns_window,
setLevel: ffi::NSWindowLevel::NSFloatingWindowLevel
];
} }
if let Some(increments) = pl_attrs.resize_increments { if let Some(increments) = pl_attrs.resize_increments {
@ -254,7 +252,7 @@ fn create_window(
} }
if !pl_attrs.has_shadow { if !pl_attrs.has_shadow {
ns_window.setHasShadow_(NO); ns_window.setHasShadow_(Bool::NO.as_raw());
} }
if attrs.position.is_none() { if attrs.position.is_none() {
ns_window.center(); ns_window.center();
@ -270,25 +268,25 @@ unsafe impl Sync for WindowClass {}
static WINDOW_CLASS: Lazy<WindowClass> = Lazy::new(|| unsafe { static WINDOW_CLASS: Lazy<WindowClass> = Lazy::new(|| unsafe {
let window_superclass = class!(NSWindow); let window_superclass = class!(NSWindow);
let mut decl = ClassDecl::new("WinitWindow", window_superclass).unwrap(); let mut decl = ClassBuilder::new("WinitWindow", window_superclass).unwrap();
pub extern "C" fn can_become_main_window(_: &Object, _: Sel) -> BOOL { pub extern "C" fn can_become_main_window(_: &Object, _: Sel) -> Bool {
trace_scope!("canBecomeMainWindow"); trace_scope!("canBecomeMainWindow");
YES Bool::YES
} }
pub extern "C" fn can_become_key_window(_: &Object, _: Sel) -> BOOL { pub extern "C" fn can_become_key_window(_: &Object, _: Sel) -> Bool {
trace_scope!("canBecomeKeyWindow"); trace_scope!("canBecomeKeyWindow");
YES Bool::YES
} }
decl.add_method( decl.add_method(
sel!(canBecomeMainWindow), sel!(canBecomeMainWindow),
can_become_main_window as extern "C" fn(&Object, Sel) -> BOOL, can_become_main_window as extern "C" fn(_, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(canBecomeKeyWindow), sel!(canBecomeKeyWindow),
can_become_key_window as extern "C" fn(&Object, Sel) -> BOOL, can_become_key_window as extern "C" fn(_, _) -> _,
); );
WindowClass(decl.register()) WindowClass(decl.register())
}); });
@ -396,11 +394,8 @@ impl UnownedWindow {
mut win_attribs: WindowAttributes, mut win_attribs: WindowAttributes,
pl_attribs: PlatformSpecificWindowBuilderAttributes, pl_attribs: PlatformSpecificWindowBuilderAttributes,
) -> Result<(Arc<Self>, IdRef), RootOsError> { ) -> Result<(Arc<Self>, IdRef), RootOsError> {
unsafe { if !is_main_thread() {
let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); panic!("Windows can only be created on the main thread on macOS");
if is_main_thread == NO {
panic!("Windows can only be created on the main thread on macOS");
}
} }
trace!("Creating new window"); trace!("Creating new window");
@ -420,7 +415,7 @@ impl UnownedWindow {
unsafe { unsafe {
if win_attribs.transparent { if win_attribs.transparent {
ns_window.setOpaque_(NO); ns_window.setOpaque_(Bool::NO.as_raw());
ns_window.setBackgroundColor_(NSColor::clearColor(nil)); ns_window.setBackgroundColor_(NSColor::clearColor(nil));
} }
@ -519,8 +514,8 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn is_visible(&self) -> Option<bool> { pub fn is_visible(&self) -> Option<bool> {
let is_visible: BOOL = unsafe { msg_send![*self.ns_window, isVisible] }; let is_visible = unsafe { msg_send![*self.ns_window, isVisible] };
Some(is_visible == YES) Some(is_visible)
} }
pub fn request_redraw(&self) { pub fn request_redraw(&self) {
@ -625,8 +620,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn is_resizable(&self) -> bool { pub fn is_resizable(&self) -> bool {
let is_resizable: BOOL = unsafe { msg_send![*self.ns_window, isResizable] }; unsafe { msg_send![*self.ns_window, isResizable] }
is_resizable == YES
} }
pub fn set_cursor_icon(&self, cursor: CursorIcon) { pub fn set_cursor_icon(&self, cursor: CursorIcon) {
@ -726,14 +720,14 @@ impl UnownedWindow {
self.set_style_mask_sync(required); self.set_style_mask_sync(required);
} }
let is_zoomed: BOOL = unsafe { msg_send![*self.ns_window, isZoomed] }; let is_zoomed = unsafe { msg_send![*self.ns_window, isZoomed] };
// Roll back temp styles // Roll back temp styles
if needs_temp_mask { if needs_temp_mask {
self.set_style_mask_async(curr_mask); self.set_style_mask_async(curr_mask);
} }
is_zoomed != NO is_zoomed
} }
fn saved_style(&self, shared_state: &mut SharedState) -> NSWindowStyleMask { fn saved_style(&self, shared_state: &mut SharedState) -> NSWindowStyleMask {
@ -767,8 +761,7 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn set_minimized(&self, minimized: bool) { pub fn set_minimized(&self, minimized: bool) {
let is_minimized: BOOL = unsafe { msg_send![*self.ns_window, isMiniaturized] }; let is_minimized: bool = unsafe { msg_send![*self.ns_window, isMiniaturized] };
let is_minimized: bool = is_minimized == YES;
if is_minimized == minimized { if is_minimized == minimized {
return; return;
} }
@ -998,10 +991,7 @@ impl UnownedWindow {
// Restore the normal window level following the Borderless fullscreen // Restore the normal window level following the Borderless fullscreen
// `CGShieldingWindowLevel() + 1` hack. // `CGShieldingWindowLevel() + 1` hack.
let _: () = msg_send![ let _: () = msg_send![*self.ns_window, setLevel: ffi::kCGBaseWindowLevelKey];
*self.ns_window,
setLevel: ffi::NSWindowLevel::NSNormalWindowLevel
];
}, },
_ => {} _ => {}
}; };
@ -1088,14 +1078,12 @@ impl UnownedWindow {
#[inline] #[inline]
pub fn focus_window(&self) { pub fn focus_window(&self) {
let is_minimized: BOOL = unsafe { msg_send![*self.ns_window, isMiniaturized] }; let is_minimized: bool = unsafe { msg_send![*self.ns_window, isMiniaturized] };
let is_minimized = is_minimized == YES; let is_visible: bool = unsafe { msg_send![*self.ns_window, isVisible] };
let is_visible: BOOL = unsafe { msg_send![*self.ns_window, isVisible] };
let is_visible = is_visible == YES;
if !is_minimized && is_visible { if !is_minimized && is_visible {
unsafe { unsafe {
NSApp().activateIgnoringOtherApps_(YES); NSApp().activateIgnoringOtherApps_(Bool::YES.as_raw());
util::make_key_and_order_front_async(*self.ns_window); util::make_key_and_order_front_async(*self.ns_window);
} }
} }
@ -1223,7 +1211,7 @@ impl WindowExtMacOS for UnownedWindow {
// Set the window frame to the screen frame size // Set the window frame to the screen frame size
let screen = self.ns_window.screen(); let screen = self.ns_window.screen();
let screen_frame = NSScreen::frame(screen); let screen_frame = NSScreen::frame(screen);
NSWindow::setFrame_display_(*self.ns_window, screen_frame, YES); NSWindow::setFrame_display_(*self.ns_window, screen_frame, Bool::YES.as_raw());
// Fullscreen windows can't be resized, minimized, or moved // Fullscreen windows can't be resized, minimized, or moved
util::toggle_style_mask( util::toggle_style_mask(
@ -1238,7 +1226,7 @@ impl WindowExtMacOS for UnownedWindow {
NSWindowStyleMask::NSResizableWindowMask, NSWindowStyleMask::NSResizableWindowMask,
false, false,
); );
NSWindow::setMovable_(*self.ns_window, NO); NSWindow::setMovable_(*self.ns_window, Bool::NO.as_raw());
true true
} else { } else {
@ -1251,8 +1239,8 @@ impl WindowExtMacOS for UnownedWindow {
} }
let frame = shared_state_lock.saved_standard_frame(); let frame = shared_state_lock.saved_standard_frame();
NSWindow::setFrame_display_(*self.ns_window, frame, YES); NSWindow::setFrame_display_(*self.ns_window, frame, Bool::YES.as_raw());
NSWindow::setMovable_(*self.ns_window, YES); NSWindow::setMovable_(*self.ns_window, Bool::YES.as_raw());
true true
} }
@ -1261,15 +1249,12 @@ impl WindowExtMacOS for UnownedWindow {
#[inline] #[inline]
fn has_shadow(&self) -> bool { fn has_shadow(&self) -> bool {
unsafe { self.ns_window.hasShadow() == YES } unsafe { Bool::from_raw(self.ns_window.hasShadow()).as_bool() }
} }
#[inline] #[inline]
fn set_has_shadow(&self, has_shadow: bool) { fn set_has_shadow(&self, has_shadow: bool) {
unsafe { unsafe { self.ns_window.setHasShadow_(Bool::new(has_shadow).as_raw()) }
self.ns_window
.setHasShadow_(if has_shadow { YES } else { NO })
}
} }
} }
@ -1297,14 +1282,14 @@ unsafe fn set_min_inner_size<V: NSWindow + Copy>(window: V, mut min_size: Logica
// If necessary, resize the window to match constraint // If necessary, resize the window to match constraint
if current_rect.size.width < min_size.width { if current_rect.size.width < min_size.width {
current_rect.size.width = min_size.width; current_rect.size.width = min_size.width;
window.setFrame_display_(current_rect, NO) window.setFrame_display_(current_rect, Bool::NO.as_raw())
} }
if current_rect.size.height < min_size.height { if current_rect.size.height < min_size.height {
// The origin point of a rectangle is at its bottom left in Cocoa. // The origin point of a rectangle is at its bottom left in Cocoa.
// To ensure the window's top-left point remains the same: // To ensure the window's top-left point remains the same:
current_rect.origin.y += current_rect.size.height - min_size.height; current_rect.origin.y += current_rect.size.height - min_size.height;
current_rect.size.height = min_size.height; current_rect.size.height = min_size.height;
window.setFrame_display_(current_rect, NO) window.setFrame_display_(current_rect, Bool::NO.as_raw())
} }
} }
@ -1322,13 +1307,13 @@ unsafe fn set_max_inner_size<V: NSWindow + Copy>(window: V, mut max_size: Logica
// If necessary, resize the window to match constraint // If necessary, resize the window to match constraint
if current_rect.size.width > max_size.width { if current_rect.size.width > max_size.width {
current_rect.size.width = max_size.width; current_rect.size.width = max_size.width;
window.setFrame_display_(current_rect, NO) window.setFrame_display_(current_rect, Bool::NO.as_raw())
} }
if current_rect.size.height > max_size.height { if current_rect.size.height > max_size.height {
// The origin point of a rectangle is at its bottom left in Cocoa. // The origin point of a rectangle is at its bottom left in Cocoa.
// To ensure the window's top-left point remains the same: // To ensure the window's top-left point remains the same:
current_rect.origin.y += current_rect.size.height - max_size.height; current_rect.origin.y += current_rect.size.height - max_size.height;
current_rect.size.height = max_size.height; current_rect.size.height = max_size.height;
window.setFrame_display_(current_rect, NO) window.setFrame_display_(current_rect, Bool::NO.as_raw())
} }
} }

View file

@ -7,12 +7,12 @@ use std::{
use cocoa::{ use cocoa::{
appkit::{self, NSApplicationPresentationOptions, NSView, NSWindow, NSWindowOcclusionState}, appkit::{self, NSApplicationPresentationOptions, NSView, NSWindow, NSWindowOcclusionState},
base::{id, nil}, base::{id, nil},
foundation::NSUInteger,
}; };
use objc::{ use objc::{
declare::ClassDecl, declare::ClassBuilder,
foundation::NSUInteger,
rc::autoreleasepool, rc::autoreleasepool,
runtime::{Class, Object, Sel, BOOL, NO, YES}, runtime::{Bool, Class, Object, Sel},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -137,92 +137,91 @@ unsafe impl Sync for WindowDelegateClass {}
static WINDOW_DELEGATE_CLASS: Lazy<WindowDelegateClass> = Lazy::new(|| unsafe { static WINDOW_DELEGATE_CLASS: Lazy<WindowDelegateClass> = Lazy::new(|| unsafe {
let superclass = class!(NSResponder); let superclass = class!(NSResponder);
let mut decl = ClassDecl::new("WinitWindowDelegate", superclass).unwrap(); let mut decl = ClassBuilder::new("WinitWindowDelegate", superclass).unwrap();
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _));
decl.add_method( decl.add_method(
sel!(initWithWinit:), sel!(initWithWinit:),
init_with_winit as extern "C" fn(&Object, Sel, *mut c_void) -> id, init_with_winit as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(windowShouldClose:), sel!(windowShouldClose:),
window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL, window_should_close as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(windowWillClose:), sel!(windowWillClose:),
window_will_close as extern "C" fn(&Object, Sel, id), window_will_close as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidResize:), sel!(windowDidResize:),
window_did_resize as extern "C" fn(&Object, Sel, id), window_did_resize as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidMove:), sel!(windowDidMove:),
window_did_move as extern "C" fn(&Object, Sel, id), window_did_move as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidChangeBackingProperties:), sel!(windowDidChangeBackingProperties:),
window_did_change_backing_properties as extern "C" fn(&Object, Sel, id), window_did_change_backing_properties as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidBecomeKey:), sel!(windowDidBecomeKey:),
window_did_become_key as extern "C" fn(&Object, Sel, id), window_did_become_key as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidResignKey:), sel!(windowDidResignKey:),
window_did_resign_key as extern "C" fn(&Object, Sel, id), window_did_resign_key as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(draggingEntered:), sel!(draggingEntered:),
dragging_entered as extern "C" fn(&Object, Sel, id) -> BOOL, dragging_entered as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(prepareForDragOperation:), sel!(prepareForDragOperation:),
prepare_for_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL, prepare_for_drag_operation as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(performDragOperation:), sel!(performDragOperation:),
perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL, perform_drag_operation as extern "C" fn(_, _, _) -> _,
); );
decl.add_method( decl.add_method(
sel!(concludeDragOperation:), sel!(concludeDragOperation:),
conclude_drag_operation as extern "C" fn(&Object, Sel, id), conclude_drag_operation as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(draggingExited:), sel!(draggingExited:),
dragging_exited as extern "C" fn(&Object, Sel, id), dragging_exited as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(window:willUseFullScreenPresentationOptions:), sel!(window:willUseFullScreenPresentationOptions:),
window_will_use_fullscreen_presentation_options window_will_use_fullscreen_presentation_options as extern "C" fn(_, _, _, _) -> _,
as extern "C" fn(&Object, Sel, id, NSUInteger) -> NSUInteger,
); );
decl.add_method( decl.add_method(
sel!(windowDidEnterFullScreen:), sel!(windowDidEnterFullScreen:),
window_did_enter_fullscreen as extern "C" fn(&Object, Sel, id), window_did_enter_fullscreen as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowWillEnterFullScreen:), sel!(windowWillEnterFullScreen:),
window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id), window_will_enter_fullscreen as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidExitFullScreen:), sel!(windowDidExitFullScreen:),
window_did_exit_fullscreen as extern "C" fn(&Object, Sel, id), window_did_exit_fullscreen as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowWillExitFullScreen:), sel!(windowWillExitFullScreen:),
window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id), window_will_exit_fullscreen as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidFailToEnterFullScreen:), sel!(windowDidFailToEnterFullScreen:),
window_did_fail_to_enter_fullscreen as extern "C" fn(&Object, Sel, id), window_did_fail_to_enter_fullscreen as extern "C" fn(_, _, _),
); );
decl.add_method( decl.add_method(
sel!(windowDidChangeOcclusionState:), sel!(windowDidChangeOcclusionState:),
window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id), window_did_change_occlusion_state as extern "C" fn(_, _, _),
); );
decl.add_ivar::<*mut c_void>("winitState"); decl.add_ivar::<*mut c_void>("winitState");
@ -233,7 +232,7 @@ static WINDOW_DELEGATE_CLASS: Lazy<WindowDelegateClass> = Lazy::new(|| unsafe {
// boilerplate and wouldn't really clarify anything... // boilerplate and wouldn't really clarify anything...
fn with_state<F: FnOnce(&mut WindowDelegateState) -> T, T>(this: &Object, callback: F) { fn with_state<F: FnOnce(&mut WindowDelegateState) -> T, T>(this: &Object, callback: F) {
let state_ptr = unsafe { let state_ptr = unsafe {
let state_ptr: *mut c_void = *this.get_ivar("winitState"); let state_ptr: *mut c_void = *this.ivar("winitState");
&mut *(state_ptr as *mut WindowDelegateState) &mut *(state_ptr as *mut WindowDelegateState)
}; };
callback(state_ptr); callback(state_ptr);
@ -258,17 +257,17 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
} }
} }
extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL { extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> Bool {
trace_scope!("windowShouldClose:"); trace_scope!("windowShouldClose:");
with_state(this, |state| state.emit_event(WindowEvent::CloseRequested)); with_state(this, |state| state.emit_event(WindowEvent::CloseRequested));
NO Bool::NO
} }
extern "C" fn window_will_close(this: &Object, _: Sel, _: id) { extern "C" fn window_will_close(this: &Object, _: Sel, _: id) {
trace_scope!("windowWillClose:"); trace_scope!("windowWillClose:");
with_state(this, |state| unsafe { with_state(this, |state| unsafe {
// `setDelegate:` retains the previous value and then autoreleases it // `setDelegate:` retains the previous value and then autoreleases it
autoreleasepool(|| { autoreleasepool(|_| {
// Since El Capitan, we need to be careful that delegate methods can't // Since El Capitan, we need to be careful that delegate methods can't
// be called after the window closes. // be called after the window closes.
let _: () = msg_send![*state.ns_window, setDelegate: nil]; let _: () = msg_send![*state.ns_window, setDelegate: nil];
@ -325,7 +324,7 @@ extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) {
// to an id) // to an id)
let view_state: &mut ViewState = unsafe { let view_state: &mut ViewState = unsafe {
let ns_view: &Object = (*state.ns_view).as_ref().expect("failed to deref"); let ns_view: &Object = (*state.ns_view).as_ref().expect("failed to deref");
let state_ptr: *mut c_void = *ns_view.get_ivar("winitState"); let state_ptr: *mut c_void = *ns_view.ivar("winitState");
&mut *(state_ptr as *mut ViewState) &mut *(state_ptr as *mut ViewState)
}; };
@ -340,7 +339,7 @@ extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) {
} }
/// Invoked when the dragged image enters destination bounds or frame /// Invoked when the dragged image enters destination bounds or frame
extern "C" fn dragging_entered(this: &Object, _: Sel, sender: id) -> BOOL { extern "C" fn dragging_entered(this: &Object, _: Sel, sender: id) -> Bool {
trace_scope!("draggingEntered:"); trace_scope!("draggingEntered:");
use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration}; use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration};
@ -363,17 +362,17 @@ extern "C" fn dragging_entered(this: &Object, _: Sel, sender: id) -> BOOL {
} }
} }
YES Bool::YES
} }
/// Invoked when the image is released /// Invoked when the image is released
extern "C" fn prepare_for_drag_operation(_: &Object, _: Sel, _: id) -> BOOL { extern "C" fn prepare_for_drag_operation(_: &Object, _: Sel, _: id) -> Bool {
trace_scope!("prepareForDragOperation:"); trace_scope!("prepareForDragOperation:");
YES Bool::YES
} }
/// Invoked after the released image has been removed from the screen /// Invoked after the released image has been removed from the screen
extern "C" fn perform_drag_operation(this: &Object, _: Sel, sender: id) -> BOOL { extern "C" fn perform_drag_operation(this: &Object, _: Sel, sender: id) -> Bool {
trace_scope!("performDragOperation:"); trace_scope!("performDragOperation:");
use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration}; use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration};
@ -396,7 +395,7 @@ extern "C" fn perform_drag_operation(this: &Object, _: Sel, sender: id) -> BOOL
} }
} }
YES Bool::YES
} }
/// Invoked when the dragging operation is complete /// Invoked when the dragging operation is complete
@ -478,7 +477,7 @@ extern "C" fn window_will_use_fullscreen_presentation_options(
options = (NSApplicationPresentationOptions::NSApplicationPresentationFullScreen options = (NSApplicationPresentationOptions::NSApplicationPresentationFullScreen
| NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideDock
| NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar) | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar)
.bits(); .bits() as NSUInteger;
} }
}) })
}); });