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
- macOS/iOS: Use `objc2` instead of `objc` internally.
- **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:**: Removed deprecated method `platform::unix::WindowExtUnix::is_ready`.

View File

@ -62,12 +62,14 @@ ndk = "0.7.0"
ndk-glue = "0.7.0"
[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]
cocoa = "0.24"
core-foundation = "0.9"
core-graphics = "0.22"
# Branch: objc2
# TODO: Use non-git versions before we release
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"
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]

View File

@ -9,7 +9,8 @@ use std::{
time::Instant,
};
use objc::runtime::{BOOL, YES};
use objc::foundation::{NSInteger, NSUInteger};
use objc::runtime::Object;
use once_cell::sync::Lazy;
use crate::{
@ -21,8 +22,8 @@ use crate::{
ffi::{
id, kCFRunLoopCommonModes, CFAbsoluteTimeGetCurrent, CFRelease, CFRunLoopAddTimer,
CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate,
CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CGRect, CGSize, NSInteger,
NSOperatingSystemVersion, NSUInteger,
CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CGRect, CGSize,
NSOperatingSystemVersion,
},
},
window::WindowId as RootWindowId,
@ -472,10 +473,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 +500,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();
@ -582,7 +577,7 @@ pub unsafe fn did_finish_launching() {
let _: () = msg_send![window, setScreen: screen];
let _: () = msg_send![screen, release];
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, 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 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 +1017,7 @@ pub fn os_capabilities() -> OSCapabilities {
static OS_CAPABILITIES: Lazy<OSCapabilities> = 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 +1028,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()

View File

@ -81,9 +81,10 @@ pub(crate) struct PlatformSpecificEventLoopAttributes {}
impl<T: 'static> 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;
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. \

View File

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

View File

@ -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)*);
}
};

View File

@ -4,12 +4,14 @@ use std::{
ops::{Deref, DerefMut},
};
use objc::foundation::{NSInteger, NSUInteger};
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode},
platform_impl::platform::{
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;
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 +138,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 +167,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 {

View File

@ -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,15 +66,15 @@ 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:),
setter as extern "C" fn(&mut Object, Sel, $t),
setter as extern "C" fn(_, _, _),
);
$decl.add_method(
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 || {
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,
@ -156,11 +156,12 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
untrusted_scale_factor: CGFloat,
) {
unsafe {
let superclass: &'static Class = msg_send![object, superclass];
let superclass: &'static Class = msg_send![&*object, superclass];
let _: () = msg_send![
super(object, superclass),
super(&mut *object, superclass),
setContentScaleFactor: untrusted_scale_factor
];
let object = &*object; // Immutable for rest of method
let window: id = msg_send![object, window];
// `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_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 _,
@ -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`");
ID += 1;
decl.add_method(
sel!(drawRect:),
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(sel!(drawRect:), draw_rect as extern "C" fn(_, _, _));
decl.add_method(sel!(layoutSubviews), layout_subviews as extern "C" fn(_, _));
decl.add_method(
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(
sel!(touchesBegan:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id),
handle_touches as extern "C" fn(_, _, _, _),
);
decl.add_method(
sel!(touchesMoved:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id),
handle_touches as extern "C" fn(_, _, _, _),
);
decl.add_method(
sel!(touchesEnded:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id),
handle_touches as extern "C" fn(_, _, _, _),
);
decl.add_method(
sel!(touchesCancelled:withEvent:),
handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id),
handle_touches as extern "C" fn(_, _, _, _),
);
decl.register()
@ -325,19 +320,19 @@ 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),
should_autorotate as extern "C" fn(&Object, Sel) -> BOOL,
should_autorotate as extern "C" fn(_, _) -> _,
);
add_property! {
decl,
prefers_status_bar_hidden: BOOL,
prefers_status_bar_hidden: Bool,
setPrefersStatusBarHidden: |object| {
unsafe {
let _: () = msg_send![object, setNeedsStatusBarAppearanceUpdate];
@ -347,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;
@ -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`");
decl.add_method(
sel!(becomeKeyWindow),
become_key_window as extern "C" fn(&Object, Sel),
become_key_window as extern "C" fn(_, _),
);
decl.add_method(
sel!(resignKeyWindow),
resign_key_window as extern "C" fn(&Object, Sel),
resign_key_window as extern "C" fn(_, _),
);
CLASS = Some(decl.register());
@ -440,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];
}
@ -466,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();
@ -545,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) {
@ -574,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,
@ -588,35 +576,35 @@ 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(
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(
sel!(applicationDidBecomeActive:),
did_become_active as extern "C" fn(&Object, Sel, id),
did_become_active as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(applicationWillResignActive:),
will_resign_active as extern "C" fn(&Object, Sel, id),
will_resign_active as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(applicationWillEnterForeground:),
will_enter_foreground as extern "C" fn(&Object, Sel, id),
will_enter_foreground as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(applicationDidEnterBackground:),
did_enter_background as extern "C" fn(&Object, Sel, id),
did_enter_background as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(applicationWillTerminate:),
will_terminate as extern "C" fn(&Object, Sel, id),
will_terminate as extern "C" fn(_, _, _),
);
decl.register();

View File

@ -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<bool> {
@ -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
}

View File

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

View File

@ -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,18 +25,18 @@ unsafe impl Sync for AppDelegateClass {}
pub static APP_DELEGATE_CLASS: Lazy<AppDelegateClass> = 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(&Class, Sel) -> id);
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel));
decl.add_class_method(sel!(new), new as extern "C" fn(_, _) -> _);
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _));
decl.add_method(
sel!(applicationDidFinishLaunching:),
did_finish_launching as extern "C" fn(&Object, Sel, id),
did_finish_launching as extern "C" fn(_, _, _),
);
decl.add_method(
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);
@ -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
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<AuxDelegateState>)).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<AuxDelegateState>));

