-
Notifications
You must be signed in to change notification settings - Fork 36
/
declaration.rs
83 lines (73 loc) · 2.16 KB
/
declaration.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use objc2::{
msg_send, msg_send_id,
rc::{Id, Shared},
runtime::{Bool, Object},
};
use objc2_foundation::{declare_class, extern_class, NSObject};
#[cfg(all(feature = "apple", target_os = "macos"))]
#[link(name = "AppKit", kind = "framework")]
extern "C" {}
extern_class! {
unsafe struct NSResponder: NSObject;
}
declare_class! {
unsafe struct CustomAppDelegate: NSResponder, NSObject {
pub ivar: u8,
another_ivar: Bool,
}
unsafe impl {
@sel(initWith:another:)
fn init_with(
self: &mut Self,
ivar: u8,
another_ivar: Bool,
) -> *mut Self {
let this: *mut Self = unsafe {
msg_send![super(self, NSResponder::class()), init]
};
if let Some(this) = unsafe { this.as_mut() } {
// TODO: Allow initialization through MaybeUninit
*this.ivar = ivar;
*this.another_ivar = another_ivar;
}
this
}
@sel(myClassMethod)
fn my_class_method() {
println!("A class method!");
}
}
// For some reason, `NSApplicationDelegate` is not a "real" protocol we
// can retrieve using `objc_getProtocol` - it seems it is created by
// `clang` only when used in Objective-C...
//
// TODO: Investigate this!
unsafe impl {
@sel(applicationDidFinishLaunching:)
fn did_finish_launching(&self, _sender: *mut Object) {
println!("Did finish launching!");
}
@sel(applicationWillTerminate:)
fn will_terminate(&self, _: *mut Object) {
println!("Will terminate!");
}
}
}
impl CustomAppDelegate {
pub fn new(ivar: u8, another_ivar: bool) -> Id<Self, Shared> {
let cls = Self::class();
unsafe {
msg_send_id![
msg_send_id![cls, alloc],
initWith: ivar,
another: Bool::from(another_ivar),
]
.unwrap()
}
}
}
fn main() {
let delegate = CustomAppDelegate::new(42, true);
println!("{}", delegate.ivar);
println!("{}", delegate.another_ivar.as_bool());
}