diff --git a/src/platform_impl/ios/app_state.rs b/src/platform_impl/ios/app_state.rs index 8b5be97822c..2e88f12c97d 100644 --- a/src/platform_impl/ios/app_state.rs +++ b/src/platform_impl/ios/app_state.rs @@ -9,7 +9,7 @@ use std::{ time::Instant, }; -use objc::runtime::{Object, BOOL, YES}; +use objc::runtime::Object; use once_cell::sync::Lazy; use crate::{ @@ -472,10 +472,7 @@ impl AppState { // retains window pub unsafe fn set_key_window(window: id) { bug_assert!( - { - let is_window: BOOL = msg_send![window, isKindOfClass: class!(UIWindow)]; - is_window == YES - }, + msg_send![window, isKindOfClass: class!(UIWindow)], "set_key_window called with an incorrect type" ); let mut this = AppState::get_mut(); @@ -502,10 +499,7 @@ pub unsafe fn set_key_window(window: id) { // retains window pub unsafe fn queue_gl_or_metal_redraw(window: id) { bug_assert!( - { - let is_window: BOOL = msg_send![window, isKindOfClass: class!(UIWindow)]; - is_window == YES - }, + msg_send![window, isKindOfClass: class!(UIWindow)], "set_key_window called with an incorrect type" ); let mut this = AppState::get_mut(); @@ -886,8 +880,11 @@ fn get_view_and_screen_frame(window_id: id) -> (id, CGRect) { let bounds: CGRect = msg_send![window_id, bounds]; let screen: id = msg_send![window_id, screen]; let screen_space: id = msg_send![screen, coordinateSpace]; - let screen_frame: CGRect = - msg_send![window_id, convertRect:bounds toCoordinateSpace:screen_space]; + let screen_frame: CGRect = msg_send![ + window_id, + convertRect: bounds, + toCoordinateSpace: screen_space, + ]; (view, screen_frame) } } @@ -1019,7 +1016,7 @@ pub fn os_capabilities() -> OSCapabilities { static OS_CAPABILITIES: Lazy = Lazy::new(|| { let version: NSOperatingSystemVersion = unsafe { 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, respondsToSelector: sel!(operatingSystemVersion) ]; @@ -1030,10 +1027,7 @@ pub fn os_capabilities() -> OSCapabilities { // 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. - assert!( - atleast_ios_8 == YES, - "`winit` requires iOS version 8 or greater" - ); + assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater"); msg_send![process_info, operatingSystemVersion] }; version.into() diff --git a/src/platform_impl/ios/event_loop.rs b/src/platform_impl/ios/event_loop.rs index 2bd2bdaf90d..af9e15db4b5 100644 --- a/src/platform_impl/ios/event_loop.rs +++ b/src/platform_impl/ios/event_loop.rs @@ -81,9 +81,10 @@ pub(crate) struct PlatformSpecificEventLoopAttributes {} impl EventLoop { pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> EventLoop { + assert_main_thread!("`EventLoop` can only be created on the main thread on iOS"); + static mut SINGLETON_INIT: bool = false; unsafe { - assert_main_thread!("`EventLoop` can only be created on the main thread on iOS"); assert!( !SINGLETON_INIT, "Only one `EventLoop` is supported on iOS. \ diff --git a/src/platform_impl/ios/mod.rs b/src/platform_impl/ios/mod.rs index 37677918e51..cdac67cf717 100644 --- a/src/platform_impl/ios/mod.rs +++ b/src/platform_impl/ios/mod.rs @@ -63,8 +63,7 @@ // window size/position. macro_rules! assert_main_thread { ($($t:tt)*) => { - let is_main_thread: ::objc::runtime::BOOL = msg_send!(class!(NSThread), isMainThread); - if is_main_thread == ::objc::runtime::NO { + if !::objc::foundation::is_main_thread() { panic!($($t)*); } }; diff --git a/src/platform_impl/ios/monitor.rs b/src/platform_impl/ios/monitor.rs index 3505b8dfcaf..edccd692b03 100644 --- a/src/platform_impl/ios/monitor.rs +++ b/src/platform_impl/ios/monitor.rs @@ -113,22 +113,14 @@ impl Deref for MonitorHandle { type Target = 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 } } impl DerefMut for MonitorHandle { 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 } } @@ -144,9 +136,7 @@ impl Clone for MonitorHandle { impl Drop for MonitorHandle { 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 +165,8 @@ impl fmt::Debug for MonitorHandle { impl MonitorHandle { pub fn retained_new(uiscreen: id) -> MonitorHandle { + assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS"); unsafe { - assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS"); let _: id = msg_send![uiscreen, retain]; } MonitorHandle { diff --git a/src/platform_impl/ios/view.rs b/src/platform_impl/ios/view.rs index c4d475609a4..6afe975759d 100644 --- a/src/platform_impl/ios/view.rs +++ b/src/platform_impl/ios/view.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use objc::{ - declare::ClassDecl, - runtime::{Class, Object, Sel, BOOL, NO, YES}, + declare::ClassBuilder, + runtime::{Bool, Class, Object, Sel}, }; use crate::{ @@ -66,7 +66,7 @@ macro_rules! add_property { }; #[allow(non_snake_case)] 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( sel!($setter_name:), @@ -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 || { let uiview_class = class!(UIView); - let is_uiview: BOOL = msg_send![root_view_class, isSubclassOfClass: uiview_class]; - assert_eq!( - is_uiview, YES, - "`root_view_class` must inherit from `UIView`" - ); + let is_uiview: bool = msg_send![root_view_class, isSubclassOfClass: uiview_class]; + assert!(is_uiview, "`root_view_class` must inherit from `UIView`"); extern "C" fn draw_rect(object: &Object, _: Sel, rect: CGRect) { 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 screen: id = msg_send![window, screen]; let screen_space: id = msg_send![screen, coordinateSpace]; - let screen_frame: CGRect = - msg_send![object, convertRect:window_bounds toCoordinateSpace:screen_space]; + let screen_frame: CGRect = msg_send![ + object, + convertRect: window_bounds, + toCoordinateSpace: screen_space, + ]; let scale_factor: CGFloat = msg_send![screen, scale]; let size = crate::dpi::LogicalSize { width: screen_frame.size.width as f64, @@ -186,7 +186,7 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class { let screen: id = msg_send![window, screen]; let screen_space: id = msg_send![screen, coordinateSpace]; 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 { width: screen_frame.size.width as _, height: screen_frame.size.height as _, @@ -281,7 +281,7 @@ 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`"); ID += 1; decl.add_method(sel!(drawRect:), draw_rect as extern "C" fn(_, _, _)); @@ -320,11 +320,11 @@ unsafe fn get_view_controller_class() -> &'static Class { let uiviewcontroller_class = class!(UIViewController); - extern "C" fn should_autorotate(_: &Object, _: Sel) -> BOOL { - YES + extern "C" fn should_autorotate(_: &Object, _: Sel) -> Bool { + Bool::YES } - let mut decl = ClassDecl::new("WinitUIViewController", uiviewcontroller_class) + let mut decl = ClassBuilder::new("WinitUIViewController", uiviewcontroller_class) .expect("Failed to declare class `WinitUIViewController`"); decl.add_method( sel!(shouldAutorotate), @@ -332,7 +332,7 @@ unsafe fn get_view_controller_class() -> &'static Class { ); add_property! { decl, - prefers_status_bar_hidden: BOOL, + prefers_status_bar_hidden: Bool, setPrefersStatusBarHidden: |object| { unsafe { let _: () = msg_send![object, setNeedsStatusBarAppearanceUpdate]; @@ -342,7 +342,7 @@ unsafe fn get_view_controller_class() -> &'static Class { } add_property! { decl, - prefers_home_indicator_auto_hidden: BOOL, + prefers_home_indicator_auto_hidden: Bool, setPrefersHomeIndicatorAutoHidden: os_capabilities.home_indicator_hidden, OSCapabilities::home_indicator_hidden_err_msg; @@ -407,7 +407,7 @@ 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`"); decl.add_method( sel!(becomeKeyWindow), @@ -435,7 +435,7 @@ pub(crate) unsafe fn create_view( assert!(!view.is_null(), "Failed to create `UIView` instance"); let view: id = msg_send![view, initWithFrame: frame]; 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 { let _: () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat]; } @@ -461,21 +461,14 @@ pub(crate) unsafe fn create_view_controller( !view_controller.is_null(), "Failed to initialize `UIViewController` instance" ); - let status_bar_hidden = if platform_attributes.prefers_status_bar_hidden { - YES - } else { - NO - }; + let status_bar_hidden = Bool::new(platform_attributes.prefers_status_bar_hidden); let idiom = event_loop::get_idiom(); let supported_orientations = UIInterfaceOrientationMask::from_valid_orientations_idiom( platform_attributes.valid_orientations, idiom, ); - let prefers_home_indicator_hidden = if platform_attributes.prefers_home_indicator_hidden { - YES - } else { - NO - }; + let prefers_home_indicator_hidden = + Bool::new(platform_attributes.prefers_home_indicator_hidden); let edges: UIRectEdge = platform_attributes .preferred_screen_edges_deferring_system_gestures .into(); @@ -540,11 +533,11 @@ pub(crate) unsafe fn create_window( } 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 { app_state::did_finish_launching(); } - YES + Bool::YES } extern "C" fn did_become_active(_: &Object, _: Sel, _: id) { @@ -569,8 +562,8 @@ pub fn create_delegate_class() { if window == nil { break; } - let is_winit_window: BOOL = msg_send![window, isKindOfClass: class!(WinitUIWindow)]; - if is_winit_window == YES { + let is_winit_window = msg_send![window, isKindOfClass: class!(WinitUIWindow)]; + if is_winit_window { events.push(EventWrapper::StaticEvent(Event::WindowEvent { window_id: RootWindowId(window.into()), event: WindowEvent::Destroyed, @@ -583,8 +576,8 @@ pub fn create_delegate_class() { } let ui_responder = class!(UIResponder); - let mut decl = - ClassDecl::new("AppDelegate", ui_responder).expect("Failed to declare class `AppDelegate`"); + let mut decl = ClassBuilder::new("AppDelegate", ui_responder) + .expect("Failed to declare class `AppDelegate`"); unsafe { decl.add_method( diff --git a/src/platform_impl/ios/window.rs b/src/platform_impl/ios/window.rs index 3f5e64cf7dd..cf7b55bd7ce 100644 --- a/src/platform_impl/ios/window.rs +++ b/src/platform_impl/ios/window.rs @@ -3,7 +3,7 @@ use std::{ 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 crate::{ @@ -51,14 +51,7 @@ impl Inner { } pub fn set_visible(&self, visible: bool) { - match visible { - true => unsafe { - let _: () = msg_send![self.window, setHidden: NO]; - }, - false => unsafe { - let _: () = msg_send![self.window, setHidden: YES]; - }, - } + unsafe { msg_send![self.window, setHidden: !visible] } } pub fn is_visible(&self) -> Option { @@ -350,9 +343,7 @@ pub struct Window { impl Drop for Window { 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; 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 } } impl DerefMut for Window { 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 } } @@ -429,10 +416,9 @@ impl Window { let gl_or_metal_backed = { let view_class: *const Class = msg_send![view, class]; let layer_class: *const Class = msg_send![view_class, layerClass]; - let is_metal: BOOL = - msg_send![layer_class, isSubclassOfClass: class!(CAMetalLayer)]; - let is_gl: BOOL = msg_send![layer_class, isSubclassOfClass: class!(CAEAGLLayer)]; - is_metal == YES || is_gl == YES + let is_metal = msg_send![layer_class, isSubclassOfClass: class!(CAMetalLayer)]; + let is_gl = msg_send![layer_class, isSubclassOfClass: class!(CAEAGLLayer)]; + is_metal || is_gl }; let view_controller = @@ -463,7 +449,7 @@ impl Window { let screen: id = msg_send![window, screen]; let screen_space: id = msg_send![screen, coordinateSpace]; 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 { width: screen_frame.size.width as _, height: screen_frame.size.height as _, @@ -527,10 +513,9 @@ impl Inner { pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { unsafe { - let prefers_home_indicator_hidden = if hidden { YES } else { NO }; let _: () = msg_send![ 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) { unsafe { - let status_bar_hidden = if hidden { YES } else { NO }; - let _: () = msg_send![ - self.view_controller, - setPrefersStatusBarHidden: status_bar_hidden - ]; + let _: () = msg_send![self.view_controller, setPrefersStatusBarHidden: hidden,]; } } } @@ -567,7 +548,11 @@ impl Inner { let screen: id = msg_send![self.window, screen]; if !screen.is_null() { 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 { rect } @@ -578,7 +563,11 @@ impl Inner { let screen: id = msg_send![self.window, screen]; if !screen.is_null() { 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 { rect } diff --git a/src/platform_impl/macos/app.rs b/src/platform_impl/macos/app.rs index 129c34a638a..b477fd3a1e2 100644 --- a/src/platform_impl/macos/app.rs +++ b/src/platform_impl/macos/app.rs @@ -5,7 +5,7 @@ use cocoa::{ base::id, }; use objc::{ - declare::ClassDecl, + declare::ClassBuilder, runtime::{Class, Object, Sel}, }; use once_cell::sync::Lazy; @@ -19,7 +19,7 @@ unsafe impl Sync for AppClass {} pub static APP_CLASS: Lazy = Lazy::new(|| unsafe { let superclass = class!(NSApplication); - let mut decl = ClassDecl::new("WinitApp", superclass).unwrap(); + let mut decl = ClassBuilder::new("WinitApp", superclass).unwrap(); decl.add_method(sel!(sendEvent:), send_event as extern "C" fn(_, _, _)); diff --git a/src/platform_impl/macos/app_delegate.rs b/src/platform_impl/macos/app_delegate.rs index 3a9954afcbd..4c7adc7c98a 100644 --- a/src/platform_impl/macos/app_delegate.rs +++ b/src/platform_impl/macos/app_delegate.rs @@ -5,7 +5,7 @@ use std::{ use cocoa::base::id; use objc::{ - declare::ClassDecl, + declare::ClassBuilder, runtime::{Class, Object, Sel}, }; use once_cell::sync::Lazy; @@ -25,7 +25,7 @@ unsafe impl Sync for AppDelegateClass {} pub static APP_DELEGATE_CLASS: Lazy = Lazy::new(|| unsafe { 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(_, _) -> _); decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _)); @@ -46,7 +46,7 @@ pub static APP_DELEGATE_CLASS: Lazy = Lazy::new(|| unsafe { /// Safety: Assumes that Object is an instance of APP_DELEGATE_CLASS 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 (*(ptr as *mut RefCell)).borrow_mut() } @@ -69,7 +69,7 @@ extern "C" fn new(class: &Class, _: Sel) -> id { extern "C" fn dealloc(this: &Object, _: Sel) { 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 // memory drop(Box::from_raw(state_ptr as *mut RefCell)); diff --git a/src/platform_impl/macos/app_state.rs b/src/platform_impl/macos/app_state.rs index b655ed1454d..d5b2c7b2ed7 100644 --- a/src/platform_impl/macos/app_state.rs +++ b/src/platform_impl/macos/app_state.rs @@ -18,8 +18,9 @@ use cocoa::{ foundation::NSSize, }; use objc::{ + foundation::is_main_thread, rc::autoreleasepool, - runtime::{Object, BOOL, NO, YES}, + runtime::{Bool, Object}, }; use once_cell::sync::Lazy; @@ -288,7 +289,7 @@ impl AppState { let ns_app = NSApp(); window_activation_hack(ns_app); // 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.waker().start(); @@ -361,16 +362,14 @@ impl AppState { } pub fn queue_event(wrapper: EventWrapper) { - let is_main_thread: BOOL = unsafe { msg_send!(class!(NSThread), isMainThread) }; - if is_main_thread == NO { + if !is_main_thread() { panic!("Event queued from different thread: {:#?}", wrapper); } HANDLER.events().push_back(wrapper); } pub fn queue_events(mut wrappers: VecDeque) { - let is_main_thread: BOOL = unsafe { msg_send!(class!(NSThread), isMainThread) }; - if is_main_thread == NO { + if !is_main_thread() { panic!("Events queued from different thread: {:#?}", wrappers); } HANDLER.events().append(&mut wrappers); @@ -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` // 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? - if ns_window.isVisible() == YES { + if Bool::from_raw(ns_window.isVisible()).as_bool() { trace!("Activating visible window"); ns_window.makeKeyAndOrderFront_(nil); } else { diff --git a/src/platform_impl/macos/event_loop.rs b/src/platform_impl/macos/event_loop.rs index 6075fd53294..fdbf6efd9b0 100644 --- a/src/platform_impl/macos/event_loop.rs +++ b/src/platform_impl/macos/event_loop.rs @@ -13,10 +13,10 @@ use std::{ use cocoa::{ appkit::{NSApp, NSEventModifierFlags, NSEventSubtype, NSEventType::NSApplicationDefined}, - base::{id, nil, BOOL, NO, YES}, + base::{id, nil}, foundation::{NSInteger, NSPoint, NSTimeInterval}, }; -use objc::rc::autoreleasepool; +use objc::{foundation::is_main_thread, rc::autoreleasepool}; use raw_window_handle::{AppKitDisplayHandle, RawDisplayHandle}; use crate::{ @@ -144,8 +144,7 @@ impl Default for PlatformSpecificEventLoopAttributes { impl EventLoop { pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Self { let delegate = unsafe { - let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); - if is_main_thread == NO { + if !is_main_thread() { panic!("On macOS, `EventLoop` must be created on the main thread!"); } @@ -252,7 +251,7 @@ pub unsafe fn post_dummy_event(target: id) { data1: 0 as NSInteger data2: 0 as NSInteger ]; - 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 diff --git a/src/platform_impl/macos/util/async.rs b/src/platform_impl/macos/util/async.rs index 84f35f1f597..c221f08b217 100644 --- a/src/platform_impl/macos/util/async.rs +++ b/src/platform_impl/macos/util/async.rs @@ -9,8 +9,9 @@ use cocoa::{ foundation::{NSPoint, NSSize, NSString}, }; use dispatch::Queue; +use objc::foundation::is_main_thread; use objc::rc::autoreleasepool; -use objc::runtime::{BOOL, NO, YES}; +use objc::runtime::Bool; use crate::{ 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) { - let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); - if is_main_thread != NO { + if is_main_thread() { set_style_mask(ns_window, ns_view, mask); } else { 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) { let ns_window = MainThreadSafe(ns_window); 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 { shared_state_lock.saved_standard_frame() }; - ns_window.setFrame_display_(new_rect, NO); + ns_window.setFrame_display_(new_rect, Bool::NO.as_raw()); } } }); diff --git a/src/platform_impl/macos/util/cursor.rs b/src/platform_impl/macos/util/cursor.rs index 1e1574ce8e3..5c48720b87d 100644 --- a/src/platform_impl/macos/util/cursor.rs +++ b/src/platform_impl/macos/util/cursor.rs @@ -3,7 +3,7 @@ use cocoa::{ base::{id, nil}, foundation::{NSDictionary, NSPoint, NSString}, }; -use objc::{runtime::Sel, runtime::NO}; +use objc::runtime::Sel; use std::cell::RefCell; use crate::window::CursorIcon; @@ -147,10 +147,11 @@ pub unsafe fn invisible_cursor() -> id { CURSOR_OBJECT.with(|cursor_obj| { if *cursor_obj.borrow() == nil { // Create a cursor from `CURSOR_BYTES` - let cursor_data: id = msg_send![class!(NSData), - dataWithBytesNoCopy:CURSOR_BYTES.as_ptr() - length:CURSOR_BYTES.len() - freeWhenDone:NO + let cursor_data: id = msg_send![ + class!(NSData), + dataWithBytesNoCopy: CURSOR_BYTES.as_ptr(), + length: CURSOR_BYTES.len(), + freeWhenDone: false, ]; let ns_image: id = msg_send![class!(NSImage), alloc]; diff --git a/src/platform_impl/macos/util/mod.rs b/src/platform_impl/macos/util/mod.rs index 53217d8ca7a..be97acb5d74 100644 --- a/src/platform_impl/macos/util/mod.rs +++ b/src/platform_impl/macos/util/mod.rs @@ -12,7 +12,7 @@ use cocoa::{ foundation::{NSPoint, NSRange, NSRect, NSString, NSUInteger}, }; use core_graphics::display::CGDisplay; -use objc::runtime::{Class, Object, BOOL, NO}; +use objc::runtime::{Class, Object}; use crate::dpi::LogicalPosition; use crate::platform_impl::platform::ffi; @@ -172,8 +172,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` pub unsafe fn id_to_string_lossy(string: id) -> String { - let has_attr: BOOL = msg_send![string, isKindOfClass: class!(NSAttributedString)]; - let characters = if has_attr != NO { + let has_attr = msg_send![string, isKindOfClass: class!(NSAttributedString)]; + let characters = if has_attr { // This is a *mut NSAttributedString msg_send![string, string] } else { diff --git a/src/platform_impl/macos/view.rs b/src/platform_impl/macos/view.rs index 44f9067159d..4055e2d97a3 100644 --- a/src/platform_impl/macos/view.rs +++ b/src/platform_impl/macos/view.rs @@ -15,8 +15,8 @@ use cocoa::{ foundation::{NSInteger, NSPoint, NSRange, NSRect, NSSize, NSString, NSUInteger}, }; use objc::{ - declare::ClassDecl, - runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES}, + declare::ClassBuilder, + runtime::{Bool, Class, Object, Protocol, Sel}, }; use once_cell::sync::Lazy; @@ -124,7 +124,7 @@ pub fn new_view(ns_window: id) -> (IdRef, Weak>) { } pub unsafe fn set_ime_position(ns_view: id, position: LogicalPosition) { - 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); state.ime_position = position; let input_context: id = msg_send![ns_view, inputContext]; @@ -132,7 +132,7 @@ pub unsafe fn set_ime_position(ns_view: id, position: LogicalPosition) { } 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); if state.ime_allowed == ime_allowed { return; @@ -141,7 +141,7 @@ pub unsafe fn set_ime_allowed(ns_view: id, ime_allowed: bool) { if state.ime_allowed { 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 let _: () = msg_send![*marked_text_ref, release]; @@ -164,7 +164,7 @@ unsafe impl Sync for ViewClass {} static VIEW_CLASS: Lazy = Lazy::new(|| unsafe { 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(_, _)); decl.add_method( sel!(initWithWinit:), @@ -303,9 +303,9 @@ static VIEW_CLASS: Lazy = Lazy::new(|| unsafe { extern "C" fn dealloc(this: &Object, _sel: Sel) { unsafe { - let marked_text: id = *this.get_ivar("markedText"); + let marked_text: id = *this.ivar("markedText"); 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)); } } @@ -318,7 +318,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i let marked_text = ::init(NSMutableAttributedString::alloc(nil)); (*this).set_ivar("markedText", marked_text); - let _: () = msg_send![this, setPostsFrameChangedNotifications: YES]; + let _: () = msg_send![this, setPostsFrameChangedNotifications: true]; let notification_center: &Object = msg_send![class!(NSNotificationCenter), defaultCenter]; @@ -343,7 +343,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) { trace_scope!("viewDidMoveToWindow"); 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); if let Some(tracking_rect) = state.tracking_rect.take() { @@ -351,11 +351,12 @@ extern "C" fn view_did_move_to_window(this: &Object, _sel: Sel) { } let rect: NSRect = msg_send![this, visibleRect]; - let tracking_rect: NSInteger = msg_send![this, - addTrackingRect:rect - owner:this - userData:ptr::null_mut::() - assumeInside:NO + let tracking_rect: NSInteger = msg_send![ + this, + addTrackingRect: rect, + owner: this, + userData: ptr::null_mut::(), + assumeInside: false ]; state.tracking_rect = Some(tracking_rect); } @@ -364,7 +365,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) { trace_scope!("frameDidChange:"); 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); if let Some(tracking_rect) = state.tracking_rect.take() { @@ -372,11 +373,12 @@ extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) { } let rect: NSRect = msg_send![this, visibleRect]; - let tracking_rect: NSInteger = msg_send![this, - addTrackingRect:rect - owner:this - userData:ptr::null_mut::() - assumeInside:NO + let tracking_rect: NSInteger = msg_send![ + this, + addTrackingRect: rect, + owner: this, + userData: ptr::null_mut::(), + assumeInside: false, ]; state.tracking_rect = Some(tracking_rect); @@ -395,7 +397,7 @@ extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) { extern "C" fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) { trace_scope!("drawRect:"); 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); AppState::handle_redraw(WindowId(get_window_id(state.ns_window))); @@ -405,23 +407,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"); - YES + Bool::YES } // 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 // 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"); - NO + Bool::NO } extern "C" fn reset_cursor_rects(this: &Object, _sel: Sel) { trace_scope!("resetCursorRects"); 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 bounds: NSRect = msg_send![this, bounds]; @@ -438,18 +440,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"); unsafe { - let marked_text: id = *this.get_ivar("markedText"); - (marked_text.length() > 0) as BOOL + let marked_text: id = *this.ivar("markedText"); + Bool::new(marked_text.length() > 0) } } extern "C" fn marked_range(this: &Object, _sel: Sel) -> NSRange { trace_scope!("markedRange"); unsafe { - let marked_text: id = *this.get_ivar("markedText"); + let marked_text: id = *this.ivar("markedText"); let length = marked_text.length(); if length > 0 { NSRange::new(0, length) @@ -481,13 +483,13 @@ extern "C" fn set_marked_text( trace_scope!("setMarkedText:selectedRange:replacementRange:"); unsafe { // 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 - let _: () = msg_send![(*marked_text_ref), release]; + let _: () = msg_send![*marked_text_ref, release]; let marked_text = NSMutableAttributedString::alloc(nil); - let has_attr: BOOL = msg_send![string, isKindOfClass: class!(NSAttributedString)]; - if has_attr != NO { + let has_attr = msg_send![string, isKindOfClass: class!(NSAttributedString)]; + if has_attr { marked_text.initWithAttributedString(string); } else { marked_text.initWithString(string); @@ -495,7 +497,7 @@ extern "C" fn set_marked_text( *marked_text_ref = 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 preedit_string = id_to_string_lossy(string); @@ -533,7 +535,7 @@ extern "C" fn set_marked_text( extern "C" fn unmark_text(this: &Object, _sel: Sel) { trace_scope!("unmarkText"); unsafe { - let marked_text: id = *this.get_ivar("markedText"); + let marked_text: id = *this.ivar("markedText"); let mutable_string = marked_text.mutableString(); let s: id = msg_send![class!(NSString), new]; let _: () = msg_send![mutable_string, setString: s]; @@ -541,7 +543,7 @@ extern "C" fn unmark_text(this: &Object, _sel: Sel) { let input_context: id = msg_send![this, inputContext]; 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); AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent { window_id: WindowId(get_window_id(state.ns_window)), @@ -584,7 +586,7 @@ extern "C" fn first_rect_for_character_range( ) -> NSRect { trace_scope!("firstRectForCharacterRange:actualRange:"); 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 content_rect = NSWindow::contentRectForFrameRect_(state.ns_window, NSWindow::frame(state.ns_window)); @@ -603,7 +605,7 @@ extern "C" fn first_rect_for_character_range( extern "C" fn insert_text(this: &Object, _sel: Sel, string: id, _replacement_range: NSRange) { trace_scope!("insertText:replacementRange:"); 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 string = id_to_string_lossy(string); @@ -628,7 +630,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 // readable" character happens, i.e. newlines, tabs, and Ctrl+C. 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); // We shouldn't forward any character from just commited text, since we'll end up sending @@ -640,8 +642,8 @@ extern "C" fn do_command_by_selector(this: &Object, _sel: Sel, _command: Sel) { state.forward_key_to_app = true; - let has_marked_text: BOOL = msg_send![this, hasMarkedText]; - if has_marked_text == NO && state.ime_state == ImeState::Preedit { + let has_marked_text = msg_send![this, hasMarkedText]; + if has_marked_text && state.ime_state == ImeState::Preedit { // Leave preedit so that we also report the keyup for this key state.ime_state = ImeState::Enabled; } @@ -719,7 +721,7 @@ fn update_potentially_stale_modifiers(state: &mut ViewState, event: id) { extern "C" fn key_down(this: &Object, _sel: Sel, event: id) { trace_scope!("keyDown:"); 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 window_id = WindowId(get_window_id(state.ns_window)); @@ -802,7 +804,7 @@ extern "C" fn key_down(this: &Object, _sel: Sel, event: id) { extern "C" fn key_up(this: &Object, _sel: Sel, event: id) { trace_scope!("keyUp:"); 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 scancode = get_scancode(event) as u32; @@ -835,7 +837,7 @@ extern "C" fn key_up(this: &Object, _sel: Sel, event: id) { extern "C" fn flags_changed(this: &Object, _sel: Sel, event: id) { trace_scope!("flagsChanged:"); 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 mut events = VecDeque::with_capacity(4); @@ -921,7 +923,7 @@ extern "C" fn insert_back_tab(this: &Object, _sel: Sel, _sender: id) { extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) { trace_scope!("cancelOperation:"); 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 scancode = 0x2f; @@ -953,7 +955,7 @@ extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) { fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: ElementState) { 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); update_potentially_stale_modifiers(state, event); @@ -1010,7 +1012,7 @@ extern "C" fn other_mouse_up(this: &Object, _sel: Sel, event: id) { fn mouse_motion(this: &Object, event: id) { 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); // We have to do this to have access to the `NSView` trait... @@ -1072,7 +1074,7 @@ extern "C" fn other_mouse_dragged(this: &Object, _sel: Sel, event: id) { extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) { trace_scope!("mouseEntered:"); 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 enter_event = Event::WindowEvent { @@ -1089,7 +1091,7 @@ extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) { extern "C" fn mouse_exited(this: &Object, _sel: Sel, _event: id) { trace_scope!("mouseExited:"); 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 window_event = Event::WindowEvent { @@ -1109,12 +1111,12 @@ extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) { mouse_motion(this, event); 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 delta = { 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()); MouseScrollDelta::PixelDelta(delta) } else { @@ -1149,7 +1151,7 @@ extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) { 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); update_potentially_stale_modifiers(state, event); @@ -1173,7 +1175,7 @@ extern "C" fn magnify_with_event(this: &Object, _sel: Sel, event: id) { trace_scope!("magnifyWithEvent:"); 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 delta = event.magnification(); @@ -1202,7 +1204,7 @@ extern "C" fn rotate_with_event(this: &Object, _sel: Sel, event: id) { trace_scope!("rotateWithEvent:"); 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 delta = event.rotation(); @@ -1233,7 +1235,7 @@ extern "C" fn pressure_change_with_event(this: &Object, _sel: Sel, event: id) { mouse_motion(this, event); 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 pressure = event.pressure(); @@ -1255,12 +1257,12 @@ extern "C" fn pressure_change_with_event(this: &Object, _sel: Sel, event: id) { // Allows us to receive Ctrl-Tab and Ctrl-Esc. // 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 -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:"); - 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:"); - YES + Bool::YES } diff --git a/src/platform_impl/macos/window.rs b/src/platform_impl/macos/window.rs index 4a63f9e2e0d..bd2a4f45cf8 100644 --- a/src/platform_impl/macos/window.rs +++ b/src/platform_impl/macos/window.rs @@ -46,9 +46,10 @@ use cocoa::{ }; use core_graphics::display::{CGDisplay, CGDisplayMode}; use objc::{ - declare::ClassDecl, + declare::ClassBuilder, + foundation::is_main_thread, rc::autoreleasepool, - runtime::{Class, Object, Sel, BOOL, NO, YES}, + runtime::{Bool, Class, Object, Sel}, }; 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 // always the default system value in favour of the user's code if !pl_attribs.disallow_hidpi { - ns_view.setWantsBestResolutionOpenGLSurface_(YES); + ns_view.setWantsBestResolutionOpenGLSurface_(Bool::YES.as_raw()); } else { - ns_view.setWantsBestResolutionOpenGLSurface_(NO); + ns_view.setWantsBestResolutionOpenGLSurface_(Bool::NO.as_raw()); } // 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 // itself and break the association with its context. if f64::floor(appkit::NSAppKitVersionNumber) > appkit::NSAppKitVersionNumber10_12 { - ns_view.setWantsLayer(YES); + ns_view.setWantsLayer(Bool::YES.as_raw()); } (ns_view, cursor_state) @@ -208,17 +209,17 @@ fn create_window( frame, masks, appkit::NSBackingStoreBuffered, - NO, + Bool::NO.as_raw(), )); ns_window.non_nil().map(|ns_window| { 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.setAcceptsMouseMovedEvents_(YES); + ns_window.setAcceptsMouseMovedEvents_(Bool::YES.as_raw()); if pl_attrs.titlebar_transparent { - ns_window.setTitlebarAppearsTransparent_(YES); + ns_window.setTitlebarAppearsTransparent_(Bool::YES.as_raw()); } if pl_attrs.title_hidden { ns_window.setTitleVisibility_(appkit::NSWindowTitleVisibility::NSWindowTitleHidden); @@ -231,11 +232,11 @@ fn create_window( NSWindowButton::NSWindowZoomButton, ] { 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 { - ns_window.setMovableByWindowBackground_(YES); + ns_window.setMovableByWindowBackground_(Bool::YES.as_raw()); } if attrs.always_on_top { @@ -251,7 +252,7 @@ fn create_window( } if !pl_attrs.has_shadow { - ns_window.setHasShadow_(NO); + ns_window.setHasShadow_(Bool::NO.as_raw()); } if attrs.position.is_none() { ns_window.center(); @@ -267,16 +268,16 @@ unsafe impl Sync for WindowClass {} static WINDOW_CLASS: Lazy = Lazy::new(|| unsafe { 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"); - 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"); - YES + Bool::YES } decl.add_method( @@ -393,11 +394,8 @@ impl UnownedWindow { mut win_attribs: WindowAttributes, pl_attribs: PlatformSpecificWindowBuilderAttributes, ) -> Result<(Arc, IdRef), RootOsError> { - unsafe { - let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); - if is_main_thread == NO { - panic!("Windows can only be created on the main thread on macOS"); - } + if !is_main_thread() { + panic!("Windows can only be created on the main thread on macOS"); } trace!("Creating new window"); @@ -417,7 +415,7 @@ impl UnownedWindow { unsafe { if win_attribs.transparent { - ns_window.setOpaque_(NO); + ns_window.setOpaque_(Bool::NO.as_raw()); ns_window.setBackgroundColor_(NSColor::clearColor(nil)); } @@ -516,8 +514,8 @@ impl UnownedWindow { #[inline] pub fn is_visible(&self) -> Option { - let is_visible: BOOL = unsafe { msg_send![*self.ns_window, isVisible] }; - Some(is_visible == YES) + let is_visible = unsafe { msg_send![*self.ns_window, isVisible] }; + Some(is_visible) } pub fn request_redraw(&self) { @@ -622,8 +620,7 @@ impl UnownedWindow { #[inline] pub fn is_resizable(&self) -> bool { - let is_resizable: BOOL = unsafe { msg_send![*self.ns_window, isResizable] }; - is_resizable == YES + unsafe { msg_send![*self.ns_window, isResizable] } } pub fn set_cursor_icon(&self, cursor: CursorIcon) { @@ -723,14 +720,14 @@ impl UnownedWindow { 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 if needs_temp_mask { self.set_style_mask_async(curr_mask); } - is_zoomed != NO + is_zoomed } fn saved_style(&self, shared_state: &mut SharedState) -> NSWindowStyleMask { @@ -764,8 +761,7 @@ impl UnownedWindow { #[inline] pub fn set_minimized(&self, minimized: bool) { - let is_minimized: BOOL = unsafe { msg_send![*self.ns_window, isMiniaturized] }; - let is_minimized: bool = is_minimized == YES; + let is_minimized: bool = unsafe { msg_send![*self.ns_window, isMiniaturized] }; if is_minimized == minimized { return; } @@ -1082,14 +1078,12 @@ impl UnownedWindow { #[inline] pub fn focus_window(&self) { - 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 = is_visible == YES; + let is_minimized: bool = unsafe { msg_send![*self.ns_window, isMiniaturized] }; + let is_visible: bool = unsafe { msg_send![*self.ns_window, isVisible] }; if !is_minimized && is_visible { unsafe { - NSApp().activateIgnoringOtherApps_(YES); + NSApp().activateIgnoringOtherApps_(Bool::YES.as_raw()); util::make_key_and_order_front_async(*self.ns_window); } } @@ -1217,7 +1211,7 @@ impl WindowExtMacOS for UnownedWindow { // Set the window frame to the screen frame size let screen = self.ns_window.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 util::toggle_style_mask( @@ -1232,7 +1226,7 @@ impl WindowExtMacOS for UnownedWindow { NSWindowStyleMask::NSResizableWindowMask, false, ); - NSWindow::setMovable_(*self.ns_window, NO); + NSWindow::setMovable_(*self.ns_window, Bool::NO.as_raw()); true } else { @@ -1245,8 +1239,8 @@ impl WindowExtMacOS for UnownedWindow { } let frame = shared_state_lock.saved_standard_frame(); - NSWindow::setFrame_display_(*self.ns_window, frame, YES); - NSWindow::setMovable_(*self.ns_window, YES); + NSWindow::setFrame_display_(*self.ns_window, frame, Bool::YES.as_raw()); + NSWindow::setMovable_(*self.ns_window, Bool::YES.as_raw()); true } @@ -1255,15 +1249,12 @@ impl WindowExtMacOS for UnownedWindow { #[inline] fn has_shadow(&self) -> bool { - unsafe { self.ns_window.hasShadow() == YES } + unsafe { Bool::from_raw(self.ns_window.hasShadow()).as_bool() } } #[inline] fn set_has_shadow(&self, has_shadow: bool) { - unsafe { - self.ns_window - .setHasShadow_(if has_shadow { YES } else { NO }) - } + unsafe { self.ns_window.setHasShadow_(Bool::new(has_shadow).as_raw()) } } } @@ -1291,14 +1282,14 @@ unsafe fn set_min_inner_size(window: V, mut min_size: Logica // If necessary, resize the window to match constraint if 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 { // The origin point of a rectangle is at its bottom left in Cocoa. // To ensure the window's top-left point remains the same: current_rect.origin.y += 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()) } } @@ -1316,13 +1307,13 @@ unsafe fn set_max_inner_size(window: V, mut max_size: Logica // If necessary, resize the window to match constraint if 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 { // The origin point of a rectangle is at its bottom left in Cocoa. // To ensure the window's top-left point remains the same: current_rect.origin.y += 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()) } } diff --git a/src/platform_impl/macos/window_delegate.rs b/src/platform_impl/macos/window_delegate.rs index 0dc5e8575e6..ba3636dad8c 100644 --- a/src/platform_impl/macos/window_delegate.rs +++ b/src/platform_impl/macos/window_delegate.rs @@ -10,9 +10,9 @@ use cocoa::{ foundation::NSUInteger, }; use objc::{ - declare::ClassDecl, + declare::ClassBuilder, rc::autoreleasepool, - runtime::{Class, Object, Sel, BOOL, NO, YES}, + runtime::{Bool, Class, Object, Sel}, }; use once_cell::sync::Lazy; @@ -137,7 +137,7 @@ unsafe impl Sync for WindowDelegateClass {} static WINDOW_DELEGATE_CLASS: Lazy = Lazy::new(|| unsafe { 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(_, _)); decl.add_method( @@ -232,7 +232,7 @@ static WINDOW_DELEGATE_CLASS: Lazy = Lazy::new(|| unsafe { // boilerplate and wouldn't really clarify anything... fn with_state T, T>(this: &Object, callback: F) { 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) }; callback(state_ptr); @@ -257,10 +257,10 @@ 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:"); with_state(this, |state| state.emit_event(WindowEvent::CloseRequested)); - NO + Bool::NO } extern "C" fn window_will_close(this: &Object, _: Sel, _: id) { @@ -324,7 +324,7 @@ extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) { // to an id) let view_state: &mut ViewState = unsafe { 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) }; @@ -339,7 +339,7 @@ extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) { } /// 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:"); use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration}; @@ -362,17 +362,17 @@ extern "C" fn dragging_entered(this: &Object, _: Sel, sender: id) -> BOOL { } } - YES + Bool::YES } /// 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:"); - YES + Bool::YES } /// 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:"); use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration}; @@ -395,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