View File

@ -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<EventWrapper>) {
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);
@ -403,7 +402,7 @@ impl AppState {
unsafe {
let app: id = NSApp();
autoreleasepool(|| {
autoreleasepool(|_| {
let _: () = msg_send![app, stop: nil];
// To stop event loop immediately, we need to post some event here.
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`
// 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 {

View File

@ -13,9 +13,10 @@ use std::{
use cocoa::{
appkit::{NSApp, NSEventModifierFlags, NSEventSubtype, NSEventType::NSApplicationDefined},
base::{id, nil, BOOL, NO, YES},
foundation::{NSInteger, NSPoint, NSTimeInterval},
base::{id, nil},
foundation::{NSPoint, NSTimeInterval},
};
use objc::foundation::is_main_thread;
use objc::rc::autoreleasepool;
use raw_window_handle::{AppKitDisplayHandle, RawDisplayHandle};
@ -144,8 +145,7 @@ impl Default for PlatformSpecificEventLoopAttributes {
impl<T> EventLoop<T> {
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!");
}
@ -161,7 +161,7 @@ impl<T> EventLoop<T> {
aux_state.activation_policy = attributes.activation_policy;
aux_state.default_menu = attributes.default_menu;
autoreleasepool(|| {
autoreleasepool(|_| {
let _: () = msg_send![app, setDelegate:*delegate];
});
@ -209,7 +209,7 @@ impl<T> EventLoop<T> {
self._callback = Some(Rc::clone(&callback));
let exit_code = autoreleasepool(|| unsafe {
let exit_code = autoreleasepool(|_| unsafe {
let app = NSApp();
assert_ne!(app, nil);
@ -246,13 +246,13 @@ pub unsafe fn post_dummy_event(target: id) {
location: NSPoint::new(0.0, 0.0)
modifierFlags: NSEventModifierFlags::empty()
timestamp: 0 as NSTimeInterval
windowNumber: 0 as NSInteger
windowNumber: 0isize
context: nil
subtype: NSEventSubtype::NSWindowExposedEventType
data1: 0 as NSInteger
data2: 0 as NSInteger
data1: 0isize
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

View File

@ -4,10 +4,7 @@
use std::ffi::c_void;
use cocoa::{
base::id,
foundation::{NSInteger, NSUInteger},
};
use cocoa::base::id;
use core_foundation::{
array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef,
};
@ -15,34 +12,10 @@ use core_graphics::{
base::CGError,
display::{CGDirectDisplayID, CGDisplayConfigRef},
};
use objc::foundation::{NSInteger, NSUInteger};
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 {
unsafe fn alloc(_: Self) -> id {
msg_send![class!(NSMutableAttributedString), alloc]

View File

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

View File

@ -75,7 +75,7 @@ impl Window {
attributes: WindowAttributes,
pl_attribs: PlatformSpecificWindowBuilderAttributes,
) -> 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 })
}
}

View File

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

View File

@ -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());
}
}
});
@ -229,7 +229,7 @@ pub unsafe fn set_title_async(ns_window: id, title: String) {
pub unsafe fn close_async(ns_window: IdRef) {
let ns_window = MainThreadSafe(ns_window);
Queue::main().exec_async(move || {
autoreleasepool(move || {
autoreleasepool(move |_| {
ns_window.close();
});
});

View File

@ -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 *const [u8]
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];

View File

@ -9,10 +9,11 @@ use std::os::raw::c_uchar;
use cocoa::{
appkit::{CGFloat, NSApp, NSWindowStyleMask},
base::{id, nil},
foundation::{NSPoint, NSRect, NSString, NSUInteger},
foundation::{NSPoint, NSRect, NSString},
};
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::platform_impl::platform::ffi;
@ -28,7 +29,7 @@ where
bitset & flag == flag
}
pub const EMPTY_RANGE: ffi::NSRange = ffi::NSRange {
pub const EMPTY_RANGE: NSRange = NSRange {
location: ffi::NSNotFound as NSUInteger,
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`
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 {

View File

@ -12,11 +12,12 @@ use std::{
use cocoa::{
appkit::{NSApp, NSEvent, NSEventModifierFlags, NSEventPhase, NSView, NSWindow},
base::{id, nil},
foundation::{NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger},
foundation::{NSPoint, NSRect, NSSize, NSString},
};
use objc::{
declare::ClassDecl,
runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
declare::ClassBuilder,
foundation::{NSInteger, NSRange, NSUInteger},
runtime::{Bool, Class, Object, Protocol, Sel},
};
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>) {
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 +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) {
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 +142,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,170 +165,135 @@ unsafe impl Sync for ViewClass {}
static VIEW_CLASS: Lazy<ViewClass> = Lazy::new(|| unsafe {
let superclass = class!(NSView);
let mut decl = ClassDecl::new("WinitView", superclass).unwrap();
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel));
let mut decl = ClassBuilder::new("WinitView", superclass).unwrap();
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _));
decl.add_method(
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(
sel!(viewDidMoveToWindow),
view_did_move_to_window as extern "C" fn(&Object, Sel),
);
decl.add_method(
sel!(drawRect:),
draw_rect as extern "C" fn(&Object, Sel, NSRect),
view_did_move_to_window as extern "C" fn(_, _),
);
decl.add_method(sel!(drawRect:), draw_rect as extern "C" fn(_, _, _));
decl.add_method(
sel!(acceptsFirstResponder),
accepts_first_responder as extern "C" fn(&Object, Sel) -> BOOL,
);
decl.add_method(
sel!(touchBar),
touch_bar 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(_, _) -> _);
decl.add_method(
sel!(resetCursorRects),
reset_cursor_rects as extern "C" fn(&Object, Sel),
reset_cursor_rects as extern "C" fn(_, _),
);
// ------------------------------------------------------------------
// NSTextInputClient
decl.add_method(
sel!(hasMarkedText),
has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
);
decl.add_method(
sel!(markedRange),
marked_range as extern "C" fn(&Object, Sel) -> NSRange,
has_marked_text as extern "C" fn(_, _) -> _,
);
decl.add_method(sel!(markedRange), marked_range as extern "C" fn(_, _) -> _);
decl.add_method(
sel!(selectedRange),
selected_range as extern "C" fn(&Object, Sel) -> NSRange,
selected_range as extern "C" fn(_, _) -> _,
);
decl.add_method(
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(
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(
sel!(attributedSubstringForProposedRange:actualRange:),
attributed_substring_for_proposed_range
as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
attributed_substring_for_proposed_range as extern "C" fn(_, _, _, _) -> _,
);
decl.add_method(
sel!(insertText:replacementRange:),
insert_text as extern "C" fn(&Object, Sel, id, NSRange),
insert_text as extern "C" fn(_, _, _, _),
);
decl.add_method(
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(
sel!(firstRectForCharacterRange:actualRange:),
first_rect_for_character_range
as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> NSRect,
first_rect_for_character_range as extern "C" fn(_, _, _, _) -> _,
);
decl.add_method(
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!(keyUp:), key_up as extern "C" fn(&Object, Sel, id));
decl.add_method(
sel!(flagsChanged:),
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(sel!(keyDown:), key_down as extern "C" fn(_, _, _));
decl.add_method(sel!(keyUp:), key_up as extern "C" fn(_, _, _));
decl.add_method(sel!(flagsChanged:), flags_changed as extern "C" fn(_, _, _));
decl.add_method(sel!(insertTab:), insert_tab as extern "C" fn(_, _, _));
decl.add_method(
sel!(insertBackTab:),
insert_back_tab as extern "C" fn(&Object, Sel, id),
insert_back_tab as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(mouseDown:),
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(sel!(mouseDown:), mouse_down as extern "C" fn(_, _, _));
decl.add_method(sel!(mouseUp:), mouse_up as extern "C" fn(_, _, _));
decl.add_method(
sel!(rightMouseDown:),
right_mouse_down as extern "C" fn(&Object, Sel, id),
right_mouse_down as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(rightMouseUp:),
right_mouse_up as extern "C" fn(&Object, Sel, id),
right_mouse_up as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(otherMouseDown:),
other_mouse_down as extern "C" fn(&Object, Sel, id),
other_mouse_down as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(otherMouseUp:),
other_mouse_up as extern "C" fn(&Object, Sel, id),
);
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),
other_mouse_up as extern "C" fn(_, _, _),
);
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(
sel!(rightMouseDragged:),
right_mouse_dragged as extern "C" fn(&Object, Sel, id),
right_mouse_dragged as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(otherMouseDragged:),
other_mouse_dragged as extern "C" fn(&Object, Sel, id),
);
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),
other_mouse_dragged as extern "C" fn(_, _, _),
);
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(
sel!(magnifyWithEvent:),
magnify_with_event as extern "C" fn(&Object, Sel, id),
magnify_with_event as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(rotateWithEvent:),
rotate_with_event as extern "C" fn(&Object, Sel, id),
rotate_with_event as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(pressureChangeWithEvent:),
pressure_change_with_event as extern "C" fn(&Object, Sel, id),
pressure_change_with_event as extern "C" fn(_, _, _),
);
decl.add_method(
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(
sel!(cancelOperation:),
cancel_operation as extern "C" fn(&Object, Sel, id),
cancel_operation as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(frameDidChange:),
frame_did_change as extern "C" fn(&Object, Sel, id),
frame_did_change as extern "C" fn(_, _, _),
);
decl.add_method(
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::<id>("markedText");
@ -338,9 +304,9 @@ static VIEW_CLASS: Lazy<ViewClass> = 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));
}
}
@ -353,7 +319,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
let marked_text =
<id as NSMutableAttributedString>::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];
@ -364,7 +330,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
notification_center,
addObserver: this
selector: sel!(frameDidChange:)
name: frame_did_change_notification_name
name: *frame_did_change_notification_name
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) {
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() {
@ -386,11 +352,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::<c_void>()
assumeInside:NO
let tracking_rect: NSInteger = msg_send![
this,
addTrackingRect: rect,
owner: this,
userData: ptr::null_mut::<c_void>(),
assumeInside: false
];
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) {
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() {
@ -407,11 +374,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::<c_void>()
assumeInside:NO
let tracking_rect: NSInteger = msg_send![
this,
addTrackingRect: rect,
owner: this,
userData: ptr::null_mut::<c_void>(),
assumeInside: false,
];
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) {
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)));
@ -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");
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];
@ -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");
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)
@ -516,13 +484,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);
@ -530,7 +498,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);
@ -568,7 +536,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];
@ -576,7 +544,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)),
@ -619,7 +587,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));
@ -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) {
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);
@ -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
// 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
@ -675,8 +643,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;
}
@ -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) {
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));
@ -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) {
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;
@ -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) {
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);
@ -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) {
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;
@ -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) {
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);
@ -1045,7 +1013,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...
@ -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) {
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 {
@ -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) {
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 {
@ -1144,12 +1112,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 {
@ -1184,7 +1152,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);
@ -1208,7 +1176,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();
@ -1237,7 +1205,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();
@ -1268,7 +1236,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();
@ -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.
// 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
}

View File

@ -42,13 +42,14 @@ use cocoa::{
NSRequestUserAttentionType, NSScreen, NSView, NSWindow, NSWindowButton, NSWindowStyleMask,
},
base::{id, nil},
foundation::{NSDictionary, NSPoint, NSRect, NSSize, NSUInteger},
foundation::{NSDictionary, NSPoint, NSRect, NSSize},
};
use core_graphics::display::{CGDisplay, CGDisplayMode};
use objc::{
declare::ClassDecl,
declare::ClassBuilder,
foundation::{is_main_thread, NSUInteger},
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)
@ -141,7 +142,7 @@ fn create_window(
attrs: &WindowAttributes,
pl_attrs: &PlatformSpecificWindowBuilderAttributes,
) -> Option<IdRef> {
autoreleasepool(|| unsafe {
autoreleasepool(|_| unsafe {
let screen = match attrs.fullscreen {
Some(Fullscreen::Borderless(Some(RootMonitorHandle { inner: ref monitor })))
| Some(Fullscreen::Exclusive(RootVideoMode {
@ -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,18 +232,15 @@ 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 {
let _: () = msg_send![
*ns_window,
setLevel: ffi::NSWindowLevel::NSFloatingWindowLevel
];
let _: () = msg_send![*ns_window, setLevel: ffi::kCGFloatingWindowLevelKey];
}
if let Some(increments) = pl_attrs.resize_increments {
@ -254,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();
@ -270,25 +268,25 @@ unsafe impl Sync for WindowClass {}
static WINDOW_CLASS: Lazy<WindowClass> = 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(
sel!(canBecomeMainWindow),
can_become_main_window as extern "C" fn(&Object, Sel) -> BOOL,
can_become_main_window as extern "C" fn(_, _) -> _,
);
decl.add_method(
sel!(canBecomeKeyWindow),
can_become_key_window as extern "C" fn(&Object, Sel) -> BOOL,
can_become_key_window as extern "C" fn(_, _) -> _,
);
WindowClass(decl.register())
});
@ -396,11 +394,8 @@ impl UnownedWindow {
mut win_attribs: WindowAttributes,
pl_attribs: PlatformSpecificWindowBuilderAttributes,
) -> Result<(Arc<Self>, 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");
@ -420,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));
}
@ -519,8 +514,8 @@ impl UnownedWindow {
#[inline]
pub fn is_visible(&self) -> Option<bool> {
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) {
@ -625,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) {
@ -726,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 {
@ -767,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;
}
@ -998,10 +991,7 @@ impl UnownedWindow {
// Restore the normal window level following the Borderless fullscreen
// `CGShieldingWindowLevel() + 1` hack.
let _: () = msg_send![
*self.ns_window,
setLevel: ffi::NSWindowLevel::NSNormalWindowLevel
];
let _: () = msg_send![*self.ns_window, setLevel: ffi::kCGBaseWindowLevelKey];
},
_ => {}
};
@ -1088,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);
}
}
@ -1223,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(
@ -1238,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 {
@ -1251,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
}
@ -1261,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()) }
}
}
@ -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 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())
}
}
@ -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 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())
}
}

