-
-
Notifications
You must be signed in to change notification settings - Fork 836
/
Copy pathwindow.rs
3307 lines (2932 loc) · 117 KB
/
window.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
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// let () = msg_send! is a common pattern for objc
#![allow(clippy::let_unit_value)]
use super::keycodes::*;
use super::{nsstring, nsstring_to_str};
use crate::clipboard::Clipboard as ClipboardContext;
use crate::connection::ConnectionOps;
use crate::os::macos::menu::{MenuItem, RepresentedItem};
use crate::parameters::{Border, Parameters, TitleBar};
use crate::{
Clipboard, Connection, DeadKeyStatus, Dimensions, Handled, KeyCode, KeyEvent, Modifiers,
MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point, RawKeyEvent, Rect,
RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, ScreenPoint, Size, ULength,
WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,
};
use anyhow::{anyhow, bail, ensure};
use async_trait::async_trait;
use cocoa::appkit::{
self, CGFloat, NSApplication, NSApplicationActivateIgnoringOtherApps,
NSApplicationPresentationOptions, NSBackingStoreBuffered, NSEvent, NSEventModifierFlags,
NSOpenGLContext, NSOpenGLPixelFormat, NSPasteboard, NSRunningApplication, NSScreen, NSView,
NSViewHeightSizable, NSViewWidthSizable, NSWindow, NSWindowStyleMask,
};
use cocoa::base::*;
use cocoa::foundation::{
NSArray, NSAutoreleasePool, NSFastEnumeration, NSInteger, NSNotFound, NSPoint, NSRect, NSSize,
NSUInteger,
};
use config::window::WindowLevel;
use config::ConfigHandle;
use core_foundation::base::{CFTypeID, TCFType};
use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFunctionPointerForName};
use core_foundation::data::{CFData, CFDataGetBytePtr, CFDataRef};
use core_foundation::string::{CFString, CFStringRef, UniChar};
use core_foundation::{declare_TCFType, impl_TCFType};
use objc::declare::ClassDecl;
use objc::rc::{StrongPtr, WeakPtr};
use objc::runtime::{Class, Object, Protocol, Sel};
use objc::*;
use promise::Future;
use raw_window_handle::{
AppKitDisplayHandle, AppKitWindowHandle, DisplayHandle, HandleError, HasDisplayHandle,
HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle,
};
use std::any::Any;
use std::cell::RefCell;
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr::NonNull;
use std::rc::Rc;
use std::str::FromStr;
use std::time::Instant;
use wezterm_font::FontConfiguration;
use wezterm_input_types::{is_ascii_control, IntegratedTitleButtonStyle, KeyboardLedStatus};
#[allow(non_upper_case_globals)]
const NSViewLayerContentsPlacementTopLeft: NSInteger = 11;
#[allow(non_upper_case_globals)]
const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGSMainConnectionID() -> id;
fn CGSSetWindowBackgroundBlurRadius(
connection_id: id,
window_id: NSInteger,
radius: i64,
) -> i32;
}
fn round_away_from_zerof(value: f64) -> f64 {
if value > 0. {
value.max(1.).round()
} else {
value.min(-1.).round()
}
}
fn round_away_from_zero(value: f64) -> i16 {
if value > 0. {
value.max(1.).round() as i16
} else {
value.min(-1.).round() as i16
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum ImeDisposition {
/// Nothing happened
None,
/// IME triggered an action
Acted,
/// We decided to continue with key dispatch
Continue,
}
#[repr(C)]
struct NSRange(cocoa::foundation::NSRange);
#[derive(Debug)]
#[repr(C)]
struct NSRangePointer(*mut NSRange);
impl std::fmt::Debug for NSRange {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
fmt.debug_struct("NSRange")
.field("location", &self.0.location)
.field("length", &self.0.length)
.finish()
}
}
unsafe impl objc::Encode for NSRange {
fn encode() -> objc::Encoding {
let encoding = format!(
"{{NSRange={}{}}}",
NSUInteger::encode().as_str(),
NSUInteger::encode().as_str()
);
unsafe { objc::Encoding::from_str(&encoding) }
}
}
unsafe impl objc::Encode for NSRangePointer {
fn encode() -> objc::Encoding {
unsafe { objc::Encoding::from_str(&format!("^{}", NSRange::encode().as_str())) }
}
}
impl NSRange {
fn new(location: u64, length: u64) -> Self {
Self(cocoa::foundation::NSRange { location, length })
}
}
#[derive(Clone)]
pub enum BackendImpl {
Cgl(Rc<cglbits::GlState>),
Egl(Rc<crate::egl::GlState>),
}
impl BackendImpl {
pub fn update(&self) {
if let Self::Cgl(be) = self {
be.update();
}
}
}
#[derive(Clone)]
pub struct GlContextPair {
pub context: Rc<glium::backend::Context>,
pub backend: BackendImpl,
}
impl GlContextPair {
/// on macOS we first try to initialize EGL by dynamically loading it.
/// The system doesn't provide an EGL implementation, but the ANGLE
/// project (and MetalANGLE) both provide implementations.
/// The ANGLE EGL implementation wants a CALayer descendant passed
/// as the EGLNativeWindowType.
pub fn create(view: id) -> anyhow::Result<Self> {
let behavior = if cfg!(debug_assertions) {
glium::debug::DebugCallbackBehavior::DebugMessageOnError
} else {
glium::debug::DebugCallbackBehavior::Ignore
};
// Let's first try to initialize EGL...
let (context, backend) = match if config::configuration().prefer_egl {
// ANGLE wants a layer, so tell the view to create one.
// Importantly, we must set its scale to 1.0 prior to initializing
// EGL to prevent undesirable scaling.
let layer: id;
unsafe {
let _: () = msg_send![view, setWantsLayer: YES];
layer = msg_send![view, layer];
let _: () = msg_send![layer, setContentsScale: 1.0f64];
let _: () = msg_send![layer, setOpaque: NO];
};
let conn = Connection::get().unwrap();
let state = match conn.gl_connection.borrow().as_ref() {
None => crate::egl::GlState::create(None, layer as *const c_void),
Some(glconn) => crate::egl::GlState::create_with_existing_connection(
glconn,
layer as *const c_void,
),
};
if state.is_ok() {
conn.gl_connection
.borrow_mut()
.replace(Rc::clone(state.as_ref().unwrap().get_connection()));
// ANGLE will create a CAMetalLayer as a sublayer of our provided
// layer. Even though CALayer defaults to !opaque, CAMetalLayer
// defaults to opaque, so we need to find that layer and fix
// the opacity so that our alpha values are respected.
unsafe {
let sublayers: id = msg_send![layer, sublayers];
let layer_count = sublayers.count();
for i in 0..layer_count {
let layer = sublayers.objectAtIndex(i);
let _: () = msg_send![layer, setOpaque: NO];
}
}
}
state
} else {
Err(anyhow!("prefers not to use EGL"))
} {
Ok(backend) => {
let backend = Rc::new(backend);
let context =
unsafe { glium::backend::Context::new(Rc::clone(&backend), true, behavior) }?;
(context, BackendImpl::Egl(backend))
}
// ... and then fallback to the deprecated platform provided CGL
Err(err) => {
log::debug!("EGL init failed: {:#}, falling back to CGL", err);
let backend = Rc::new(cglbits::GlState::create(view)?);
let context =
unsafe { glium::backend::Context::new(Rc::clone(&backend), true, behavior) }?;
(context, BackendImpl::Cgl(backend))
}
};
Ok(Self { context, backend })
}
}
mod cglbits {
use super::*;
pub struct GlState {
_pixel_format: StrongPtr,
gl_context: StrongPtr,
}
impl GlState {
pub fn create(view: id) -> anyhow::Result<Self> {
log::trace!("Calling NSOpenGLPixelFormat::initWithAttributes");
let pixel_format = unsafe {
StrongPtr::new(NSOpenGLPixelFormat::alloc(nil).initWithAttributes_(&[
appkit::NSOpenGLPFAOpenGLProfile as u32,
appkit::NSOpenGLProfileVersion3_2Core as u32,
appkit::NSOpenGLPFAClosestPolicy as u32,
appkit::NSOpenGLPFAColorSize as u32,
32,
appkit::NSOpenGLPFAAlphaSize as u32,
8,
appkit::NSOpenGLPFADepthSize as u32,
24,
appkit::NSOpenGLPFAStencilSize as u32,
8,
appkit::NSOpenGLPFAAllowOfflineRenderers as u32,
appkit::NSOpenGLPFAAccelerated as u32,
appkit::NSOpenGLPFADoubleBuffer as u32,
0,
]))
};
log::trace!("NSOpenGLPixelFormat::initWithAttributes returned");
ensure!(
!pixel_format.is_null(),
"failed to create NSOpenGLPixelFormat"
);
// Allow using retina resolutions; without this we're forced into low res
// and the system will scale us up, resulting in blurry rendering
unsafe {
let _: () = msg_send![view, setWantsBestResolutionOpenGLSurface: YES];
}
let gl_context = unsafe {
StrongPtr::new(
NSOpenGLContext::alloc(nil).initWithFormat_shareContext_(*pixel_format, nil),
)
};
ensure!(!gl_context.is_null(), "failed to create NSOpenGLContext");
unsafe {
let opaque: cgl::GLint = 0;
gl_context.setValues_forParameter_(
&opaque,
cocoa::appkit::NSOpenGLContextParameter::NSOpenGLCPSurfaceOpacity,
);
gl_context.setView_(view);
// Explicitly disable vsync; we'll manage throttling frames at
// the application level
let swap_interval: cgl::GLint = 0;
gl_context.setValues_forParameter_(
&swap_interval,
cocoa::appkit::NSOpenGLContextParameter::NSOpenGLCPSwapInterval,
);
}
Ok(Self {
_pixel_format: pixel_format,
gl_context,
})
}
/// Calls NSOpenGLContext update; we need to do this on resize
pub fn update(&self) {
unsafe {
let _: () = msg_send![*self.gl_context, update];
}
}
}
unsafe impl glium::backend::Backend for GlState {
fn resize(&self, _: (u32, u32)) {
todo!()
}
fn swap_buffers(&self) -> Result<(), glium::SwapBuffersError> {
unsafe {
let pool = NSAutoreleasePool::new(nil);
self.gl_context.flushBuffer();
let _: () = msg_send![pool, release];
}
Ok(())
}
unsafe fn get_proc_address(&self, symbol: &str) -> *const c_void {
let symbol_name: CFString = FromStr::from_str(symbol).unwrap();
let framework_name: CFString = FromStr::from_str("com.apple.opengl").unwrap();
let framework = CFBundleGetBundleWithIdentifier(framework_name.as_concrete_TypeRef());
let symbol =
CFBundleGetFunctionPointerForName(framework, symbol_name.as_concrete_TypeRef());
symbol as *const _
}
fn get_framebuffer_dimensions(&self) -> (u32, u32) {
unsafe {
let view = self.gl_context.view();
let frame = NSView::frame(view);
let backing_frame = NSView::convertRectToBacking(view, frame);
(
backing_frame.size.width as u32,
backing_frame.size.height as u32,
)
}
}
fn is_current(&self) -> bool {
unsafe {
let pool = NSAutoreleasePool::new(nil);
let current = NSOpenGLContext::currentContext(nil);
let res = if current != nil {
let is_equal: BOOL = msg_send![current, isEqual: *self.gl_context];
is_equal != NO
} else {
false
};
let _: () = msg_send![pool, release];
res
}
}
unsafe fn make_current(&self) {
let _: () = msg_send![*self.gl_context, update];
self.gl_context.makeCurrentContext();
}
}
}
pub(crate) struct WindowInner {
view: StrongPtr,
window: StrongPtr,
config: ConfigHandle,
}
fn function_key_to_keycode(function_key: char) -> KeyCode {
// FIXME: CTRL-C is 0x3, should it be normalized to C here
// using the unmod string? Or should be normalize the 0x3
// as the canonical representation of that input?
match function_key as u16 {
appkit::NSUpArrowFunctionKey => KeyCode::UpArrow,
appkit::NSDownArrowFunctionKey => KeyCode::DownArrow,
appkit::NSLeftArrowFunctionKey => KeyCode::LeftArrow,
appkit::NSRightArrowFunctionKey => KeyCode::RightArrow,
appkit::NSHomeFunctionKey => KeyCode::Home,
appkit::NSEndFunctionKey => KeyCode::End,
appkit::NSPageUpFunctionKey => KeyCode::PageUp,
appkit::NSPageDownFunctionKey => KeyCode::PageDown,
appkit::NSClearLineFunctionKey => KeyCode::NumLock,
value @ appkit::NSF1FunctionKey..=appkit::NSF35FunctionKey => {
KeyCode::Function((value - appkit::NSF1FunctionKey + 1) as u8)
}
appkit::NSInsertFunctionKey => KeyCode::Insert,
appkit::NSDeleteFunctionKey => KeyCode::Char('\u{7f}'),
appkit::NSPrintScreenFunctionKey => KeyCode::PrintScreen,
appkit::NSScrollLockFunctionKey => KeyCode::ScrollLock,
appkit::NSPauseFunctionKey => KeyCode::Pause,
appkit::NSBreakFunctionKey => KeyCode::Cancel,
appkit::NSPrintFunctionKey => KeyCode::Print,
_ => KeyCode::Char(function_key),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct Window {
id: usize,
ns_window: *mut Object,
ns_view: *mut Object,
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
fn set_window_position(window: *mut Object, coords: ScreenPoint) {
unsafe {
let cartesian = screen_point_to_cartesian(coords);
let frame = NSWindow::frame(window);
let content_frame = NSWindow::contentRectForFrameRect_(window, frame);
let delta_x = content_frame.origin.x - frame.origin.x;
let delta_y = content_frame.origin.y - frame.origin.y;
let point = NSPoint::new(
cartesian.x as f64 - delta_x,
cartesian.y as f64 - delta_y - content_frame.size.height,
);
NSWindow::setFrameOrigin_(window, point);
}
}
impl Window {
pub async fn new_window<F>(
_class_name: &str,
name: &str,
geometry: RequestedWindowGeometry,
config: Option<&ConfigHandle>,
_font_config: Rc<FontConfiguration>,
event_handler: F,
) -> anyhow::Result<Window>
where
F: 'static + FnMut(WindowEvent, &Window),
{
let config = match config {
Some(c) => c.clone(),
None => config::configuration(),
};
let conn = Connection::get().expect("new_window called on gui thread");
let ResolvedGeometry {
width,
height,
x,
y,
} = conn.resolve_geometry(geometry);
let scale_factor = (conn.default_dpi() / crate::DEFAULT_DPI) as usize;
let width = width / scale_factor;
let height = height / scale_factor;
let x = x.map(|x| x / scale_factor as i32);
let y = y.map(|y| y / scale_factor as i32);
let initial_pos = match (x, y) {
(Some(x), Some(y)) => Some(ScreenPoint::new(x as isize, y as isize)),
_ => None,
};
unsafe {
let style_mask = decoration_to_mask(
config.window_decorations,
config.integrated_title_button_style,
);
let rect = NSRect::new(
NSPoint::new(0., 0.),
NSSize::new(width as f64, height as f64),
);
let conn = Connection::get().expect("Connection::init has not been called");
let window_id = conn.next_window_id();
let events = WindowEventSender::new(event_handler);
let inner = Rc::new(RefCell::new(Inner {
events,
view_id: None,
window_id,
window: None,
screen_changed: false,
paint_throttled: false,
invalidated: true,
gl_context_pair: None,
text_cursor_position: Rect::new(Point::new(0, 0), Size::new(0, 0)),
tracking_rect_tag: 0,
hscroll_remainder: 0.,
vscroll_remainder: 0.,
last_wheel: Instant::now(),
key_is_down: None,
dead_pending: None,
fullscreen: None,
config: config.clone(),
ime_state: ImeDisposition::None,
ime_last_event: None,
live_resizing: false,
ime_text: String::new(),
}));
let window: id = msg_send![get_window_class(), alloc];
let window = StrongPtr::new(NSWindow::initWithContentRect_styleMask_backing_defer_(
window,
rect,
style_mask,
NSBackingStoreBuffered,
NO,
));
apply_decorations_to_window(
&window,
config.window_decorations,
config.integrated_title_button_style,
);
// Prevent Cocoa native tabs from being used
let _: () = msg_send![*window, setTabbingMode:2 /* NSWindowTabbingModeDisallowed */];
let _: () = msg_send![*window, setRestorable: NO];
window.setReleasedWhenClosed_(NO);
window.setBackgroundColor_(cocoa::appkit::NSColor::clearColor(nil));
// Tell Cocoa that we output in sRGB, so it handles color space
// conversion for non-sRGB displays.
window.setColorSpace_(cocoa::appkit::NSColorSpace::sRGBColorSpace(nil));
// We could set this, but it makes the entire window, including
// its titlebar, opaque to this fixed degree.
// window.setAlphaValue_(0.4);
// Window positioning: the first window opens up in the center of
// the screen. Subsequent windows will be offset from the position
// of the prior window at the time it was created. It's not a
// perfect algorithm by any means, and doesn't take in account
// windows moving and closing since the last creation, but it is
// better than creating them all centered which is what we used
// to do here.
thread_local! {
static LAST_POSITION: RefCell<Option<NSPoint>> = RefCell::new(None);
}
let frame = NSWindow::frame(*window);
let active_screen = NSScreen::mainScreen(nil);
let active_screen_frame = NSScreen::frame(active_screen);
fn point_in_rect(pt: NSPoint, rect: NSRect) -> bool {
let rect: euclid::Rect<f64, ()> = euclid::rect(
rect.origin.x,
rect.origin.y,
rect.size.width,
rect.size.height,
);
rect.contains(euclid::point2(pt.x, pt.y))
}
LAST_POSITION.with(|last_pos| {
if let Some(pos) = initial_pos {
// Put it where they asked it to be, without influencing
// future positioning info
set_window_position(*window, pos);
return;
}
let pos = last_pos.borrow_mut().take();
let next_pos = match pos {
Some(pos) if point_in_rect(pos, active_screen_frame) => {
// Only continue the cascade if the prior point is
// still within the currently active screen
window.cascadeTopLeftFromPoint_(pos)
}
_ => {
// Otherwise, position as if it is the first time
// we're displaying on this screen
window.center();
window.cascadeTopLeftFromPoint_(frame.origin)
}
};
last_pos.borrow_mut().replace(next_pos);
});
window.setTitle_(*nsstring(&name));
window.setAcceptsMouseMovedEvents_(YES);
let view = WindowView::alloc(&inner)?;
view.initWithFrame_(rect);
view.setAutoresizingMask_(NSViewHeightSizable | NSViewWidthSizable);
let () = msg_send![
*view,
setLayerContentsPlacement: NSViewLayerContentsPlacementTopLeft
];
CGSSetWindowBackgroundBlurRadius(
CGSMainConnectionID(),
window.windowNumber(),
config.macos_window_background_blur,
);
window.setContentView_(*view);
window.setDelegate_(*view);
view.setWantsLayer(YES);
let () = msg_send![
*view,
setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
];
// register for drag and drop operations.
let () = msg_send![
*window,
registerForDraggedTypes:
NSArray::arrayWithObject(nil, appkit::NSFilenamesPboardType)
];
let frame = NSView::frame(*view);
let backing_frame = NSView::convertRectToBacking(*view, frame);
let width = backing_frame.size.width;
let height = backing_frame.size.height;
let dpi = dpi_for_window_screen(*window, &config)
.unwrap_or(crate::DEFAULT_DPI * (backing_frame.size.width / frame.size.width))
as usize;
let weak_window = window.weak();
let window_handle = Window {
id: window_id,
ns_window: *window,
ns_view: *view,
};
let window_inner = Rc::new(RefCell::new(WindowInner {
window,
view,
config: config.clone(),
}));
inner.borrow_mut().window.replace(weak_window);
conn.windows
.borrow_mut()
.insert(window_id, Rc::clone(&window_inner));
inner
.borrow_mut()
.events
.assign_window(window_handle.clone());
window_handle.config_did_change(&config);
// Synthesize a resize event immediately; this allows
// the embedding application an opportunity to discover
// the dpi and adjust for display scaling
inner.borrow_mut().events.dispatch(WindowEvent::Resized {
dimensions: Dimensions {
pixel_width: width as usize,
pixel_height: height as usize,
dpi,
},
window_state: WindowState::default(),
live_resizing: false,
});
Ok(window_handle)
}
}
}
impl HasDisplayHandle for Window {
fn display_handle(&self) -> Result<DisplayHandle, HandleError> {
unsafe {
Ok(DisplayHandle::borrow_raw(RawDisplayHandle::AppKit(
AppKitDisplayHandle::new(),
)))
}
}
}
impl HasWindowHandle for Window {
fn window_handle(&self) -> Result<WindowHandle, HandleError> {
let mut handle =
AppKitWindowHandle::new(NonNull::new(self.ns_view as *mut _).expect("non-null"));
unsafe { Ok(WindowHandle::borrow_raw(RawWindowHandle::AppKit(handle))) }
}
}
/// @see https://developer.apple.com/documentation/appkit/nswindow/level
pub type NSWindowLevel = i64;
pub fn nswindow_level_to_window_level(nswindow_level: NSWindowLevel) -> WindowLevel {
match nswindow_level {
-1 => WindowLevel::AlwaysOnBottom,
0 => WindowLevel::Normal,
3 => WindowLevel::AlwaysOnTop,
_ => panic!("Invalid window level: {}", nswindow_level),
}
}
pub fn window_level_to_nswindow_level(level: WindowLevel) -> NSWindowLevel {
match level {
WindowLevel::AlwaysOnBottom => -1,
WindowLevel::Normal => 0,
WindowLevel::AlwaysOnTop => 3,
}
}
#[async_trait(?Send)]
impl WindowOps for Window {
async fn enable_opengl(&self) -> anyhow::Result<Rc<glium::backend::Context>> {
let window_id = self.id;
promise::spawn::spawn(async move {
if let Some(handle) = Connection::get().unwrap().window_by_id(window_id) {
let mut inner = handle.borrow_mut();
inner.enable_opengl()
} else {
bail!("invalid window");
}
})
.await
}
fn notify<T: Any + Send + Sync>(&self, t: T)
where
Self: Sized,
{
Connection::with_window_inner(self.id, move |inner| {
if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {
window_view
.inner
.borrow_mut()
.events
.dispatch(WindowEvent::Notification(Box::new(t)));
}
Ok(())
});
}
fn close(&self) {
Connection::with_window_inner(self.id, |inner| {
inner.close();
Ok(())
});
}
fn focus(&self) {
Connection::with_window_inner(self.id, |inner| {
inner.focus();
Ok(())
});
}
fn hide(&self) {
Connection::with_window_inner(self.id, |inner| {
inner.hide();
Ok(())
});
}
fn show(&self) {
Connection::with_window_inner(self.id, |inner| {
inner.show();
Ok(())
});
}
fn set_cursor(&self, cursor: Option<MouseCursor>) {
Connection::with_window_inner(self.id, move |inner| {
let _ = inner.set_cursor(cursor);
Ok(())
});
}
fn invalidate(&self) {
Connection::with_window_inner(self.id, |inner| {
inner.invalidate();
Ok(())
});
}
fn set_title(&self, title: &str) {
let title = title.to_owned();
Connection::with_window_inner(self.id, move |inner| {
inner.set_title(&title);
Ok(())
});
}
fn set_window_level(&self, level: WindowLevel) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_window_level(level);
Ok(())
});
}
fn set_inner_size(&self, width: usize, height: usize) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_inner_size(width, height);
if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {
window_view
.inner
.borrow_mut()
.events
.dispatch(WindowEvent::SetInnerSizeCompleted);
}
Ok(())
});
}
fn set_window_position(&self, coords: ScreenPoint) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_window_position(coords);
Ok(())
});
}
fn set_text_cursor_position(&self, cursor: Rect) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_text_cursor_position(cursor);
Ok(())
});
}
fn get_clipboard(&self, _clipboard: Clipboard) -> Future<String> {
Future::result(
ClipboardContext::new()
.read()
.map_err(|e| anyhow!("Failed to get clipboard:{}", e)),
)
}
fn set_clipboard(&self, _clipboard: Clipboard, text: String) {
ClipboardContext::new().write(text).ok();
}
fn toggle_fullscreen(&self) {
Connection::with_window_inner(self.id, move |inner| {
inner.toggle_fullscreen();
Ok(())
});
}
fn maximize(&self) {
Connection::with_window_inner(self.id, move |inner| {
inner.maximize();
Ok(())
});
}
fn restore(&self) {
Connection::with_window_inner(self.id, move |inner| {
inner.restore();
Ok(())
});
}
fn set_resize_increments(&self, incr: ResizeIncrement) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_resize_increments(incr);
Ok(())
});
}
fn config_did_change(&self, config: &ConfigHandle) {
let config = config.clone();
Connection::with_window_inner(self.id, move |inner| {
inner.config_did_change(&config);
Ok(())
});
}
fn get_os_parameters(
&self,
_config: &ConfigHandle,
window_state: WindowState,
) -> anyhow::Result<Option<Parameters>> {
// We implement this method primarily to provide Notch-avoidance for
// systems with a notch.
// We only need this for non-native full screen mode.
let native_full_screen = {
let style_mask = unsafe { NSWindow::styleMask(self.ns_window) };
style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
};
let border_dimensions =
if window_state.contains(WindowState::FULL_SCREEN) && !native_full_screen {
let main_screen = unsafe { NSScreen::mainScreen(nil) };
let has_safe_area_insets: BOOL =
unsafe { msg_send![main_screen, respondsToSelector: sel!(safeAreaInsets)] };
if has_safe_area_insets == YES {
#[derive(Debug)]
struct NSEdgeInsets {
top: CGFloat,
left: CGFloat,
bottom: CGFloat,
right: CGFloat,
}
let insets: NSEdgeInsets = unsafe { msg_send![main_screen, safeAreaInsets] };
log::trace!("{:?}", insets);
let scale = unsafe {
let frame = NSScreen::frame(main_screen);
let backing_frame = NSScreen::convertRectToBacking_(main_screen, frame);
backing_frame.size.height / frame.size.height
};
let top = (insets.top.ceil() * scale) as usize;
Some(Border {
top: ULength::new(top),
left: ULength::new(insets.left.ceil() as usize),
right: ULength::new(insets.right.ceil() as usize),
bottom: ULength::new(insets.bottom.ceil() as usize),
color: crate::color::LinearRgba::with_components(0., 0., 0., 1.),
})
} else {
None
}
} else {
None
};
Ok(Some(Parameters {
title_bar: TitleBar {
padding_left: ULength::new(0),
padding_right: ULength::new(0),
height: None,
font_and_size: None,
},
border_dimensions,
}))
}
}
/// Convert from a macOS screen coordinate with the origin in the bottom left
/// to a pixel coordinate with its origin in the top left
fn cartesian_to_screen_point(cartesian: NSPoint) -> ScreenPoint {
unsafe {
let screens = NSScreen::screens(nil);
let primary = screens.objectAtIndex(0);
let frame = NSScreen::frame(primary);
let backing_frame = NSScreen::convertRectToBacking_(primary, frame);
let scale = backing_frame.size.height / frame.size.height;
ScreenPoint::new(
(cartesian.x * scale) as isize,
((frame.size.height - cartesian.y) * scale) as isize,
)
}
}
/// Convert from a pixel coordinate in the top left to a macOS screen
/// coordinate with its origin in the bottom left
fn screen_point_to_cartesian(point: ScreenPoint) -> NSPoint {
unsafe {
let screens = NSScreen::screens(nil);
let primary = screens.objectAtIndex(0);
let frame = NSScreen::frame(primary);
let backing_frame = NSScreen::convertRectToBacking_(primary, frame);
let scale = backing_frame.size.height / frame.size.height;
NSPoint::new(
point.x as f64 / scale,
frame.size.height - (point.y as f64 / scale),
)
}
}
impl WindowInner {
fn enable_opengl(&mut self) -> anyhow::Result<Rc<glium::backend::Context>> {
if let Some(window_view) = WindowView::get_this(unsafe { &**self.view }) {
window_view.inner.borrow_mut().enable_opengl()
} else {
anyhow::bail!("window invalid");
}
}
fn is_fullscreen(&mut self) -> bool {
if self.is_native_fullscreen() {
true
} else if let Some(window_view) = WindowView::get_this(unsafe { &**self.view }) {
window_view.inner.borrow().fullscreen.is_some()
} else {
false
}
}
fn apply_decorations(&mut self) {
if !self.is_fullscreen() {
apply_decorations_to_window(
&self.window,
self.config.window_decorations,
self.config.integrated_title_button_style,
);
}
}
fn toggle_native_fullscreen(&mut self) {
unsafe {
NSWindow::toggleFullScreen_(*self.window, nil);
}
}