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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
use crate::file_dialogs::FileDialog;
use {
std::{
rc::Rc,
cell::RefCell,
time::Instant,
collections::HashMap,
os::raw::c_void,
},
crate::{
makepad_live_id::*,
makepad_math::DVec2,
os::{
apple::apple_sys::*,
macos::{
macos_delegates::*,
macos_event::*,
macos_window::MacosWindow,
},
apple_util::{
nsstring_to_string,
str_to_nsstring,
keycode_to_menu_key,
get_event_keycode,
get_event_key_modifier
},
cx_native::EventFlow,
},
//macos_menu::{
// CxCommandSetting
//},
//turtle::{
// Rect
//},
event::{
KeyCode,
KeyEvent,
TextInputEvent,
TextClipboardEvent,
TimerEvent,
KeyModifiers,
},
cursor::MouseCursor,
macos_menu::MacosMenu,
}
};
// this is unsafe, however we don't have much choice since the system calls into
// the objective C entrypoints we need to enter our eventloop
// So wherever we put this boundary, it will be unsafe
// this value will be fetched from multiple threads (post signal uses it)
pub static mut MACOS_CLASSES: *const MacosClasses = 0 as *const _;
// this value should not. Todo: guard this somehow proper
thread_local! {
pub static MACOS_APP: RefCell<Option<MacosApp>> = RefCell::new(None);
}
pub fn with_macos_app<R>(f: impl FnOnce(&mut MacosApp) -> R) -> R {
MACOS_APP.with_borrow_mut(|app| {
f(app.as_mut().unwrap())
})
}
pub fn init_macos_app_global(event_callback: Box<dyn FnMut(MacosEvent) -> EventFlow>) {
unsafe {
MACOS_CLASSES = Box::into_raw(Box::new(MacosClasses::new()));
}
MACOS_APP.with(|app| {
*app.borrow_mut() = Some(MacosApp::new(event_callback));
})
}
pub fn get_macos_class_global() -> &'static MacosClasses {
unsafe {
&*(MACOS_CLASSES)
}
}
#[derive(Clone)]
pub struct CocoaTimer {
timer_id: u64,
nstimer: ObjcId,
repeats: bool
}
pub struct MacosClasses {
pub window: *const Class,
pub window_delegate: *const Class,
pub menu_delegate: *const Class,
pub app_delegate: *const Class,
pub menu_target: *const Class,
pub view: *const Class,
pub timer_delegate: *const Class,
}
impl MacosClasses {
pub fn new() -> Self {
/*let const_attributes = vec![
RcObjcId::from_unowned(NonNull::new(str_to_nsstring("NSMarkedClauseSegment")).unwrap()).forget(),
RcObjcId::from_unowned(NonNull::new(str_to_nsstring("NSGlyphInfo")).unwrap()).forget(),
];*/
Self {
timer_delegate: define_macos_timer_delegate(),
window: define_macos_window_class(),
window_delegate: define_macos_window_delegate(),
//post_delegate: define_cocoa_post_delegate(),
menu_delegate: define_menu_delegate(),
app_delegate: define_app_delegate(),
menu_target: define_menu_target_class(),
view: define_cocoa_view_class(),
}
}
}
pub struct MacosApp {
menu_delegate_instance: ObjcId,
//app_delegate_instance: ObjcId,
pub time_start: Instant,
pub timer_delegate_instance: ObjcId,
timers: Vec<CocoaTimer>,
//pub signals: Mutex<RefCell<HashSet<Signal>>>,
pub cocoa_windows: Vec<(ObjcId, ObjcId)>,
last_key_mod: KeyModifiers,
#[allow(unused)]
pasteboard: ObjcId,
startup_focus_hack_ran: bool,
event_callback: Option<Box<dyn FnMut(MacosEvent) -> EventFlow >>,
event_flow: EventFlow,
pub cursors: HashMap<MouseCursor, ObjcId>,
pub current_cursor: MouseCursor,
//current_ns_event: Option<ObjcId>,
}
impl MacosApp {
pub fn new(event_callback: Box<dyn FnMut(MacosEvent) -> EventFlow>) -> MacosApp {
unsafe {
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let app_delegate_instance: ObjcId = msg_send![get_macos_class_global().app_delegate, new];
let () = msg_send![ns_app, setDelegate: app_delegate_instance];
let () = msg_send![ns_app, setActivationPolicy: NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular as i64];
// Construct the bits that are shared between windows
MacosApp {
startup_focus_hack_ran: false,
pasteboard: msg_send![class!(NSPasteboard), generalPasteboard],
time_start: Instant::now(),
timer_delegate_instance: msg_send![get_macos_class_global().timer_delegate, new],
menu_delegate_instance: msg_send![get_macos_class_global().menu_delegate, new],
//app_delegate_instance,
//signals: Mutex::new(RefCell::new(HashSet::new())),
timers: Vec::new(),
cocoa_windows: Vec::new(),
event_flow: EventFlow::Poll,
last_key_mod: KeyModifiers {..Default::default()},
event_callback: Some(event_callback),
cursors: HashMap::new(),
current_cursor: MouseCursor::Default,
//current_ns_event: None,
}
}
}
pub fn init_quit_menu(&mut self){
self.update_macos_menu(
&MacosMenu::Main{items:vec![MacosMenu::Sub{
name:"Makepad".to_string(),
items:vec![MacosMenu::Item{
command:live_id!(quit),
key:KeyCode::KeyQ,
shift: false,
enabled: true,
name:"Quit Example".to_string()
}]
}]}
);
}
// Determines whether to show your application in the dock when it runs. The default value is true.
pub fn show_in_dock(&mut self, show: bool) {
unsafe{
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
if show {
let () = msg_send![ns_app, setActivationPolicy: NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular as i64];
} else {
let () = msg_send![ns_app, setActivationPolicy: NSApplicationActivationPolicy::NSApplicationActivationPolicyAccessory as i64];
}
}
}
pub fn update_macos_menu(&mut self, menu: &MacosMenu) {
unsafe fn make_menu(
parent_menu: ObjcId,
delegate: ObjcId,
menu_target_class: *const Class,
menu: &MacosMenu,
) {
match menu {
MacosMenu::Main {items} => {
let main_menu: ObjcId = msg_send![class!(NSMenu), new];
let () = msg_send![main_menu, setTitle: str_to_nsstring("MainMenu")];
let () = msg_send![main_menu, setAutoenablesItems: NO];
let () = msg_send![main_menu, setDelegate: delegate];
for item in items {
make_menu(main_menu, delegate, menu_target_class, item);
}
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let () = msg_send![
ns_app,
setMainMenu: main_menu
];
},
MacosMenu::Sub {name, items} => {
let sub_menu: ObjcId = msg_send![class!(NSMenu), new];
let () = msg_send![sub_menu, setTitle: str_to_nsstring(name)];
let () = msg_send![sub_menu, setAutoenablesItems: NO];
let () = msg_send![sub_menu, setDelegate: delegate];
// append item to parebt
let sub_item: ObjcId = msg_send![
parent_menu,
addItemWithTitle: str_to_nsstring(name)
action: nil
keyEquivalent: str_to_nsstring("")
];
// connect submenu
let () = msg_send![parent_menu, setSubmenu: sub_menu forItem: sub_item];
for item in items {
make_menu(sub_menu, delegate, menu_target_class, item);
}
},
MacosMenu::Item {name, command, shift, key, enabled} => {
let sub_item: ObjcId = msg_send![
parent_menu,
addItemWithTitle: str_to_nsstring(name)
action: sel!(menuAction:)
keyEquivalent: str_to_nsstring(keycode_to_menu_key(*key, *shift))
];
let target: ObjcId = msg_send![menu_target_class, new];
let () = msg_send![sub_item, setTarget: target];
let () = msg_send![sub_item, setEnabled: if *enabled {YES}else {NO}];
/*
let command_usize = if let Ok(mut status_map) = status_map.lock() {
if let Some(id) = status_map.command_to_usize.get(&command) {
*id
}
else {
let id = status_map.status_to_usize.len();
status_map.command_to_usize.insert(*command, id);
status_map.usize_to_command.insert(id, *command);
id
}
}
else {
panic!("cannot lock cmd_map");
};*/
//(*target).set_ivar("macos_app_ptr", GLOBAL_COCOA_APP as *mut _ as *mut c_void);
(*target).set_ivar("command_u64", command.0);
},
MacosMenu::Line => {
let sep_item: ObjcId = msg_send![class!(NSMenuItem), separatorItem];
let () = msg_send![
parent_menu,
addItem: sep_item
];
}
}
}
unsafe {
make_menu(nil, self.menu_delegate_instance, get_macos_class_global().menu_target, menu);
}
}
/*
pub fn startup_focus_hack(&mut self) {
unsafe {
self.startup_focus_hack_ran = true;
if !self.startup_focus_hack_ran {
self.startup_focus_hack_ran = true;
//let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
//let active: bool = msg_send![ns_app, isActive];
//if !active {
let dock_bundle_id = str_to_nsstring("com.apple.dock");
let dock_array: ObjcId = msg_send![
class!(NSRunningApplication),
runningApplicationsWithBundleIdentifier: dock_bundle_id
];
let my_app: ObjcId = msg_send![
class!(NSRunningApplication),
runningApplicationWithProcessIdentifier: std::process::id()
];
let dock_array_len: u64 = msg_send![dock_array, count];
if dock_array_len == 0 {
panic!("Dock not running");
} else {
let dock: ObjcId = msg_send![dock_array, objectAtIndex: 0];
let _status: BOOL = msg_send![
dock,
activateWithOptions: NSApplicationActivationOptions::NSApplicationActivateIgnoringOtherApps
];
//let ns_running_app: ObjcId = msg_send![class!(NSRunningApplication), currentApplication];
let () = msg_send![
my_app,
activateWithOptions: NSApplicationActivationOptions::NSApplicationActivateIgnoringOtherApps
];
let () = msg_send![self.cocoa_windows[0].0, makeKeyAndOrderFront: nil];
}
//}
}
}
}*/
pub fn startup_focus_hack(&mut self) {
return
unsafe {
if !self.startup_focus_hack_ran {
self.startup_focus_hack_ran = true;
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let active: bool = msg_send![ns_app, isActive];
if !active {
let dock_bundle_id: ObjcId = str_to_nsstring("com.apple.dock");
let dock_array: ObjcId = msg_send![
class!(NSRunningApplication),
runningApplicationsWithBundleIdentifier: dock_bundle_id
];
let dock_array_len: u64 = msg_send![dock_array, count];
if dock_array_len == 0 {
panic!("Dock not running");
} else {
let dock: ObjcId = msg_send![dock_array, objectAtIndex: 0];
let _status: BOOL = msg_send![
dock,
activateWithOptions: NSApplicationActivationOptions::NSApplicationActivateIgnoringOtherApps
];
let ns_running_app: ObjcId = msg_send![class!(NSRunningApplication), currentApplication];
let () = msg_send![
ns_running_app,
activateWithOptions: NSApplicationActivationOptions::NSApplicationActivateIgnoringOtherApps
];
}
}
}
}
}
pub fn time_now(&self) -> f64 {
let time_now = Instant::now(); //unsafe {mach_absolute_time()};
(time_now.duration_since(self.time_start)).as_secs_f64()
}
unsafe fn process_ns_event(ns_event: ObjcId) {
let ev_type: NSEventType = msg_send![ns_event, type];
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let () = msg_send![ns_app, sendEvent: ns_event];
if ev_type as u64 == 21 { // some missing event from cocoa-rs crate
return;
}
match ev_type {
NSEventType::NSApplicationDefined => { // event loop unblocker
},
NSEventType::NSKeyUp => {
if let Some(key_code) = get_event_keycode(ns_event) {
let modifiers = get_event_key_modifier(ns_event);
//let key_char = get_event_char(ns_event);
let is_repeat: bool = msg_send![ns_event, isARepeat];
let time = with_macos_app(|app| app.time_now());
MacosApp::do_callback(
MacosEvent::KeyUp(KeyEvent {
key_code: key_code,
//key_char: key_char,
is_repeat: is_repeat,
modifiers: modifiers,
time
})
);
}
},
NSEventType::NSKeyDown => {
if let Some(key_code) = get_event_keycode(ns_event) {
let modifiers = get_event_key_modifier(ns_event);
//let key_char = get_event_char(ns_event);
let is_repeat: bool = msg_send![ns_event, isARepeat];
//let is_return = if let KeyCode::Return = key_code{true} else{false};
#[cfg(target_os = "macos")]
match key_code {
KeyCode::KeyV => if modifiers.logo || modifiers.control {
// was a paste
let pasteboard: ObjcId = with_macos_app(|app| app.pasteboard);
let nsstring: ObjcId = msg_send![pasteboard, stringForType: NSStringPboardType];
if nsstring != std::ptr::null_mut() {
let string = nsstring_to_string(nsstring);
MacosApp::do_callback(
MacosEvent::TextInput(TextInputEvent {
input: string,
was_paste: true,
replace_last: false
})
);
}
},
KeyCode::KeyC => if modifiers.logo || modifiers.control {
let pasteboard: ObjcId = with_macos_app(|app| app.pasteboard);
let response = Rc::new(RefCell::new(None));
MacosApp::do_callback(
MacosEvent::TextCopy(TextClipboardEvent {
response: response.clone()
})
);
let response = response.borrow();
if let Some(response) = response.as_ref() {
let nsstring = str_to_nsstring(&response);
let array: ObjcId = msg_send![class!(NSArray), arrayWithObject: NSStringPboardType];
let () = msg_send![pasteboard, declareTypes: array owner: nil];
let () = msg_send![pasteboard, setString: nsstring forType: NSStringPboardType];
}
},
KeyCode::KeyX => if modifiers.logo || modifiers.control {
let pasteboard: ObjcId = with_macos_app(|app| app.pasteboard);
let response = Rc::new(RefCell::new(None));
MacosApp::do_callback(
MacosEvent::TextCut(TextClipboardEvent {
response: response.clone()
})
);
let response = response.borrow();
if let Some(response) = response.as_ref() {
let nsstring = str_to_nsstring(&response);
let array: ObjcId = msg_send![class!(NSArray), arrayWithObject: NSStringPboardType];
let () = msg_send![pasteboard, declareTypes: array owner: nil];
let () = msg_send![pasteboard, setString: nsstring forType: NSStringPboardType];
}
},
_ => {}
}
let time = with_macos_app(|app: &mut MacosApp| app.time_now());
// lets check if we have marked text
if KeyCode::Backspace == key_code {
// we have to check if we dont have any marked text in our windows
with_macos_app(|app| {
for (_,view) in &app.cocoa_windows {
let marked = unsafe{msg_send![*view, hasMarkedText]};
if marked{
return
}
}
});
}
MacosApp::do_callback(
MacosEvent::KeyDown(KeyEvent {
key_code: key_code,
is_repeat: is_repeat,
modifiers: modifiers,
time
})
);
/*
if is_return{
self.do_callback(&mut vec![
Event::TextInput(TextInputEvent{
input:"\n".to_string(),
was_paste:false,
replace_last:false
})
]);
}*/
}
},
NSEventType::NSFlagsChanged => {
let modifiers = get_event_key_modifier(ns_event);
let last_key_mod = with_macos_app(|app| app.last_key_mod.clone());
with_macos_app(|app| app.last_key_mod = modifiers.clone());
let mut events = Vec::new();
fn add_event(time: f64, old: bool, new: bool, modifiers: KeyModifiers, events: &mut Vec<MacosEvent>, key_code: KeyCode) {
if old != new {
let event = KeyEvent {
key_code: key_code,
//key_char: '\0',
is_repeat: false,
modifiers: modifiers,
time: time
};
if new {
events.push(MacosEvent::KeyDown(event));
}
else {
events.push(MacosEvent::KeyUp(event));
}
}
}
let time = with_macos_app(|app| app.time_now());
add_event(time, last_key_mod.shift, modifiers.shift, modifiers.clone(), &mut events, KeyCode::Shift);
add_event(time, last_key_mod.alt, modifiers.alt, modifiers.clone(), &mut events, KeyCode::Alt);
add_event(time, last_key_mod.logo, modifiers.logo, modifiers.clone(), &mut events, KeyCode::Logo);
add_event(time, last_key_mod.control, modifiers.control, modifiers.clone(), &mut events, KeyCode::Control);
if events.len() >0 {
for event in events {
MacosApp::do_callback(event);
}
}
},
NSEventType::NSMouseEntered => {},
NSEventType::NSMouseExited => {},
NSEventType::NSScrollWheel => {
let window: ObjcId = msg_send![ns_event, window];
if window == nil {
return
}
let window_delegate: ObjcId = msg_send![window, delegate];
if window_delegate == nil {
return
}
let ptr: *mut c_void = *(*window_delegate).get_ivar("macos_window_ptr");
let cocoa_window = &mut *(ptr as *mut MacosWindow);
let dx: f64 = msg_send![ns_event, scrollingDeltaX];
let dy: f64 = msg_send![ns_event, scrollingDeltaY];
let has_prec: BOOL = msg_send![ns_event, hasPreciseScrollingDeltas];
return if has_prec == YES {
cocoa_window.send_scroll(DVec2 {x: -dx, y: -dy}, get_event_key_modifier(ns_event), false);
} else {
cocoa_window.send_scroll(DVec2 {x: -dx * 32., y: -dy * 32.}, get_event_key_modifier(ns_event), true);
}
},
NSEventType::NSEventTypePressure => {
},
_ => (),
}
}
pub fn event_loop() {
unsafe {
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
//let () = msg_send![ns_app, activateIgnoringOtherApps:YES];
let () = msg_send![ns_app, finishLaunching];
// get_macos_app_global().init_quit_menu();
// get_macos_app_global().startup_focus_hack();
loop {
let event_flow = with_macos_app(|app| app.event_flow);
match event_flow {
EventFlow::Exit => {
break;
}
EventFlow::Poll | EventFlow::Wait => {
let event_wait = if let EventFlow::Wait = with_macos_app(|app| app.event_flow) {true}else {false};
let pool: ObjcId = msg_send![class!(NSAutoreleasePool), new];
let ns_until: ObjcId = if event_wait {
msg_send![class!(NSDate), distantFuture]
}else {
msg_send![class!(NSDate), distantPast]
};
let ns_event: ObjcId = msg_send![
ns_app,
nextEventMatchingMask: NSEventMask::NSAnyEventMask as u64 | NSEventMask::NSEventMaskPressure as u64
untilDate: ns_until
inMode: NSDefaultRunLoopMode
dequeue: YES
];
//self.current_ns_event = Some(ns_event);
if ns_event != nil {
MacosApp::process_ns_event(ns_event);
}
//let event_wait = if let EventFlow::Wait = with_macos_app(|app| app.event_flow) {true}else {false};
//if ns_event == nil || event_wait {
//if event_wait{
// with_macos_app(|app| app.event_flow = EventFlow::Wait);
//}
//self.current_ns_event = None;
let () = msg_send![pool, release];
}
}
}
}
}
pub fn do_callback(event: MacosEvent) {
let cb = with_macos_app(|app| app.event_callback.take());
if let Some(mut callback) = cb {
let event_flow = callback(event);
with_macos_app(|app| app.event_flow = event_flow);
if let EventFlow::Exit = event_flow {
unsafe {
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let () = msg_send![ns_app, terminate: nil];
}
}
with_macos_app(|app| app.event_callback = Some(callback));
}
}
/*
pub fn post_signal(signal: Signal) {
unsafe {
let cocoa_app = get_macos_app_global();
if let Ok(signals) = cocoa_app.signals.lock(){
let mut signals = signals.borrow_mut();
// if empty, we do shit. otherwise we add
if signals.is_empty(){
signals.insert(signal);
let pool: ObjcId = msg_send![class!(NSAutoreleasePool), new];
//let cocoa_app = get_macos_app_global();
let post_delegate_instance: ObjcId = msg_send![get_macos_class_global().post_delegate, new];
//(*post_delegate_instance).set_ivar("macos_app_ptr", GLOBAL_COCOA_APP as *mut _ as *mut c_void);
let nstimer: ObjcId = msg_send![
class!(NSTimer),
timerWithTimeInterval: 0.
target: post_delegate_instance
selector: sel!(receivedPost:)
userInfo: nil
repeats: false
];
let nsrunloop: ObjcId = msg_send![class!(NSRunLoop), mainRunLoop];
let () = msg_send![nsrunloop, addTimer: nstimer forMode: NSRunLoopCommonModes];
let () = msg_send![pool, release];
}
else{
signals.insert(signal);
}
}
}
}*/
pub fn set_mouse_cursor(&mut self, cursor: MouseCursor) {
if self.current_cursor != cursor {
self.current_cursor = cursor;
// todo set it on all windows
unsafe {
for (window, view) in &self.cocoa_windows {
let _: () = msg_send![
*window,
invalidateCursorRectsForView: *view
];
}
}
}
}
pub fn start_timer(&mut self, timer_id: u64, interval: f64, repeats: bool) {
unsafe {
let pool: ObjcId = msg_send![class!(NSAutoreleasePool), new];
let nstimer: ObjcId = msg_send![
class!(NSTimer),
timerWithTimeInterval: interval
target: self.timer_delegate_instance
selector: sel!(receivedTimer:)
userInfo: nil
repeats: repeats
];
let nsrunloop: ObjcId = msg_send![class!(NSRunLoop), mainRunLoop];
let () = msg_send![nsrunloop, addTimer: nstimer forMode: NSRunLoopCommonModes];
self.timers.push(CocoaTimer {
timer_id: timer_id,
nstimer: nstimer,
repeats: repeats
});
let () = msg_send![pool, release];
}
}
pub fn stop_timer(&mut self, timer_id: u64) {
for i in 0..self.timers.len() {
if self.timers[i].timer_id == timer_id {
unsafe {
let () = msg_send![self.timers[i].nstimer, invalidate];
}
self.timers.remove(i);
return;
}
}
}
pub fn send_timer_received(nstimer: ObjcId) {
let len = with_macos_app(|app| app.timers.len());
for i in 0..len {
let time =with_macos_app(|app| app.time_now());
if with_macos_app(|app| app.timers[i].nstimer == nstimer) {
let timer_id = with_macos_app(|app| app.timers[i].timer_id);
if !with_macos_app(|app| app.timers[i].repeats) {
with_macos_app(|app| app.timers.remove(i));
}
MacosApp::do_callback(MacosEvent::Timer(TimerEvent {time:Some(time), timer_id: timer_id}));
// break the eventloop if its in blocked mode
unsafe {
let pool: ObjcId = msg_send![class!(NSAutoreleasePool), new];
let nsevent: ObjcId = msg_send![
class!(NSEvent),
otherEventWithType: NSEventType::NSApplicationDefined
location: NSPoint {x: 0., y: 0.}
modifierFlags: 0u64
timestamp: 0f64
windowNumber: 1u64
context: nil
subtype: 0i16
data1: 0u64
data2: 0u64
];
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let () = msg_send![ns_app, postEvent: nsevent atStart: 0];
let () = msg_send![pool, release];
}
return;
}
}
}
/*
pub fn send_signal_event(&mut self) {
let signals = if let Ok(signals) = self.signals.lock(){
let mut new_signals = HashSet::new();
std::mem::swap(&mut *signals.borrow_mut(), &mut new_signals);
new_signals
}else{panic!()};
self.do_callback(vec![
MacosEvent::Signal(SignalEvent {
signals,
})
]);
self.do_callback(vec![MacosEvent::Paint]);
}*/
pub fn send_command_event(command: LiveId) {
MacosApp::do_callback(
MacosEvent::MacosMenuCommand(command)
);
MacosApp::do_callback(MacosEvent::Paint);
}
pub fn send_paint_event() {
MacosApp::do_callback(MacosEvent::Paint);
}
/*
#[cfg(target_os = "macos")]
pub fn start_dragging(&mut self, items: Vec<DragItem>) {
unsafe {
let ns_app: ObjcId = msg_send![class!(NSApplication), sharedApplication];
let ns_event: ObjcId = msg_send![ns_app, currentEvent];
let window: ObjcId = msg_send![ns_event, window];
let window_delegate: ObjcId = msg_send![window, delegate];
if window == nil {
crate::error!("start_dragging: Cocoa window nil on event");
return
}
let cocoa_window: *mut c_void = *(*window_delegate).get_ivar("macos_window_ptr");
let cocoa_window = &mut *(cocoa_window as *mut MacosWindow);
cocoa_window.start_dragging(ns_event, items);
};
}*/
pub fn copy_to_clipboard(&mut self, content: &str) {
unsafe {
let pasteboard: ObjcId = self.pasteboard;
let nsstring = str_to_nsstring(content);
let array: ObjcId = msg_send![class!(NSArray), arrayWithObject: NSStringPboardType];
let () = msg_send![pasteboard, declareTypes: array owner: nil];
let () = msg_send![pasteboard, setString: nsstring forType: NSStringPboardType];
}
}
pub fn open_save_file_dialog(&mut self, _settings: FileDialog)
{
println!("open save file dialog!");
}
pub fn open_select_file_dialog(&mut self, _settings: FileDialog )
{
println!("open select file dialog!");
}
pub fn open_save_folder_dialog(&mut self, _settings: FileDialog)
{
println!("open save folder dialog!");
}
pub fn open_select_folder_dialog(&mut self, _settings: FileDialog)
{
println!("open select folder dialog!");
}
}