View File

@ -7,12 +7,12 @@ use std::{
use cocoa::{
appkit::{self, NSApplicationPresentationOptions, NSView, NSWindow, NSWindowOcclusionState},
base::{id, nil},
foundation::NSUInteger,
};
use objc::{
declare::ClassDecl,
declare::ClassBuilder,
foundation::NSUInteger,
rc::autoreleasepool,
runtime::{Class, Object, Sel, BOOL, NO, YES},
runtime::{Bool, Class, Object, Sel},
};
use once_cell::sync::Lazy;
@ -137,92 +137,91 @@ unsafe impl Sync for WindowDelegateClass {}
static WINDOW_DELEGATE_CLASS: Lazy<WindowDelegateClass> = 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(&Object, Sel));
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(_, _));
decl.add_method(
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(
sel!(windowShouldClose:),
window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
window_should_close as extern "C" fn(_, _, _) -> _,
);
decl.add_method(
sel!(windowWillClose:),
window_will_close as extern "C" fn(&Object, Sel, id),
window_will_close as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(windowDidResize:),
window_did_resize as extern "C" fn(&Object, Sel, id),
window_did_resize as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(windowDidMove:),
window_did_move as extern "C" fn(&Object, Sel, id),
window_did_move as extern "C" fn(_, _, _),
);
decl.add_method(
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(
sel!(windowDidBecomeKey:),
window_did_become_key as extern "C" fn(&Object, Sel, id),
window_did_become_key as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(windowDidResignKey:),
window_did_resign_key as extern "C" fn(&Object, Sel, id),
window_did_resign_key as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(draggingEntered:),
dragging_entered as extern "C" fn(&Object, Sel, id) -> BOOL,
dragging_entered as extern "C" fn(_, _, _) -> _,
);
decl.add_method(
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(
sel!(performDragOperation:),
perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
perform_drag_operation as extern "C" fn(_, _, _) -> _,
);
decl.add_method(
sel!(concludeDragOperation:),
conclude_drag_operation as extern "C" fn(&Object, Sel, id),
conclude_drag_operation as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(draggingExited:),
dragging_exited as extern "C" fn(&Object, Sel, id),
dragging_exited as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(window:willUseFullScreenPresentationOptions:),
window_will_use_fullscreen_presentation_options
as extern "C" fn(&Object, Sel, id, NSUInteger) -> NSUInteger,
window_will_use_fullscreen_presentation_options as extern "C" fn(_, _, _, _) -> _,
);
decl.add_method(
sel!(windowDidEnterFullScreen:),
window_did_enter_fullscreen as extern "C" fn(&Object, Sel, id),
window_did_enter_fullscreen as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(windowWillEnterFullScreen:),
window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
window_will_enter_fullscreen as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(windowDidExitFullScreen:),
window_did_exit_fullscreen as extern "C" fn(&Object, Sel, id),
window_did_exit_fullscreen as extern "C" fn(_, _, _),
);
decl.add_method(
sel!(windowWillExitFullScreen:),
window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
window_will_exit_fullscreen as extern "C" fn(_, _, _),
);
decl.add_method(
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(
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");
@ -233,7 +232,7 @@ static WINDOW_DELEGATE_CLASS: Lazy<WindowDelegateClass> = Lazy::new(|| unsafe {
// boilerplate and wouldn't really clarify anything...
fn with_state<F: FnOnce(&mut WindowDelegateState) -> 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);
@ -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:");
with_state(this, |state| state.emit_event(WindowEvent::CloseRequested));
NO
Bool::NO
}
extern "C" fn window_will_close(this: &Object, _: Sel, _: id) {
trace_scope!("windowWillClose:");
with_state(this, |state| unsafe {
// `setDelegate:` retains the previous value and then autoreleases it
autoreleasepool(|| {
autoreleasepool(|_| {
// Since El Capitan, we need to be careful that delegate methods can't
// be called after the window closes.
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)
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)
};
@ -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
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};
@ -363,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};
@ -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
@ -478,7 +477,7 @@ extern "C" fn window_will_use_fullscreen_presentation_options(
options = (NSApplicationPresentationOptions::NSApplicationPresentationFullScreen
| NSApplicationPresentationOptions::NSApplicationPresentationHideDock
| NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar)
.bits();
.bits() as NSUInteger;
}
})
});