Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default Id ownership to Shared #422

Merged
merged 1 commit into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 11 additions & 20 deletions crates/header-translator/src/rust_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,6 @@ impl From<bool> for Ownership {
}
}

impl fmt::Display for Ownership {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Owned => write!(f, "Owned"),
Self::Shared => write!(f, "Shared"),
}
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum TypeParams {
Empty,
Expand Down Expand Up @@ -234,14 +225,14 @@ impl IdType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
IdType::Class {
ownership: Some(ownership),
ownership: Some(Ownership::Owned),
..
}
| IdType::Self_ {
ownership: Some(ownership),
} => write!(f, "{ownership}"),
IdType::GenericParam { name } => write!(f, "{name}Ownership"),
_ => write!(f, "{}", Ownership::Shared),
ownership: Some(Ownership::Owned),
} => write!(f, ", Owned"),
IdType::GenericParam { name } => write!(f, ", {name}Ownership"),
_ => Ok(()),
}
}
}
Expand Down Expand Up @@ -1598,9 +1589,9 @@ impl fmt::Display for Ty {
nullability,
} => {
if *nullability == Nullability::NonNull {
write!(f, "Id<{ty}, {}>", ty.ownership())
write!(f, "Id<{ty}{}>", ty.ownership())
} else {
write!(f, "Option<Id<{ty}, {}>>", ty.ownership())
write!(f, "Option<Id<{ty}{}>>", ty.ownership())
}
}
Inner::Class { nullability } => {
Expand All @@ -1627,7 +1618,7 @@ impl fmt::Display for Ty {
// NULL -> error
write!(
f,
" -> Result<Id<{ty}, {}>, Id<{}, Shared>>",
" -> Result<Id<{ty}{}>, Id<{}>>",
ty.ownership(),
ItemIdentifier::nserror().path(),
)
Expand All @@ -1636,7 +1627,7 @@ impl fmt::Display for Ty {
// NO -> error
write!(
f,
" -> Result<(), Id<{}, Shared>>",
" -> Result<(), Id<{}>>",
ItemIdentifier::nserror().path()
)
}
Expand Down Expand Up @@ -1733,9 +1724,9 @@ impl fmt::Display for Ty {
nullability: inner_nullability,
} if self.kind == TyKind::MethodArgument => {
let tokens = if *inner_nullability == Nullability::NonNull {
format!("Id<{ty}, Shared>")
format!("Id<{ty}>")
} else {
format!("Option<Id<{ty}, Shared>>")
format!("Option<Id<{ty}>>")
};
if *nullability == Nullability::NonNull {
write!(f, "&mut {tokens}")
Expand Down
8 changes: 4 additions & 4 deletions crates/icrate/examples/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use icrate::{
objc2::{
declare::{Ivar, IvarDrop},
declare_class, extern_methods, msg_send,
rc::{Allocated, Id, Shared},
rc::{Allocated, Id},
runtime::{Object, Sel},
sel, ClassType, ProtocolObject,
},
Expand All @@ -24,8 +24,8 @@ use icrate::{

declare_class!(
struct Delegate {
text_field: IvarDrop<Id<NSTextField, Shared>, "_text_field">,
web_view: IvarDrop<Id<WKWebView, Shared>, "_web_view">,
text_field: IvarDrop<Id<NSTextField>, "_text_field">,
web_view: IvarDrop<Id<WKWebView>, "_web_view">,
}
mod ivars;

Expand Down Expand Up @@ -99,7 +99,7 @@ extern_methods!(
this: Option<Allocated<Self>>,
text_field: &NSTextField,
web_view: &WKWebView,
) -> Id<Self, Shared>;
) -> Id<Self>;
}
);

Expand Down
8 changes: 4 additions & 4 deletions crates/icrate/examples/delegate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![cfg_attr(not(target_os = "macos"), allow(unused))]
use icrate::ns_string;
use icrate::objc2::declare::{Ivar, IvarBool, IvarDrop, IvarEncode};
use icrate::objc2::rc::{Id, Shared};
use icrate::objc2::rc::Id;
use icrate::objc2::runtime::Object;
use icrate::objc2::{declare_class, msg_send, msg_send_id, ClassType};
use icrate::Foundation::{NSCopying, NSObject, NSString};
Expand All @@ -18,8 +18,8 @@ declare_class!(
another_ivar: IvarBool<"_another_ivar">,
box_ivar: IvarDrop<Box<i32>, "_box_ivar">,
maybe_box_ivar: IvarDrop<Option<Box<i32>>, "_maybe_box_ivar">,
id_ivar: IvarDrop<Id<NSString, Shared>, "_id_ivar">,
maybe_id_ivar: IvarDrop<Option<Id<NSString, Shared>>, "_maybe_id_ivar">,
id_ivar: IvarDrop<Id<NSString>, "_id_ivar">,
maybe_id_ivar: IvarDrop<Option<Id<NSString>>, "_maybe_id_ivar">,
}

mod ivars;
Expand Down Expand Up @@ -80,7 +80,7 @@ declare_class!(

#[cfg(target_os = "macos")]
impl CustomAppDelegate {
pub fn new(ivar: u8, another_ivar: bool) -> Id<Self, Shared> {
pub fn new(ivar: u8, another_ivar: bool) -> Id<Self> {
unsafe { msg_send_id![Self::alloc(), initWith: ivar, another: another_ivar] }
}
}
Expand Down
18 changes: 9 additions & 9 deletions crates/icrate/examples/nspasteboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use std::mem::ManuallyDrop;

use icrate::objc2::rc::{Id, Shared};
use icrate::objc2::rc::Id;
use icrate::objc2::runtime::{Class, Object};
use icrate::objc2::{extern_class, msg_send, msg_send_id, ClassType};
use icrate::Foundation::{NSArray, NSDictionary, NSInteger, NSObject, NSString};
Expand Down Expand Up @@ -44,14 +44,14 @@ impl NSPasteboard {
/// TODO: Is this safe to call outside the main thread?
///
/// <https://developer.apple.com/documentation/appkit/nspasteboard/1530091-generalpasteboard?language=objc>
pub fn general() -> Id<Self, Shared> {
pub fn general() -> Id<Self> {
unsafe { msg_send_id![Self::class(), generalPasteboard] }
}

/// Simple, straightforward implementation
///
/// <https://developer.apple.com/documentation/appkit/nspasteboard/1533566-stringfortype?language=objc>
pub fn text_impl_1(&self) -> Id<NSString, Shared> {
pub fn text_impl_1(&self) -> Id<NSString> {
let s = unsafe { NSPasteboardTypeString }.unwrap();
unsafe { msg_send_id![self, stringForType: s] }
}
Expand All @@ -61,15 +61,15 @@ impl NSPasteboard {
/// of nitty-gritty details.
///
/// <https://developer.apple.com/documentation/appkit/nspasteboard/1524454-readobjectsforclasses?language=objc>
pub fn text_impl_2(&self) -> Id<NSString, Shared> {
pub fn text_impl_2(&self) -> 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. Also, we wrap it in `ManuallyDrop` because I'm not sure
// how classes handle `release` calls?
//
// TODO: Investigate and find a better way to express this in objc2.
let string_classes: ManuallyDrop<[Id<Object, Shared>; 1]> = {
let string_classes: ManuallyDrop<[Id<Object>; 1]> = {
let cls: *const Class = NSString::class();
let cls = cls as *mut Object;
unsafe { ManuallyDrop::new([Id::new(cls).unwrap()]) }
Expand All @@ -80,7 +80,7 @@ impl NSPasteboard {
let options = NSDictionary::new();
let objects = unsafe { self.read_objects_for_classes(&class_array, &options) };

// TODO: Should perhaps return Id<Object, Shared>?
// TODO: Should perhaps return Id<Object>?
let ptr: *const Object = objects.first().unwrap();

// And this part is weird as well, since we now have to convert the
Expand All @@ -96,9 +96,9 @@ impl NSPasteboard {
/// SAFETY: `class_array` must contain classes!
unsafe fn read_objects_for_classes(
&self,
class_array: &NSArray<Object, Shared>,
class_array: &NSArray<Object>,
options: &NSDictionary<NSPasteboardReadingOptionKey, Object>,
) -> Id<NSArray<Object, Shared>, Shared> {
) -> Id<NSArray<Object>> {
unsafe { msg_send_id![self, readObjectsForClasses: class_array, options: options] }
}

Expand All @@ -113,7 +113,7 @@ impl NSPasteboard {
///
/// <https://developer.apple.com/documentation/appkit/nspasteboard/1533599-clearcontents?language=objc>
/// <https://developer.apple.com/documentation/appkit/nspasteboard/1525945-writeobjects?language=objc>
pub fn set_text(&self, text: Id<NSString, Shared>) {
pub fn set_text(&self, text: Id<NSString>) {
let _: NSInteger = unsafe { msg_send![self, clearContents] };
let string_array = NSArray::from_slice(&[text]);
let res: bool = unsafe { msg_send![self, writeObjects: &*string_array] };
Expand Down
3 changes: 1 addition & 2 deletions crates/icrate/examples/speech_synthesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use icrate::Foundation::{NSObject, NSString};

#[cfg(target_os = "macos")]
mod appkit {
use icrate::objc2::rc::Shared;
use icrate::Foundation::NSCopying;

use super::*;
Expand Down Expand Up @@ -75,7 +74,7 @@ mod appkit {
pub struct Utterance {
rate: f32,
volume: f32,
string: Id<NSString, Shared>,
string: Id<NSString>,
}

impl Utterance {
Expand Down
4 changes: 2 additions & 2 deletions crates/icrate/src/Foundation/__macro_helpers/cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use core::mem::ManuallyDrop;
use core::ptr;
use core::sync::atomic::{AtomicPtr, Ordering};

use objc2::rc::{Id, Shared};
use objc2::rc::Id;
use objc2::Message;

/// Allows storing an `Id` in a static and lazily loading it.
Expand All @@ -23,7 +23,7 @@ impl<T: Message> CachedId<T> {
/// Returns the cached object. If no object is yet cached, creates one
/// from the given closure and stores it.
#[inline]
pub fn get(&self, f: impl FnOnce() -> Id<T, Shared>) -> &'static T {
pub fn get(&self, f: impl FnOnce() -> Id<T>) -> &'static T {
// TODO: Investigate if we can use weaker orderings.
let ptr = self.ptr.load(Ordering::SeqCst);
// SAFETY: The pointer is either NULL, or has been created below.
Expand Down
6 changes: 3 additions & 3 deletions crates/icrate/src/Foundation/additions/attributed_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ extern_methods!(
unsafe impl NSAttributedString {
/// Construct an empty attributed string.
#[method_id(new)]
pub fn new() -> Id<Self, Shared>;
pub fn new() -> Id<Self>;

/// Creates a new attributed string from the given string and attributes.
///
Expand All @@ -37,14 +37,14 @@ extern_methods!(
pub unsafe fn new_with_attributes(
string: &Foundation::NSString,
attributes: &Foundation::NSDictionary<NSAttributedStringKey, Object>,
) -> Id<Self, Shared> {
) -> Id<Self> {
unsafe { Self::initWithString_attributes(Self::alloc(), string, Some(attributes)) }
}

/// Creates a new attributed string without any attributes.
#[doc(alias = "initWithString:")]
#[cfg(feature = "Foundation_NSString")]
pub fn from_nsstring(string: &Foundation::NSString) -> Id<Self, Shared> {
pub fn from_nsstring(string: &Foundation::NSString) -> Id<Self> {
Self::initWithString(Self::alloc(), string)
}
}
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 @@ -14,7 +14,7 @@ impl RefUnwindSafe for NSBundle {}
impl NSBundle {
#[cfg(feature = "Foundation_NSString")]
#[cfg(feature = "Foundation_NSDictionary")]
pub fn name(&self) -> Option<Id<Foundation::NSString, Shared>> {
pub fn name(&self) -> Option<Id<Foundation::NSString>> {
use Foundation::{NSCopying, NSString};

let info = self.infoDictionary()?;
Expand Down
10 changes: 5 additions & 5 deletions crates/icrate/src/Foundation/additions/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ extern_methods!(
/// Creation methods.
unsafe impl NSData {
#[method_id(new)]
pub fn new() -> Id<Self, Shared>;
pub fn new() -> Id<Self>;

pub fn with_bytes(bytes: &[u8]) -> Id<Self, Shared> {
pub fn with_bytes(bytes: &[u8]) -> Id<Self> {
unsafe { Id::cast(with_slice(Self::class(), bytes)) }
}

#[cfg(feature = "block")]
pub fn from_vec(bytes: Vec<u8>) -> Id<Self, Shared> {
pub fn from_vec(bytes: Vec<u8>) -> Id<Self> {
// GNUStep's NSData `initWithBytesNoCopy:length:deallocator:` has a
// bug; it forgets to assign the input buffer and length to the
// instance before it swizzles to NSDataWithDeallocatorBlock.
Expand Down Expand Up @@ -119,7 +119,7 @@ impl<'a> IntoIterator for &'a NSData {
}
}

pub(crate) unsafe fn with_slice(cls: &Class, bytes: &[u8]) -> Id<Object, Shared> {
pub(crate) unsafe fn with_slice(cls: &Class, bytes: &[u8]) -> Id<Object> {
let bytes_ptr: *const c_void = bytes.as_ptr().cast();
unsafe {
msg_send_id![
Expand All @@ -131,7 +131,7 @@ pub(crate) unsafe fn with_slice(cls: &Class, bytes: &[u8]) -> Id<Object, Shared>
}

#[cfg(feature = "block")]
pub(crate) unsafe fn with_vec(cls: &Class, bytes: Vec<u8>) -> Id<Object, Shared> {
pub(crate) unsafe fn with_vec(cls: &Class, bytes: Vec<u8>) -> Id<Object> {
use core::mem::ManuallyDrop;

use block2::{Block, ConcreteBlock};
Expand Down
4 changes: 2 additions & 2 deletions crates/icrate/src/Foundation/additions/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use core::fmt;
use core::panic::{RefUnwindSafe, UnwindSafe};

use objc2::rc::{Id, Shared};
use objc2::rc::Id;
use objc2::ClassType;

use crate::Foundation::{
Expand All @@ -19,7 +19,7 @@ impl RefUnwindSafe for NSError {}
/// Creation methods.
impl NSError {
/// Construct a new [`NSError`] with the given code in the given domain.
pub fn new(code: NSInteger, domain: &NSErrorDomain) -> Id<Self, Shared> {
pub fn new(code: NSInteger, domain: &NSErrorDomain) -> Id<Self> {
// SAFETY: `domain` and `user_info` are copied to the error object, so
// even if the `&NSString` came from a `&mut NSMutableString`, we're
// still good!
Expand Down
8 changes: 3 additions & 5 deletions crates/icrate/src/Foundation/additions/exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ extern_methods!(
name: &NSExceptionName,
reason: Option<&Foundation::NSString>,
user_info: Option<&Foundation::NSDictionary<Object, Object>>,
) -> Option<Id<Self, Shared>> {
) -> Option<Id<Self>> {
unsafe {
msg_send_id![
Self::alloc(),
Expand Down Expand Up @@ -62,7 +62,7 @@ extern_methods!(
}

/// Convert this into an [`Exception`] object.
pub fn into_exception(this: Id<Self, Shared>) -> Id<Exception, Shared> {
pub fn into_exception(this: Id<Self>) -> Id<Exception> {
// SAFETY: Downcasting to "subclass"
unsafe { Id::cast(this) }
}
Expand All @@ -82,9 +82,7 @@ extern_methods!(
///
/// This should be considered a hint; it may return `Err` in very, very
/// few cases where the object is actually an instance of `NSException`.
pub fn from_exception(
obj: Id<Exception, Shared>,
) -> Result<Id<Self, Shared>, Id<Exception, Shared>> {
pub fn from_exception(obj: Id<Exception>) -> Result<Id<Self>, Id<Exception>> {
if Self::is_nsexception(&obj) {
// SAFETY: Just checked the object is an NSException
Ok(unsafe { Id::cast::<Self>(obj) })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![cfg(feature = "Foundation_NSMutableAttributedString")]
use objc2::rc::{DefaultId, Id, Owned, Shared};
use objc2::rc::{DefaultId, Id, Owned};
use objc2::{extern_methods, msg_send_id, ClassType};

use crate::Foundation::{self, NSAttributedString, NSMutableAttributedString};
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/Foundation/additions/mutable_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use core::ptr::NonNull;
use core::slice::{self, SliceIndex};
use std::io;

use objc2::rc::{DefaultId, Id, Owned, Shared};
use objc2::rc::{DefaultId, Id, Owned};
use objc2::{extern_methods, ClassType};

use super::data::with_slice;
Expand Down
Loading