Skip to content

Commit

Permalink
Rename Class, Object and Protocol to AnyClass, AnyObject and AnyProtocol
Browse files Browse the repository at this point in the history
To match Swift's naming, and to be able to call the `ClassType` trait for just `Class` in the future
  • Loading branch information
madsmtm committed Jun 22, 2023
1 parent d8e5065 commit ceae1e4
Show file tree
Hide file tree
Showing 128 changed files with 1,662 additions and 1,635 deletions.
18 changes: 9 additions & 9 deletions crates/header-translator/src/rust_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,18 +358,18 @@ impl fmt::Display for IdType {
Ok(())
}
Self::AnyObject { protocols } => match &**protocols {
[] => write!(f, "Object"),
[] => write!(f, "AnyObject"),
[id] if id.is_nsobject() => write!(f, "NSObject"),
[id] if id.name == "NSCopying" || id.name == "NSMutableCopying" => {
write!(f, "Object")
write!(f, "AnyObject")
}
[id] => write!(f, "ProtocolObject<dyn {}>", id.path()),
// TODO: Handle this better
_ => write!(f, "TodoProtocols"),
},
Self::TypeDef { id, .. } => write!(f, "{}", id.path()),
Self::GenericParam { name } => write!(f, "{name}"),
Self::AnyProtocol => write!(f, "Protocol"),
Self::AnyProtocol => write!(f, "AnyProtocol"),
// TODO: Handle this better
Self::AnyClass { .. } => write!(f, "TodoClass"),
Self::Self_ { .. } => write!(f, "Self"),
Expand Down Expand Up @@ -1052,9 +1052,9 @@ impl fmt::Display for Inner {
}
Class { nullability } => {
if *nullability == Nullability::NonNull {
write!(f, "NonNull<Class>")
write!(f, "NonNull<AnyClass>")
} else {
write!(f, "*const Class")
write!(f, "*const AnyClass")
}
}
Sel { nullability } => {
Expand Down Expand Up @@ -1546,9 +1546,9 @@ impl fmt::Display for Ty {
}
Inner::Class { nullability } => {
if *nullability == Nullability::NonNull {
write!(f, "&'static Class")
write!(f, "&'static AnyClass")
} else {
write!(f, "Option<&'static Class>")
write!(f, "Option<&'static AnyClass>")
}
}
Inner::C99Bool => {
Expand Down Expand Up @@ -1648,9 +1648,9 @@ impl fmt::Display for Ty {
}
Inner::Class { nullability } => {
if *nullability == Nullability::NonNull {
write!(f, "&Class")
write!(f, "&AnyClass")
} else {
write!(f, "Option<&Class>")
write!(f, "Option<&AnyClass>")
}
}
Inner::C99Bool if self.kind == TyKind::MethodArgument => {
Expand Down
2 changes: 1 addition & 1 deletion crates/header-translator/src/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1280,7 +1280,7 @@ impl fmt::Display for Stmt {
if !generics.is_empty() {
write!(f, "<")?;
for generic in generics {
write!(f, "{generic}: Message = Object, ")?;
write!(f, "{generic}: Message = AnyObject, ")?;
}
write!(f, ">")?;
};
Expand Down
2 changes: 1 addition & 1 deletion crates/header-translator/translation-config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -1235,7 +1235,7 @@ skipped = true
menuHasKeyEquivalent_forEvent_target_action = { skipped = true }

# These subclass a generic struct, and hence the type parameter defaults to
# `Object`, which is not PartialEq, Eq nor Hash.
# `AnyObject`, which is not PartialEq, Eq nor Hash.
[class.NSLayoutXAxisAnchor]
derives = "Debug"
[class.NSLayoutYAxisAnchor]
Expand Down
6 changes: 3 additions & 3 deletions crates/icrate/examples/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use objc2::{
declare_class, extern_methods, msg_send,
mutability::InteriorMutable,
rc::{Allocated, Id},
runtime::{Object, ProtocolObject, Sel},
runtime::{AnyObject, ProtocolObject, Sel},
sel, ClassType,
};

Expand Down Expand Up @@ -169,7 +169,7 @@ fn main() {
let back_button = {
// configure the button to navigate the webview backward
let title = ns_string!("back");
let target = Some::<&Object>(&web_view);
let target = Some::<&AnyObject>(&web_view);
let action = Some(sel!(goBack));
let this = unsafe { NSButton::buttonWithTitle_target_action(title, target, action) };
unsafe { this.setBezelStyle(NSBezelStyleShadowlessSquare) };
Expand All @@ -180,7 +180,7 @@ fn main() {
let forward_button = {
// configure the button to navigate the web view forward
let title = ns_string!("forward");
let target = Some::<&Object>(&web_view);
let target = Some::<&AnyObject>(&web_view);
let action = Some(sel!(goForward));
let this = unsafe { NSButton::buttonWithTitle_target_action(title, target, action) };
unsafe { this.setBezelStyle(NSBezelStyleShadowlessSquare) };
Expand Down
6 changes: 3 additions & 3 deletions crates/icrate/examples/delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use icrate::ns_string;
use icrate::Foundation::{NSCopying, NSObject, NSString};
use objc2::declare::{Ivar, IvarBool, IvarDrop, IvarEncode};
use objc2::rc::Id;
use objc2::runtime::Object;
use objc2::runtime::AnyObject;
use objc2::{declare_class, msg_send, msg_send_id, mutability, ClassType};

#[cfg(target_os = "macos")]
Expand Down Expand Up @@ -71,7 +71,7 @@ declare_class!(
unsafe impl CustomAppDelegate {
/// This is `unsafe` because it expects `sender` to be valid
#[method(applicationDidFinishLaunching:)]
unsafe fn did_finish_launching(&self, sender: *mut Object) {
unsafe fn did_finish_launching(&self, sender: *mut AnyObject) {
println!("Did finish launching!");
// Do something with `sender`
dbg!(sender);
Expand All @@ -80,7 +80,7 @@ declare_class!(
/// Some comment before `sel`.
#[method(applicationWillTerminate:)]
/// Some comment after `sel`.
fn will_terminate(&self, _: *mut Object) {
fn will_terminate(&self, _: *mut AnyObject) {
println!("Will terminate!");
}
}
Expand Down
10 changes: 5 additions & 5 deletions crates/icrate/examples/nspasteboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use icrate::AppKit::{NSPasteboard, NSPasteboardTypeString};
use icrate::Foundation::{NSArray, NSCopying, NSString};
use objc2::rc::Id;
use objc2::runtime::{Class, Object, ProtocolObject};
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2::ClassType;

/// Simplest implementation
Expand All @@ -20,18 +20,18 @@ pub fn get_text_1(pasteboard: &NSPasteboard) -> Option<Id<NSString>> {
pub fn get_text_2(pasteboard: &NSPasteboard) -> Option<Id<NSString>> {
// The NSPasteboard API is a bit weird, it requires you to pass classes as
// objects, which `icrate::Foundation::NSArray` was not really made for -
// so we convert the class to an `Object` type instead.
// so we convert the class to an `AnyObject` type instead.
//
// TODO: Investigate and find a better way to express this in `objc2`.
let string_class = {
let cls: *const Class = NSString::class();
let cls = cls as *mut Object;
let cls: *const AnyClass = NSString::class();
let cls = cls as *mut AnyObject;
unsafe { Id::new(cls).unwrap() }
};
let class_array = NSArray::from_vec(vec![string_class]);
let objects = unsafe { pasteboard.readObjectsForClasses_options(&class_array, None) };

let obj: *const Object = objects?.first()?;
let obj: *const AnyObject = objects?.first()?;
// And this part is weird as well, since we now have to convert the object
// into an NSString, which we know it to be since that's what we told
// `readObjectsForClasses:options:`.
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/AppKit/fixes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ extern_class!(
__inner_extern_class!(
#[cfg(feature = "AppKit_NSLayoutAnchor")]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct NSLayoutAnchor<AnchorType: Message = Object> {
pub struct NSLayoutAnchor<AnchorType: Message = AnyObject> {
__superclass: NSObject,
_inner0: PhantomData<*mut AnchorType>,
notunwindsafe: PhantomData<&'static mut ()>,
Expand Down
10 changes: 5 additions & 5 deletions crates/icrate/src/Foundation/__macro_helpers/ns_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
use core::ffi::c_void;

use crate::Foundation::NSString;
use objc2::runtime::Class;
use objc2::runtime::AnyClass;

// This is defined in CoreFoundation, but we don't emit a link attribute
// here because it is already linked via Foundation.
//
// Although this is a "private" (underscored) symbol, it is directly
// referenced in Objective-C binaries. So it's safe for us to reference.
extern "C" {
pub static __CFConstantStringClassReference: Class;
pub static __CFConstantStringClassReference: AnyClass;
}

/// Structure used to describe a constant `CFString`.
Expand All @@ -38,7 +38,7 @@ extern "C" {
/// [`CF_CONST_STRING`]: <https://github.com/apple-oss-distributions/CF/blob/CF-1153.18/CFInternal.h#L332-L336>
#[repr(C)]
pub struct CFConstString {
isa: &'static Class,
isa: &'static AnyClass,
// Important that we don't use `usize` here, since that would be wrong on
// big-endian systems!
cfinfo: u32,
Expand Down Expand Up @@ -66,7 +66,7 @@ impl CFConstString {
const FLAGS_ASCII: u32 = 0x07_C8;
const FLAGS_UTF16: u32 = 0x07_D0;

pub const unsafe fn new_ascii(isa: &'static Class, data: &'static [u8]) -> Self {
pub const unsafe fn new_ascii(isa: &'static AnyClass, data: &'static [u8]) -> Self {
Self {
isa,
cfinfo: Self::FLAGS_ASCII,
Expand All @@ -78,7 +78,7 @@ impl CFConstString {
}
}

pub const unsafe fn new_utf16(isa: &'static Class, data: &'static [u16]) -> Self {
pub const unsafe fn new_utf16(isa: &'static AnyClass, data: &'static [u16]) -> Self {
Self {
isa,
cfinfo: Self::FLAGS_UTF16,
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/Foundation/additions/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl<T: Message> NSArray<T> {
// now safely take ownership (even if `T` is mutable).
unsafe { Self::initWithObjects_count(Self::alloc(), ptr, len) }
// The drop of `Vec` here would invalidate our mutable pointer,
// except for the fact that we're using `UnsafeCell` in `Object`.
// except for the fact that we're using `UnsafeCell` in `AnyObject`.
}

pub fn from_id_slice(slice: &[Id<T>]) -> Id<Self>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl NSAttributedString {
#[cfg(feature = "Foundation_NSString")]
pub unsafe fn new_with_attributes(
string: &Foundation::NSString,
attributes: &Foundation::NSDictionary<NSAttributedStringKey, Object>,
attributes: &Foundation::NSDictionary<NSAttributedStringKey, AnyObject>,
) -> Id<Self> {
unsafe { Self::initWithString_attributes(Self::alloc(), string, Some(attributes)) }
}
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/Foundation/additions/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl NSBundle {
let info = self.infoDictionary()?;
// TODO: Use ns_string!
let name = info.get(&NSString::from_str("CFBundleName"))?;
let ptr: *const Object = name;
let ptr: *const AnyObject = name;
let ptr: *const NSString = ptr.cast();
// SAFETY: TODO
let name = unsafe { ptr.as_ref().unwrap_unchecked() };
Expand Down
9 changes: 4 additions & 5 deletions crates/icrate/src/Foundation/additions/dictionary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use core::panic::{RefUnwindSafe, UnwindSafe};
use core::ptr::{self, NonNull};

use objc2::mutability::IsMutable;
use objc2::runtime::Object;

use super::iter;
use super::util;
Expand All @@ -27,7 +26,7 @@ impl<K: Message, V: Message> NSDictionary<K, V> {
let count = min(keys.len(), vals.len());

let keys: *mut NonNull<T> = util::ref_ptr_cast_const(keys.as_ptr());
let keys: *mut NonNull<Object> = keys.cast();
let keys: *mut NonNull<AnyObject> = keys.cast();
let vals = util::id_ptr_cast(vals.as_mut_ptr());

unsafe { Self::initWithObjects_forKeys_count(Self::alloc(), vals, keys, count) }
Expand All @@ -44,7 +43,7 @@ impl<K: Message, V: Message> NSMutableDictionary<K, V> {
let count = min(keys.len(), vals.len());

let keys: *mut NonNull<T> = util::ref_ptr_cast_const(keys.as_ptr());
let keys: *mut NonNull<Object> = keys.cast();
let keys: *mut NonNull<AnyObject> = keys.cast();
let vals = util::id_ptr_cast(vals.as_mut_ptr());

unsafe { Self::initWithObjects_forKeys_count(Self::alloc(), vals, keys, count) }
Expand Down Expand Up @@ -215,8 +214,8 @@ impl<K: Message, V: Message> NSMutableDictionary<K, V> {
.get(&key)
.map(|old_obj| unsafe { util::mutable_collection_retain_removed_id(old_obj) });

// SAFETY: It is always safe to transmute an `Id` to `Object`.
let key: Id<Object> = unsafe { Id::cast(key) };
// SAFETY: It is always safe to transmute an `Id` to `AnyObject`.
let key: Id<AnyObject> = unsafe { Id::cast(key) };
// SAFETY: We have ownership over both the key and the value.
unsafe { self.setObject_forKey(&value, &key) };
old_obj
Expand Down
4 changes: 2 additions & 2 deletions crates/icrate/src/Foundation/additions/exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl NSException {
pub fn new(
name: &NSExceptionName,
reason: Option<&Foundation::NSString>,
user_info: Option<&Foundation::NSDictionary<Object, Object>>,
user_info: Option<&Foundation::NSDictionary<AnyObject, AnyObject>>,
) -> Option<Id<Self>> {
unsafe {
msg_send_id![
Expand Down Expand Up @@ -91,7 +91,7 @@ impl NSException {
#[cfg(feature = "Foundation_NSString")]
impl fmt::Debug for NSException {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let obj: &Object = self.as_ref();
let obj: &AnyObject = self.as_ref();
write!(f, "{obj:?} '{}'", self.name())?;
if let Some(reason) = self.reason() {
write!(f, " reason:{reason}")?;
Expand Down
4 changes: 2 additions & 2 deletions crates/icrate/src/Foundation/additions/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const BUF_SIZE: usize = 16;
#[derive(Debug, PartialEq)]
struct FastEnumeratorHelper {
state: NSFastEnumerationState,
buf: [*mut Object; BUF_SIZE],
buf: [*mut AnyObject; BUF_SIZE],
// TODO: We could possibly optimize things a bit by doing
// `itemsPtr.add(1); items_count -= 1;` on every loop, instead of storing
// `current_item` - but it's not really defined whether we're allowed to
Expand Down Expand Up @@ -136,7 +136,7 @@ impl FastEnumeratorHelper {
unsafe fn next_from(
&mut self,
collection: &ProtocolObject<dyn NSFastEnumeration>,
) -> Option<NonNull<Object>> {
) -> Option<NonNull<AnyObject>> {
// If we've exhausted the current array of items.
if self.current_item >= self.items_count {
// Get the next array of items.
Expand Down
7 changes: 3 additions & 4 deletions crates/icrate/src/Foundation/additions/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,13 @@ fn make_multithreaded() {
/// Use when designing APIs that are only safe to use on the main thread:
///
/// ```no_run
/// use icrate::Foundation::MainThreadMarker;
/// use icrate::objc2::runtime::Object;
/// use icrate::Foundation::{MainThreadMarker, NSObject};
/// use icrate::objc2::msg_send;
/// # let obj = 0 as *const Object;
/// # let obj = 0 as *const NSObject;
///
/// // This action requires the main thread, so we take a marker as parameter.
/// // It signals clearly to users "this requires the main thread".
/// unsafe fn do_thing(obj: *const Object, _mtm: MainThreadMarker) {
/// unsafe fn do_thing(obj: *const NSObject, _mtm: MainThreadMarker) {
/// msg_send![obj, someActionThatRequiresTheMainThread]
/// }
///
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/Foundation/fixes/enumerator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::common::*;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NSFastEnumerationState {
pub state: c_ulong,
pub itemsPtr: *mut *mut Object,
pub itemsPtr: *mut *mut AnyObject,
pub mutationsPtr: *mut c_ulong,
pub extra: [c_ulong; 5],
}
Expand Down
Loading

0 comments on commit ceae1e4

Please sign in to comment.