-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathwindow.rs
More file actions
872 lines (776 loc) · 30.3 KB
/
window.rs
File metadata and controls
872 lines (776 loc) · 30.3 KB
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
// Copyright 2019 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! macOS implementation of window creation.
#![allow(non_snake_case)]
use std::any::Any;
use std::ffi::c_void;
use std::mem;
use std::sync::{Arc, Mutex, Weak};
use std::time::Instant;
use cocoa::appkit::{
CGFloat, NSApp, NSApplication, NSAutoresizingMaskOptions, NSBackingStoreBuffered, NSEvent,
NSEventModifierFlags, NSView, NSViewHeightSizable, NSViewWidthSizable, NSWindow,
NSWindowStyleMask,
};
use cocoa::base::{id, nil, BOOL, NO, YES};
use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSRect, NSSize, NSString};
use lazy_static::lazy_static;
use objc::declare::ClassDecl;
use objc::rc::WeakPtr;
use objc::runtime::{Class, Object, Sel};
use objc::{class, msg_send, sel, sel_impl};
use cairo::{Context, QuartzSurface};
use log::{error, info};
use crate::kurbo::{Point, Rect, Size, Vec2};
use crate::piet::{Piet, RenderContext};
use super::dialog;
use super::menu::Menu;
use super::util::{assert_main_thread, make_nsstring};
use crate::common_util::IdleCallback;
use crate::dialog::{FileDialogOptions, FileDialogType, FileInfo};
use crate::keyboard::{KeyEvent, KeyModifiers};
use crate::keycodes::KeyCode;
use crate::mouse::{Cursor, MouseButton, MouseEvent};
use crate::window::{IdleToken, Text, TimerToken, WinHandler};
use crate::Error;
#[allow(non_upper_case_globals)]
const NSWindowDidBecomeKeyNotification: &str = "NSWindowDidBecomeKeyNotification";
#[derive(Clone)]
pub(crate) struct WindowHandle {
/// This is an NSView, as our concept of "window" is more the top-level container holding
/// a view. Also, this is better for hosted applications such as VST.
nsview: WeakPtr,
idle_queue: Weak<Mutex<Vec<IdleKind>>>,
}
impl Default for WindowHandle {
fn default() -> Self {
WindowHandle {
nsview: unsafe { WeakPtr::new(nil) },
idle_queue: Default::default(),
}
}
}
/// Builder abstraction for creating new windows.
pub(crate) struct WindowBuilder {
handler: Option<Box<dyn WinHandler>>,
title: String,
menu: Option<Menu>,
size: Size,
min_size: Option<Size>,
resizable: bool,
show_titlebar: bool,
}
#[derive(Clone)]
pub(crate) struct IdleHandle {
nsview: WeakPtr,
idle_queue: Weak<Mutex<Vec<IdleKind>>>,
}
/// This represents different Idle Callback Mechanism
enum IdleKind {
Callback(Box<dyn IdleCallback>),
Token(IdleToken),
}
/// This is the state associated with our custom NSView.
struct ViewState {
nsview: WeakPtr,
handler: Box<dyn WinHandler>,
idle_queue: Arc<Mutex<Vec<IdleKind>>>,
last_mods: KeyModifiers,
}
impl WindowBuilder {
pub fn new() -> WindowBuilder {
WindowBuilder {
handler: None,
title: String::new(),
menu: None,
size: Size::new(500.0, 400.0),
min_size: None,
resizable: true,
show_titlebar: true,
}
}
pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) {
self.handler = Some(handler);
}
pub fn set_size(&mut self, size: Size) {
self.size = size;
}
pub fn set_min_size(&mut self, size: Size) {
self.min_size = Some(size);
}
pub fn resizable(&mut self, resizable: bool) {
self.resizable = resizable;
}
pub fn show_titlebar(&mut self, show_titlebar: bool) {
// TODO: Use this in `self.build`
self.show_titlebar = show_titlebar;
}
pub fn set_title(&mut self, title: impl Into<String>) {
self.title = title.into();
}
pub fn set_menu(&mut self, menu: Menu) {
self.menu = Some(menu);
}
pub fn build(self) -> Result<WindowHandle, Error> {
assert_main_thread();
unsafe {
let mut style_mask = NSWindowStyleMask::NSTitledWindowMask
| NSWindowStyleMask::NSClosableWindowMask
| NSWindowStyleMask::NSMiniaturizableWindowMask;
if self.resizable {
style_mask |= NSWindowStyleMask::NSResizableWindowMask;
}
let rect = NSRect::new(
NSPoint::new(0., 0.),
NSSize::new(self.size.width, self.size.height),
);
let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_(
rect,
style_mask,
NSBackingStoreBuffered,
NO,
);
if let Some(min_size) = self.min_size {
let size = NSSize::new(min_size.width, min_size.height);
window.setContentMinSize_(size);
}
window.cascadeTopLeftFromPoint_(NSPoint::new(20.0, 20.0));
window.setTitle_(make_nsstring(&self.title));
// TODO: this should probably be a tracking area instead
window.setAcceptsMouseMovedEvents_(YES);
let (view, idle_queue) = make_view(self.handler.expect("view"));
let content_view = window.contentView();
let frame = NSView::frame(content_view);
view.initWithFrame_(frame);
let () = msg_send![window, setDelegate: view];
if let Some(menu) = self.menu {
NSApp().setMainMenu_(menu.menu);
}
content_view.addSubview_(view);
let view_state: *mut c_void = *(*view).get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let handle = WindowHandle {
nsview: view_state.nsview.clone(),
idle_queue,
};
(*view_state).handler.connect(&handle.clone().into());
(*view_state)
.handler
.size(frame.size.width as u32, frame.size.height as u32);
Ok(handle)
}
}
}
// Wrap pointer because lazy_static requires Sync.
struct ViewClass(*const Class);
unsafe impl Sync for ViewClass {}
lazy_static! {
static ref VIEW_CLASS: ViewClass = unsafe {
let mut decl = ClassDecl::new("DruidView", class!(NSView)).expect("View class defined");
decl.add_ivar::<*mut c_void>("viewState");
decl.add_method(
sel!(isFlipped),
isFlipped as extern "C" fn(&Object, Sel) -> BOOL,
);
extern "C" fn isFlipped(_this: &Object, _sel: Sel) -> BOOL {
YES
}
decl.add_method(
sel!(acceptsFirstResponder),
acceptsFirstResponder as extern "C" fn(&Object, Sel) -> BOOL,
);
extern "C" fn acceptsFirstResponder(_this: &Object, _sel: Sel) -> BOOL {
YES
}
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel));
extern "C" fn dealloc(this: &Object, _sel: Sel) {
info!("view is dealloc'ed");
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
Box::from_raw(view_state as *mut ViewState);
}
}
decl.add_method(
sel!(windowDidBecomeKey:),
window_did_become_key as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(setFrameSize:),
set_frame_size as extern "C" fn(&mut Object, Sel, NSSize),
);
decl.add_method(
sel!(mouseDown:),
mouse_down_left as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(rightMouseDown:),
mouse_down_right as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(mouseUp:),
mouse_up_left as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(rightMouseUp:),
mouse_up_right as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(mouseMoved:),
mouse_move as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(mouseDragged:),
mouse_move as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(scrollWheel:),
scroll_wheel as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(magnifyWithEvent:),
pinch_event as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(keyDown:),
key_down as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(sel!(keyUp:), key_up as extern "C" fn(&mut Object, Sel, id));
decl.add_method(
sel!(flagsChanged:),
mods_changed as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(drawRect:),
draw_rect as extern "C" fn(&mut Object, Sel, NSRect),
);
decl.add_method(sel!(runIdle), run_idle as extern "C" fn(&mut Object, Sel));
decl.add_method(sel!(redraw), redraw as extern "C" fn(&mut Object, Sel));
decl.add_method(
sel!(handleTimer:),
handle_timer as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(handleMenuItem:),
handle_menu_item as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(showContextMenu:),
show_context_menu as extern "C" fn(&mut Object, Sel, id),
);
decl.add_method(
sel!(windowWillClose:),
window_will_close as extern "C" fn(&mut Object, Sel, id),
);
ViewClass(decl.register())
};
}
fn make_view(handler: Box<dyn WinHandler>) -> (id, Weak<Mutex<Vec<IdleKind>>>) {
let idle_queue = Arc::new(Mutex::new(Vec::new()));
let queue_handle = Arc::downgrade(&idle_queue);
unsafe {
let view: id = msg_send![VIEW_CLASS.0, new];
let nsview = WeakPtr::new(view);
let state = ViewState {
nsview,
handler,
idle_queue,
last_mods: KeyModifiers::default(),
};
let state_ptr = Box::into_raw(Box::new(state));
(*view).set_ivar("viewState", state_ptr as *mut c_void);
let options: NSAutoresizingMaskOptions = NSViewWidthSizable | NSViewHeightSizable;
view.setAutoresizingMask_(options);
(view.autorelease(), queue_handle)
}
}
extern "C" fn set_frame_size(this: &mut Object, _: Sel, size: NSSize) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
(*view_state)
.handler
.size(size.width as u32, size.height as u32);
let superclass = msg_send![this, superclass];
let () = msg_send![super(this, superclass), setFrameSize: size];
}
}
// NOTE: If we know the button (because of the origin call) we pass it through,
// otherwise we get it from the event itself.
fn mouse_event(nsevent: id, view: id, button: Option<MouseButton>) -> MouseEvent {
unsafe {
let button = button.unwrap_or_else(|| {
let button = NSEvent::pressedMouseButtons(nsevent);
get_mouse_button(button as usize)
});
let point = nsevent.locationInWindow();
let view_point = view.convertPoint_fromView_(point, nil);
let pos = Point::new(view_point.x as f64, view_point.y as f64);
let modifiers = nsevent.modifierFlags();
let modifiers = make_modifiers(modifiers);
let count = nsevent.clickCount() as u32;
MouseEvent {
pos,
mods: modifiers,
count,
button,
}
}
}
fn get_mouse_button(mask: usize) -> MouseButton {
//TODO: this doesn't correctly handle multiple buttons being pressed.
match mask {
mask if mask & 1 > 0 => MouseButton::Left,
mask if mask & 1 << 1 > 0 => MouseButton::Right,
mask if mask & 1 << 2 > 0 => MouseButton::Middle,
mask if mask & 1 << 3 > 0 => MouseButton::X1,
mask if mask & 1 << 4 > 0 => MouseButton::X2,
_ => {
//FIXME: this gets called when the mouse moves, where there
//may be no buttons down. This is mostly a problem with our API?
MouseButton::Left
}
}
}
extern "C" fn mouse_down_left(this: &mut Object, _: Sel, nsevent: id) {
mouse_down(this, nsevent, MouseButton::Left)
}
extern "C" fn mouse_down_right(this: &mut Object, _: Sel, nsevent: id) {
mouse_down(this, nsevent, MouseButton::Right)
}
fn mouse_down(this: &mut Object, nsevent: id, button: MouseButton) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let event = mouse_event(nsevent, this as id, Some(button));
(*view_state).handler.mouse_down(&event);
}
}
extern "C" fn mouse_up_left(this: &mut Object, _: Sel, nsevent: id) {
mouse_up(this, nsevent, MouseButton::Left)
}
extern "C" fn mouse_up_right(this: &mut Object, _: Sel, nsevent: id) {
mouse_up(this, nsevent, MouseButton::Right)
}
fn mouse_up(this: &mut Object, nsevent: id, button: MouseButton) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let event = mouse_event(nsevent, this as id, Some(button));
(*view_state).handler.mouse_up(&event);
}
}
extern "C" fn mouse_move(this: &mut Object, _: Sel, nsevent: id) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let event = mouse_event(nsevent, this as id, None);
(*view_state).handler.mouse_move(&event);
}
}
extern "C" fn scroll_wheel(this: &mut Object, _: Sel, nsevent: id) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let (dx, dy) = {
let dx = -nsevent.scrollingDeltaX() as f64;
let dy = -nsevent.scrollingDeltaY() as f64;
if nsevent.hasPreciseScrollingDeltas() == cocoa::base::YES {
(dx, dy)
} else {
(dx * 32.0, dy * 32.0)
}
};
let mods = nsevent.modifierFlags();
let mods = make_modifiers(mods);
let delta = Vec2::new(dx, dy);
(*view_state).handler.wheel(delta, mods);
}
}
extern "C" fn pinch_event(this: &mut Object, _: Sel, nsevent: id) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let delta: CGFloat = msg_send![nsevent, magnification];
(*view_state).handler.zoom(delta as f64);
}
}
extern "C" fn key_down(this: &mut Object, _: Sel, nsevent: id) {
let event = make_key_event(nsevent);
let view_state = unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
&mut *(view_state as *mut ViewState)
};
(*view_state).handler.key_down(event);
view_state.last_mods = event.mods;
}
extern "C" fn key_up(this: &mut Object, _: Sel, nsevent: id) {
let event = make_key_event(nsevent);
let view_state = unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
&mut *(view_state as *mut ViewState)
};
(*view_state).handler.key_up(event);
view_state.last_mods = event.mods;
}
extern "C" fn mods_changed(this: &mut Object, _: Sel, nsevent: id) {
let view_state = unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
&mut *(view_state as *mut ViewState)
};
let (down, event) = mods_changed_key_event(view_state.last_mods, nsevent);
view_state.last_mods = event.mods;
if down {
(*view_state).handler.key_down(event);
} else {
(*view_state).handler.key_up(event);
}
}
extern "C" fn draw_rect(this: &mut Object, _: Sel, dirtyRect: NSRect) {
unsafe {
let context: id = msg_send![class![NSGraphicsContext], currentContext];
// TODO: probably should use a better type than void pointer, but it's not obvious what's best.
// cairo_sys::CGContextRef would be better documentation-wise, but it's a type alias.
let cgcontext: *mut c_void = msg_send![context, CGContext];
// TODO: use width and height from view size
let frame = NSView::frame(this as *mut _);
let width = frame.size.width as u32;
let height = frame.size.height as u32;
let rect = Rect::from_origin_size(
(dirtyRect.origin.x, dirtyRect.origin.y),
(dirtyRect.size.width, dirtyRect.size.height),
);
let cairo_surface =
QuartzSurface::create_for_cg_context(cgcontext, width, height).expect("cairo surface");
let mut cairo_ctx = Context::new(&cairo_surface);
cairo_ctx.set_source_rgb(0.0, 0.5, 0.0);
cairo_ctx.paint();
let mut piet_ctx = Piet::new(&mut cairo_ctx);
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
let anim = (*view_state).handler.paint(&mut piet_ctx, rect);
if let Err(e) = piet_ctx.finish() {
error!("{}", e)
}
if anim {
// TODO: synchronize with screen refresh rate using CVDisplayLink instead.
let () = msg_send!(this as *const _, performSelectorOnMainThread: sel!(redraw)
withObject: nil waitUntilDone: NO);
}
let superclass = msg_send![this, superclass];
let () = msg_send![super(this, superclass), drawRect: dirtyRect];
}
}
extern "C" fn run_idle(this: &mut Object, _: Sel) {
let view_state = unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
&mut *(view_state as *mut ViewState)
};
let queue: Vec<_> = mem::replace(
&mut view_state.idle_queue.lock().expect("queue"),
Vec::new(),
);
for item in queue {
match item {
IdleKind::Callback(it) => it.call(view_state.handler.as_any()),
IdleKind::Token(it) => {
view_state.handler.as_mut().idle(it);
}
}
}
}
extern "C" fn redraw(this: &mut Object, _: Sel) {
unsafe {
let () = msg_send![this as *const _, setNeedsDisplay: YES];
}
}
extern "C" fn handle_timer(this: &mut Object, _: Sel, timer: id) {
let view_state = unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
&mut *(view_state as *mut ViewState)
};
let token = unsafe {
let user_info: id = msg_send![timer, userInfo];
msg_send![user_info, unsignedIntValue]
};
(*view_state).handler.timer(TimerToken::from_raw(token));
}
extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
unsafe {
let tag: isize = msg_send![item, tag];
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
(*view_state).handler.command(tag as u32);
}
}
extern "C" fn show_context_menu(this: &mut Object, _: Sel, item: id) {
unsafe {
let window: id = msg_send![this as *const _, window];
let mut location: NSPoint = msg_send![window, mouseLocationOutsideOfEventStream];
let bounds: NSRect = msg_send![this as *const _, bounds];
location.y = bounds.size.height - location.y;
let _: BOOL = msg_send![item, popUpMenuPositioningItem: nil atLocation: location inView: this as *const _];
}
}
extern "C" fn window_did_become_key(this: &mut Object, _: Sel, _notification: id) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
(*view_state).handler.got_focus();
}
}
extern "C" fn window_will_close(this: &mut Object, _: Sel, _window: id) {
unsafe {
let view_state: *mut c_void = *this.get_ivar("viewState");
let view_state = &mut *(view_state as *mut ViewState);
(*view_state).handler.destroy();
}
}
impl WindowHandle {
pub fn show(&self) {
unsafe {
let window: id = msg_send![*self.nsview.load(), window];
// register our view class to be alerted when it becomes the key view.
let notif_center_class = class!(NSNotificationCenter);
let notif_string = NSString::alloc(nil)
.init_str(NSWindowDidBecomeKeyNotification)
.autorelease();
let notif_center: id = msg_send![notif_center_class, defaultCenter];
let () = msg_send![notif_center, addObserver:*self.nsview.load() selector: sel!(windowDidBecomeKey:) name: notif_string object: window];
window.makeKeyAndOrderFront_(nil)
}
}
/// Close the window.
pub fn close(&self) {
unsafe {
let window: id = msg_send![*self.nsview.load(), window];
let () = msg_send![window, performSelectorOnMainThread: sel!(close) withObject: nil waitUntilDone: NO];
}
}
/// Bring this window to the front of the window stack and give it focus.
pub fn bring_to_front_and_focus(&self) {
unsafe {
let window: id = msg_send![*self.nsview.load(), window];
let () = msg_send![window, performSelectorOnMainThread: sel!(makeKeyAndOrderFront:) withObject: nil waitUntilDone: NO];
}
}
// Request invalidation of the entire window contents.
pub fn invalidate(&self) {
unsafe {
// We could share impl with redraw, but we'd need to deal with nil.
let () = msg_send![*self.nsview.load(), setNeedsDisplay: YES];
}
}
/// Request invalidation of one rectangle.
pub fn invalidate_rect(&self, rect: Rect) {
let rect = NSRect::new(
NSPoint::new(rect.x0, rect.y0),
NSSize::new(rect.width(), rect.height()),
);
unsafe {
// We could share impl with redraw, but we'd need to deal with nil.
let () = msg_send![*self.nsview.load(), setNeedsDisplayInRect: rect];
}
}
pub fn set_cursor(&mut self, cursor: &Cursor) {
unsafe {
let nscursor = class!(NSCursor);
let cursor: id = match cursor {
Cursor::Arrow => msg_send![nscursor, arrowCursor],
Cursor::IBeam => msg_send![nscursor, IBeamCursor],
Cursor::Crosshair => msg_send![nscursor, crosshairCursor],
Cursor::OpenHand => msg_send![nscursor, openHandCursor],
Cursor::NotAllowed => msg_send![nscursor, operationNotAllowedCursor],
Cursor::ResizeLeftRight => msg_send![nscursor, resizeLeftRightCursor],
Cursor::ResizeUpDown => msg_send![nscursor, resizeUpDownCursor],
};
let () = msg_send![cursor, set];
}
}
pub fn request_timer(&self, deadline: std::time::Instant) -> TimerToken {
let ti = time_interval_from_deadline(deadline);
let token = TimerToken::next();
unsafe {
let nstimer = class!(NSTimer);
let nsnumber = class!(NSNumber);
let user_info: id = msg_send![nsnumber, numberWithUnsignedInteger: token.into_raw()];
let selector = sel!(handleTimer:);
let view = self.nsview.load();
let _: id = msg_send![nstimer, scheduledTimerWithTimeInterval: ti target: view selector: selector userInfo: user_info repeats: NO];
}
token
}
pub fn text(&self) -> Text {
Text::new()
}
pub fn open_file_sync(&mut self, options: FileDialogOptions) -> Option<FileInfo> {
dialog::get_file_dialog_path(FileDialogType::Open, options)
.map(|s| FileInfo { path: s.into() })
}
pub fn save_as_sync(&mut self, options: FileDialogOptions) -> Option<FileInfo> {
dialog::get_file_dialog_path(FileDialogType::Save, options)
.map(|s| FileInfo { path: s.into() })
}
/// Set the title for this menu.
pub fn set_title(&self, title: &str) {
unsafe {
let window: id = msg_send![*self.nsview.load(), window];
let title = make_nsstring(title);
window.setTitle_(title);
}
}
// TODO: Implement this
pub fn show_titlebar(&self, _show_titlebar: bool) {}
pub fn resizable(&self, resizable: bool) {
unsafe {
let window: id = msg_send![*self.nsview.load(), window];
let mut style_mask: NSWindowStyleMask = window.styleMask();
if resizable {
style_mask |= NSWindowStyleMask::NSResizableWindowMask;
} else {
style_mask &= !NSWindowStyleMask::NSResizableWindowMask;
}
window.setStyleMask_(style_mask);
}
}
pub fn set_menu(&self, menu: Menu) {
unsafe {
NSApp().setMainMenu_(menu.menu);
}
}
//FIXME: we should be using the x, y values passed by the caller, but then
//we have to figure out some way to pass them along with this performSelector:
//call. This isn't super hard, I'm just not up for it right now.
pub fn show_context_menu(&self, menu: Menu, _pos: Point) {
unsafe {
let () = msg_send![*self.nsview.load(), performSelectorOnMainThread: sel!(showContextMenu:) withObject: menu.menu waitUntilDone: NO];
}
}
/// Get a handle that can be used to schedule an idle task.
pub fn get_idle_handle(&self) -> Option<IdleHandle> {
if self.nsview.load().is_null() {
None
} else {
Some(IdleHandle {
nsview: self.nsview.clone(),
idle_queue: self.idle_queue.clone(),
})
}
}
/// Get the dpi of the window.
///
/// TODO: we want to migrate this from dpi (with 96 as nominal) to a scale
/// factor (with 1 as nominal).
pub fn get_dpi(&self) -> f32 {
// TODO: get actual dpi
96.0
}
}
unsafe impl Send for IdleHandle {}
impl IdleHandle {
/// Add an idle handler, which is called (once) when the message loop
/// is empty. The idle handler will be run from the main UI thread, and
/// won't be scheduled if the associated view has been dropped.
///
/// Note: the name "idle" suggests that it will be scheduled with a lower
/// priority than other UI events, but that's not necessarily the case.
pub fn add_idle_callback<F>(&self, callback: F)
where
F: FnOnce(&dyn Any) + Send + 'static,
{
if let Some(queue) = self.idle_queue.upgrade() {
let mut queue = queue.lock().expect("queue lock");
if queue.is_empty() {
unsafe {
let nsview = self.nsview.load();
// Note: the nsview might be nil here if the window has been dropped, but that's ok.
let () = msg_send!(*nsview, performSelectorOnMainThread: sel!(runIdle)
withObject: nil waitUntilDone: NO);
}
}
queue.push(IdleKind::Callback(Box::new(callback)));
}
}
pub fn add_idle_token(&self, token: IdleToken) {
if let Some(queue) = self.idle_queue.upgrade() {
let mut queue = queue.lock().expect("queue lock");
if queue.is_empty() {
unsafe {
let nsview = self.nsview.load();
// Note: the nsview might be nil here if the window has been dropped, but that's ok.
let () = msg_send!(*nsview, performSelectorOnMainThread: sel!(runIdle)
withObject: nil waitUntilDone: NO);
}
}
queue.push(IdleKind::Token(token));
}
}
}
/// Convert an `Instant` into an NSTimeInterval, i.e. a fractional number
/// of seconds from now.
///
/// This may lose some precision for multi-month durations.
fn time_interval_from_deadline(deadline: std::time::Instant) -> f64 {
let now = Instant::now();
if now >= deadline {
0.0
} else {
let t = deadline - now;
let secs = t.as_secs() as f64;
let subsecs = f64::from(t.subsec_micros()) * 0.000_001;
secs + subsecs
}
}
fn make_key_event(event: id) -> KeyEvent {
unsafe {
let chars = event.characters();
let slice = std::slice::from_raw_parts(chars.UTF8String() as *const _, chars.len());
let text = std::str::from_utf8_unchecked(slice);
let unmodified_chars = event.charactersIgnoringModifiers();
let slice = std::slice::from_raw_parts(
unmodified_chars.UTF8String() as *const _,
unmodified_chars.len(),
);
let unmodified_text = std::str::from_utf8_unchecked(slice);
let virtual_key = event.keyCode();
let is_repeat: bool = msg_send!(event, isARepeat);
let modifiers = event.modifierFlags();
let modifiers = make_modifiers(modifiers);
KeyEvent::new(virtual_key, is_repeat, modifiers, text, unmodified_text)
}
}
fn mods_changed_key_event(prev: KeyModifiers, event: id) -> (bool, KeyEvent) {
unsafe {
let key_code: KeyCode = event.keyCode().into();
let is_repeat = false;
let modifiers = event.modifierFlags();
let modifiers = make_modifiers(modifiers);
let down = match key_code {
KeyCode::LeftShift | KeyCode::RightShift if prev.shift => false,
KeyCode::LeftAlt | KeyCode::RightAlt if prev.alt => false,
KeyCode::LeftControl | KeyCode::RightControl if prev.ctrl => false,
KeyCode::LeftMeta | KeyCode::RightMeta if prev.meta => false,
_ => true,
};
let event = KeyEvent::new(key_code, is_repeat, modifiers, "", "");
(down, event)
}
}
fn make_modifiers(raw: NSEventModifierFlags) -> KeyModifiers {
KeyModifiers {
shift: raw.contains(NSEventModifierFlags::NSShiftKeyMask),
alt: raw.contains(NSEventModifierFlags::NSAlternateKeyMask),
ctrl: raw.contains(NSEventModifierFlags::NSControlKeyMask),
meta: raw.contains(NSEventModifierFlags::NSCommandKeyMask),
}
}