1use super::{display_bounds_from_native, ns_string, MacDisplay, MetalRenderer, NSRange};
2use crate::{
3 display_bounds_to_native, point, px, size, AnyWindowHandle, Bounds, ExternalPaths,
4 FileDropEvent, ForegroundExecutor, GlobalPixels, KeyDownEvent, Keystroke, Modifiers,
5 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
6 PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
7 PromptLevel, Size, Timer, WindowAppearance, WindowBounds, WindowKind, WindowOptions,
8};
9use block::ConcreteBlock;
10use cocoa::{
11 appkit::{
12 CGPoint, NSApplication, NSBackingStoreBuffered, NSEventModifierFlags,
13 NSFilenamesPboardType, NSPasteboard, NSScreen, NSView, NSViewHeightSizable,
14 NSViewWidthSizable, NSWindow, NSWindowButton, NSWindowCollectionBehavior,
15 NSWindowStyleMask, NSWindowTitleVisibility,
16 },
17 base::{id, nil},
18 foundation::{
19 NSArray, NSAutoreleasePool, NSDictionary, NSFastEnumeration, NSInteger, NSPoint, NSRect,
20 NSSize, NSString, NSUInteger,
21 },
22};
23use core_graphics::display::CGRect;
24use ctor::ctor;
25use foreign_types::ForeignTypeRef;
26use futures::channel::oneshot;
27use objc::{
28 class,
29 declare::ClassDecl,
30 msg_send,
31 runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
32 sel, sel_impl,
33};
34use parking_lot::Mutex;
35use smallvec::SmallVec;
36use std::{
37 any::Any,
38 cell::{Cell, RefCell},
39 ffi::{c_void, CStr},
40 mem,
41 ops::Range,
42 os::raw::c_char,
43 path::PathBuf,
44 ptr,
45 rc::Rc,
46 sync::{Arc, Weak},
47 time::Duration,
48};
49
50const WINDOW_STATE_IVAR: &str = "windowState";
51
52static mut WINDOW_CLASS: *const Class = ptr::null();
53static mut PANEL_CLASS: *const Class = ptr::null();
54static mut VIEW_CLASS: *const Class = ptr::null();
55
56#[allow(non_upper_case_globals)]
57const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
58 unsafe { NSWindowStyleMask::from_bits_unchecked(1 << 7) };
59#[allow(non_upper_case_globals)]
60const NSNormalWindowLevel: NSInteger = 0;
61#[allow(non_upper_case_globals)]
62const NSPopUpWindowLevel: NSInteger = 101;
63#[allow(non_upper_case_globals)]
64const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
65#[allow(non_upper_case_globals)]
66const NSTrackingMouseMoved: NSUInteger = 0x02;
67#[allow(non_upper_case_globals)]
68const NSTrackingActiveAlways: NSUInteger = 0x80;
69#[allow(non_upper_case_globals)]
70const NSTrackingInVisibleRect: NSUInteger = 0x200;
71#[allow(non_upper_case_globals)]
72const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
73#[allow(non_upper_case_globals)]
74const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
75// https://developer.apple.com/documentation/appkit/nsdragoperation
76type NSDragOperation = NSUInteger;
77#[allow(non_upper_case_globals)]
78const NSDragOperationNone: NSDragOperation = 0;
79#[allow(non_upper_case_globals)]
80const NSDragOperationCopy: NSDragOperation = 1;
81
82#[ctor]
83unsafe fn build_classes() {
84 WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
85 PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
86 VIEW_CLASS = {
87 let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
88 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
89
90 decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
91
92 decl.add_method(
93 sel!(performKeyEquivalent:),
94 handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
95 );
96 decl.add_method(
97 sel!(keyDown:),
98 handle_key_down as extern "C" fn(&Object, Sel, id),
99 );
100 decl.add_method(
101 sel!(mouseDown:),
102 handle_view_event as extern "C" fn(&Object, Sel, id),
103 );
104 decl.add_method(
105 sel!(mouseUp:),
106 handle_view_event as extern "C" fn(&Object, Sel, id),
107 );
108 decl.add_method(
109 sel!(rightMouseDown:),
110 handle_view_event as extern "C" fn(&Object, Sel, id),
111 );
112 decl.add_method(
113 sel!(rightMouseUp:),
114 handle_view_event as extern "C" fn(&Object, Sel, id),
115 );
116 decl.add_method(
117 sel!(otherMouseDown:),
118 handle_view_event as extern "C" fn(&Object, Sel, id),
119 );
120 decl.add_method(
121 sel!(otherMouseUp:),
122 handle_view_event as extern "C" fn(&Object, Sel, id),
123 );
124 decl.add_method(
125 sel!(mouseMoved:),
126 handle_view_event as extern "C" fn(&Object, Sel, id),
127 );
128 decl.add_method(
129 sel!(mouseExited:),
130 handle_view_event as extern "C" fn(&Object, Sel, id),
131 );
132 decl.add_method(
133 sel!(mouseDragged:),
134 handle_view_event as extern "C" fn(&Object, Sel, id),
135 );
136 decl.add_method(
137 sel!(scrollWheel:),
138 handle_view_event as extern "C" fn(&Object, Sel, id),
139 );
140 decl.add_method(
141 sel!(flagsChanged:),
142 handle_view_event as extern "C" fn(&Object, Sel, id),
143 );
144 decl.add_method(
145 sel!(cancelOperation:),
146 cancel_operation as extern "C" fn(&Object, Sel, id),
147 );
148
149 decl.add_method(
150 sel!(makeBackingLayer),
151 make_backing_layer as extern "C" fn(&Object, Sel) -> id,
152 );
153
154 decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
155 decl.add_method(
156 sel!(viewDidChangeBackingProperties),
157 view_did_change_backing_properties as extern "C" fn(&Object, Sel),
158 );
159 decl.add_method(
160 sel!(setFrameSize:),
161 set_frame_size as extern "C" fn(&Object, Sel, NSSize),
162 );
163 decl.add_method(
164 sel!(displayLayer:),
165 display_layer as extern "C" fn(&Object, Sel, id),
166 );
167
168 decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
169 decl.add_method(
170 sel!(validAttributesForMarkedText),
171 valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
172 );
173 decl.add_method(
174 sel!(hasMarkedText),
175 has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
176 );
177 decl.add_method(
178 sel!(markedRange),
179 marked_range as extern "C" fn(&Object, Sel) -> NSRange,
180 );
181 decl.add_method(
182 sel!(selectedRange),
183 selected_range as extern "C" fn(&Object, Sel) -> NSRange,
184 );
185 decl.add_method(
186 sel!(firstRectForCharacterRange:actualRange:),
187 first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
188 );
189 decl.add_method(
190 sel!(insertText:replacementRange:),
191 insert_text as extern "C" fn(&Object, Sel, id, NSRange),
192 );
193 decl.add_method(
194 sel!(setMarkedText:selectedRange:replacementRange:),
195 set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
196 );
197 decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
198 decl.add_method(
199 sel!(attributedSubstringForProposedRange:actualRange:),
200 attributed_substring_for_proposed_range
201 as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
202 );
203 decl.add_method(
204 sel!(viewDidChangeEffectiveAppearance),
205 view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
206 );
207
208 // Suppress beep on keystrokes with modifier keys.
209 decl.add_method(
210 sel!(doCommandBySelector:),
211 do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
212 );
213
214 decl.add_method(
215 sel!(acceptsFirstMouse:),
216 accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
217 );
218
219 decl.register()
220 };
221}
222
223pub fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
224 point(
225 px(position.x as f32),
226 // MacOS screen coordinates are relative to bottom left
227 window_height - px(position.y as f32),
228 )
229}
230
231unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
232 let mut decl = ClassDecl::new(name, superclass).unwrap();
233 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
234 decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
235 decl.add_method(
236 sel!(canBecomeMainWindow),
237 yes as extern "C" fn(&Object, Sel) -> BOOL,
238 );
239 decl.add_method(
240 sel!(canBecomeKeyWindow),
241 yes as extern "C" fn(&Object, Sel) -> BOOL,
242 );
243 decl.add_method(
244 sel!(windowDidResize:),
245 window_did_resize as extern "C" fn(&Object, Sel, id),
246 );
247 decl.add_method(
248 sel!(windowWillEnterFullScreen:),
249 window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
250 );
251 decl.add_method(
252 sel!(windowWillExitFullScreen:),
253 window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
254 );
255 decl.add_method(
256 sel!(windowDidMove:),
257 window_did_move as extern "C" fn(&Object, Sel, id),
258 );
259 decl.add_method(
260 sel!(windowDidBecomeKey:),
261 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
262 );
263 decl.add_method(
264 sel!(windowDidResignKey:),
265 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
266 );
267 decl.add_method(
268 sel!(windowShouldClose:),
269 window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
270 );
271
272 decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
273
274 decl.add_method(
275 sel!(draggingEntered:),
276 dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
277 );
278 decl.add_method(
279 sel!(draggingUpdated:),
280 dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
281 );
282 decl.add_method(
283 sel!(draggingExited:),
284 dragging_exited as extern "C" fn(&Object, Sel, id),
285 );
286 decl.add_method(
287 sel!(performDragOperation:),
288 perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
289 );
290 decl.add_method(
291 sel!(concludeDragOperation:),
292 conclude_drag_operation as extern "C" fn(&Object, Sel, id),
293 );
294
295 decl.register()
296}
297
298///Used to track what the IME does when we send it a keystroke.
299///This is only used to handle the case where the IME mysteriously
300///swallows certain keys.
301///
302///Basically a direct copy of the approach that WezTerm uses in:
303///github.com/wez/wezterm : d5755f3e : window/src/os/macos/window.rs
304enum ImeState {
305 Continue,
306 Acted,
307 None,
308}
309
310struct InsertText {
311 replacement_range: Option<Range<usize>>,
312 text: String,
313}
314
315struct MacWindowState {
316 handle: AnyWindowHandle,
317 executor: ForegroundExecutor,
318 native_window: id,
319 renderer: MetalRenderer,
320 kind: WindowKind,
321 request_frame_callback: Option<Box<dyn FnMut()>>,
322 event_callback: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
323 activate_callback: Option<Box<dyn FnMut(bool)>>,
324 resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
325 fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
326 moved_callback: Option<Box<dyn FnMut()>>,
327 should_close_callback: Option<Box<dyn FnMut() -> bool>>,
328 close_callback: Option<Box<dyn FnOnce()>>,
329 appearance_changed_callback: Option<Box<dyn FnMut()>>,
330 input_handler: Option<Box<dyn PlatformInputHandler>>,
331 pending_key_down: Option<(KeyDownEvent, Option<InsertText>)>,
332 last_key_equivalent: Option<KeyDownEvent>,
333 synthetic_drag_counter: usize,
334 last_fresh_keydown: Option<Keystroke>,
335 traffic_light_position: Option<Point<Pixels>>,
336 previous_modifiers_changed_event: Option<PlatformInput>,
337 // State tracking what the IME did after the last request
338 ime_state: ImeState,
339 // Retains the last IME Text
340 ime_text: Option<String>,
341 external_files_dragged: bool,
342}
343
344impl MacWindowState {
345 fn move_traffic_light(&self) {
346 if let Some(traffic_light_position) = self.traffic_light_position {
347 let titlebar_height = self.titlebar_height();
348
349 unsafe {
350 let close_button: id = msg_send![
351 self.native_window,
352 standardWindowButton: NSWindowButton::NSWindowCloseButton
353 ];
354 let min_button: id = msg_send![
355 self.native_window,
356 standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
357 ];
358 let zoom_button: id = msg_send![
359 self.native_window,
360 standardWindowButton: NSWindowButton::NSWindowZoomButton
361 ];
362
363 let mut close_button_frame: CGRect = msg_send![close_button, frame];
364 let mut min_button_frame: CGRect = msg_send![min_button, frame];
365 let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
366 let mut origin = point(
367 traffic_light_position.x,
368 titlebar_height
369 - traffic_light_position.y
370 - px(close_button_frame.size.height as f32),
371 );
372 let button_spacing =
373 px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
374
375 close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
376 let _: () = msg_send![close_button, setFrame: close_button_frame];
377 origin.x += button_spacing;
378
379 min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
380 let _: () = msg_send![min_button, setFrame: min_button_frame];
381 origin.x += button_spacing;
382
383 zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
384 let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
385 origin.x += button_spacing;
386 }
387 }
388 }
389
390 fn is_fullscreen(&self) -> bool {
391 unsafe {
392 let style_mask = self.native_window.styleMask();
393 style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
394 }
395 }
396
397 fn bounds(&self) -> WindowBounds {
398 unsafe {
399 if self.is_fullscreen() {
400 return WindowBounds::Fullscreen;
401 }
402
403 let frame = self.frame();
404 let screen_size = self.native_window.screen().visibleFrame().into();
405 if frame.size == screen_size {
406 WindowBounds::Maximized
407 } else {
408 WindowBounds::Fixed(frame)
409 }
410 }
411 }
412
413 fn frame(&self) -> Bounds<GlobalPixels> {
414 unsafe {
415 let frame = NSWindow::frame(self.native_window);
416 display_bounds_from_native(mem::transmute::<NSRect, CGRect>(frame))
417 }
418 }
419
420 fn content_size(&self) -> Size<Pixels> {
421 let NSSize { width, height, .. } =
422 unsafe { NSView::frame(self.native_window.contentView()) }.size;
423 size(px(width as f32), px(height as f32))
424 }
425
426 fn scale_factor(&self) -> f32 {
427 get_scale_factor(self.native_window)
428 }
429
430 fn titlebar_height(&self) -> Pixels {
431 unsafe {
432 let frame = NSWindow::frame(self.native_window);
433 let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
434 px((frame.size.height - content_layout_rect.size.height) as f32)
435 }
436 }
437
438 fn to_screen_ns_point(&self, point: Point<Pixels>) -> NSPoint {
439 unsafe {
440 let point = NSPoint::new(
441 point.x.into(),
442 (self.content_size().height - point.y).into(),
443 );
444 msg_send![self.native_window, convertPointToScreen: point]
445 }
446 }
447}
448
449unsafe impl Send for MacWindowState {}
450
451pub struct MacWindow(Arc<Mutex<MacWindowState>>);
452
453impl MacWindow {
454 pub fn open(
455 handle: AnyWindowHandle,
456 options: WindowOptions,
457 executor: ForegroundExecutor,
458 ) -> Self {
459 unsafe {
460 let pool = NSAutoreleasePool::new(nil);
461
462 let mut style_mask;
463 if let Some(titlebar) = options.titlebar.as_ref() {
464 style_mask = NSWindowStyleMask::NSClosableWindowMask
465 | NSWindowStyleMask::NSMiniaturizableWindowMask
466 | NSWindowStyleMask::NSResizableWindowMask
467 | NSWindowStyleMask::NSTitledWindowMask;
468
469 if titlebar.appears_transparent {
470 style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
471 }
472 } else {
473 style_mask = NSWindowStyleMask::NSTitledWindowMask
474 | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
475 }
476
477 let native_window: id = match options.kind {
478 WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
479 WindowKind::PopUp => {
480 style_mask |= NSWindowStyleMaskNonactivatingPanel;
481 msg_send![PANEL_CLASS, alloc]
482 }
483 };
484
485 let display = options
486 .display_id
487 .and_then(MacDisplay::find_by_id)
488 .unwrap_or_else(MacDisplay::primary);
489
490 let mut target_screen = nil;
491 let screens = NSScreen::screens(nil);
492 let count: u64 = cocoa::foundation::NSArray::count(screens);
493 for i in 0..count {
494 let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
495 let device_description = NSScreen::deviceDescription(screen);
496 let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
497 let screen_number = device_description.objectForKey_(screen_number_key);
498 let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
499 if screen_number as u32 == display.id().0 {
500 target_screen = screen;
501 break;
502 }
503 }
504
505 let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
506 NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.)),
507 style_mask,
508 NSBackingStoreBuffered,
509 NO,
510 target_screen,
511 );
512 assert!(!native_window.is_null());
513 let () = msg_send![
514 native_window,
515 registerForDraggedTypes:
516 NSArray::arrayWithObject(nil, NSFilenamesPboardType)
517 ];
518
519 let screen = native_window.screen();
520 match options.bounds {
521 WindowBounds::Fullscreen => {
522 native_window.toggleFullScreen_(nil);
523 }
524 WindowBounds::Maximized => {
525 native_window.setFrame_display_(screen.visibleFrame(), YES);
526 }
527 WindowBounds::Fixed(bounds) => {
528 let display_bounds = display.bounds();
529 let frame = if bounds.intersects(&display_bounds) {
530 display_bounds_to_native(bounds)
531 } else {
532 display_bounds_to_native(display_bounds)
533 };
534 native_window.setFrame_display_(mem::transmute::<CGRect, NSRect>(frame), YES);
535 }
536 }
537
538 let native_view: id = msg_send![VIEW_CLASS, alloc];
539 let native_view = NSView::init(native_view);
540
541 assert!(!native_view.is_null());
542
543 let window = Self(Arc::new(Mutex::new(MacWindowState {
544 handle,
545 executor,
546 native_window,
547 renderer: MetalRenderer::new(true),
548 kind: options.kind,
549 request_frame_callback: None,
550 event_callback: None,
551 activate_callback: None,
552 resize_callback: None,
553 fullscreen_callback: None,
554 moved_callback: None,
555 should_close_callback: None,
556 close_callback: None,
557 appearance_changed_callback: None,
558 input_handler: None,
559 pending_key_down: None,
560 last_key_equivalent: None,
561 synthetic_drag_counter: 0,
562 last_fresh_keydown: None,
563 traffic_light_position: options
564 .titlebar
565 .as_ref()
566 .and_then(|titlebar| titlebar.traffic_light_position),
567 previous_modifiers_changed_event: None,
568 ime_state: ImeState::None,
569 ime_text: None,
570 external_files_dragged: false,
571 })));
572
573 (*native_window).set_ivar(
574 WINDOW_STATE_IVAR,
575 Arc::into_raw(window.0.clone()) as *const c_void,
576 );
577 native_window.setDelegate_(native_window);
578 (*native_view).set_ivar(
579 WINDOW_STATE_IVAR,
580 Arc::into_raw(window.0.clone()) as *const c_void,
581 );
582
583 if let Some(title) = options
584 .titlebar
585 .as_ref()
586 .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
587 {
588 native_window.setTitle_(NSString::alloc(nil).init_str(title));
589 }
590
591 native_window.setMovable_(options.is_movable as BOOL);
592
593 if options
594 .titlebar
595 .map_or(true, |titlebar| titlebar.appears_transparent)
596 {
597 native_window.setTitlebarAppearsTransparent_(YES);
598 native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
599 }
600
601 native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
602 native_view.setWantsBestResolutionOpenGLSurface_(YES);
603
604 // From winit crate: On Mojave, views automatically become layer-backed shortly after
605 // being added to a native_window. Changing the layer-backedness of a view breaks the
606 // association between the view and its associated OpenGL context. To work around this,
607 // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
608 // itself and break the association with its context.
609 native_view.setWantsLayer(YES);
610 let _: () = msg_send![
611 native_view,
612 setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
613 ];
614
615 native_window.setContentView_(native_view.autorelease());
616 native_window.makeFirstResponder_(native_view);
617
618 if options.center {
619 native_window.center();
620 }
621
622 match options.kind {
623 WindowKind::Normal => {
624 native_window.setLevel_(NSNormalWindowLevel);
625 native_window.setAcceptsMouseMovedEvents_(YES);
626 }
627 WindowKind::PopUp => {
628 // Use a tracking area to allow receiving MouseMoved events even when
629 // the window or application aren't active, which is often the case
630 // e.g. for notification windows.
631 let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
632 let _: () = msg_send![
633 tracking_area,
634 initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
635 options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
636 owner: native_view
637 userInfo: nil
638 ];
639 let _: () =
640 msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
641
642 native_window.setLevel_(NSPopUpWindowLevel);
643 let _: () = msg_send![
644 native_window,
645 setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
646 ];
647 native_window.setCollectionBehavior_(
648 NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
649 NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
650 );
651 }
652 }
653 if options.focus {
654 native_window.makeKeyAndOrderFront_(nil);
655 } else if options.show {
656 native_window.orderFront_(nil);
657 }
658
659 window.0.lock().move_traffic_light();
660 pool.drain();
661
662 window
663 }
664 }
665
666 pub fn active_window() -> Option<AnyWindowHandle> {
667 unsafe {
668 let app = NSApplication::sharedApplication(nil);
669 let main_window: id = msg_send![app, mainWindow];
670 if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
671 let handle = get_window_state(&*main_window).lock().handle;
672 Some(handle)
673 } else {
674 None
675 }
676 }
677 }
678}
679
680impl Drop for MacWindow {
681 fn drop(&mut self) {
682 let this = self.0.lock();
683 let window = this.native_window;
684 this.executor
685 .spawn(async move {
686 unsafe {
687 window.close();
688 }
689 })
690 .detach();
691 }
692}
693
694impl PlatformWindow for MacWindow {
695 fn bounds(&self) -> WindowBounds {
696 self.0.as_ref().lock().bounds()
697 }
698
699 fn content_size(&self) -> Size<Pixels> {
700 self.0.as_ref().lock().content_size()
701 }
702
703 fn scale_factor(&self) -> f32 {
704 self.0.as_ref().lock().scale_factor()
705 }
706
707 fn titlebar_height(&self) -> Pixels {
708 self.0.as_ref().lock().titlebar_height()
709 }
710
711 fn appearance(&self) -> WindowAppearance {
712 unsafe {
713 let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
714 WindowAppearance::from_native(appearance)
715 }
716 }
717
718 fn display(&self) -> Rc<dyn PlatformDisplay> {
719 unsafe {
720 let screen = self.0.lock().native_window.screen();
721 let device_description: id = msg_send![screen, deviceDescription];
722 let screen_number: id = NSDictionary::valueForKey_(
723 device_description,
724 NSString::alloc(nil).init_str("NSScreenNumber"),
725 );
726
727 let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
728
729 Rc::new(MacDisplay(screen_number))
730 }
731 }
732
733 fn mouse_position(&self) -> Point<Pixels> {
734 let position = unsafe {
735 self.0
736 .lock()
737 .native_window
738 .mouseLocationOutsideOfEventStream()
739 };
740 convert_mouse_position(position, self.content_size().height)
741 }
742
743 fn modifiers(&self) -> Modifiers {
744 unsafe {
745 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
746
747 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
748 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
749 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
750 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
751 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
752
753 Modifiers {
754 control,
755 alt,
756 shift,
757 command,
758 function,
759 }
760 }
761 }
762
763 fn as_any_mut(&mut self) -> &mut dyn Any {
764 self
765 }
766
767 fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>) {
768 self.0.as_ref().lock().input_handler = Some(input_handler);
769 }
770
771 fn take_input_handler(&mut self) -> Option<Box<dyn PlatformInputHandler>> {
772 self.0.as_ref().lock().input_handler.take()
773 }
774
775 fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize> {
776 // macOs applies overrides to modal window buttons after they are added.
777 // Two most important for this logic are:
778 // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
779 // * Last button added to the modal via `addButtonWithTitle` stays focused
780 // * Focused buttons react on "space"/" " keypresses
781 // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
782 //
783 // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
784 // ```
785 // By default, the first button has a key equivalent of Return,
786 // any button with a title of “Cancel” has a key equivalent of Escape,
787 // and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it’s not the first button).
788 // ```
789 //
790 // To avoid situations when the last element added is "Cancel" and it gets the focus
791 // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
792 // last, so it gets focus and a Space shortcut.
793 // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
794 let latest_non_cancel_label = answers
795 .iter()
796 .enumerate()
797 .rev()
798 .find(|(_, &label)| label != "Cancel")
799 .filter(|&(label_index, _)| label_index > 0);
800
801 unsafe {
802 let alert: id = msg_send![class!(NSAlert), alloc];
803 let alert: id = msg_send![alert, init];
804 let alert_style = match level {
805 PromptLevel::Info => 1,
806 PromptLevel::Warning => 0,
807 PromptLevel::Critical => 2,
808 };
809 let _: () = msg_send![alert, setAlertStyle: alert_style];
810 let _: () = msg_send![alert, setMessageText: ns_string(msg)];
811
812 for (ix, answer) in answers
813 .iter()
814 .enumerate()
815 .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
816 {
817 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
818 let _: () = msg_send![button, setTag: ix as NSInteger];
819 }
820 if let Some((ix, answer)) = latest_non_cancel_label {
821 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
822 let _: () = msg_send![button, setTag: ix as NSInteger];
823 }
824
825 let (done_tx, done_rx) = oneshot::channel();
826 let done_tx = Cell::new(Some(done_tx));
827 let block = ConcreteBlock::new(move |answer: NSInteger| {
828 if let Some(done_tx) = done_tx.take() {
829 let _ = done_tx.send(answer.try_into().unwrap());
830 }
831 });
832 let block = block.copy();
833 let native_window = self.0.lock().native_window;
834 let executor = self.0.lock().executor.clone();
835 executor
836 .spawn(async move {
837 let _: () = msg_send![
838 alert,
839 beginSheetModalForWindow: native_window
840 completionHandler: block
841 ];
842 })
843 .detach();
844
845 done_rx
846 }
847 }
848
849 fn activate(&self) {
850 let window = self.0.lock().native_window;
851 let executor = self.0.lock().executor.clone();
852 executor
853 .spawn(async move {
854 unsafe {
855 let _: () = msg_send![window, makeKeyAndOrderFront: nil];
856 }
857 })
858 .detach();
859 }
860
861 fn set_title(&mut self, title: &str) {
862 unsafe {
863 let app = NSApplication::sharedApplication(nil);
864 let window = self.0.lock().native_window;
865 let title = ns_string(title);
866 let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
867 let _: () = msg_send![window, setTitle: title];
868 self.0.lock().move_traffic_light();
869 }
870 }
871
872 fn set_edited(&mut self, edited: bool) {
873 unsafe {
874 let window = self.0.lock().native_window;
875 msg_send![window, setDocumentEdited: edited as BOOL]
876 }
877
878 // Changing the document edited state resets the traffic light position,
879 // so we have to move it again.
880 self.0.lock().move_traffic_light();
881 }
882
883 fn show_character_palette(&self) {
884 let this = self.0.lock();
885 let window = this.native_window;
886 this.executor
887 .spawn(async move {
888 unsafe {
889 let app = NSApplication::sharedApplication(nil);
890 let _: () = msg_send![app, orderFrontCharacterPalette: window];
891 }
892 })
893 .detach();
894 }
895
896 fn minimize(&self) {
897 let window = self.0.lock().native_window;
898 unsafe {
899 window.miniaturize_(nil);
900 }
901 }
902
903 fn zoom(&self) {
904 let this = self.0.lock();
905 let window = this.native_window;
906 this.executor
907 .spawn(async move {
908 unsafe {
909 window.zoom_(nil);
910 }
911 })
912 .detach();
913 }
914
915 fn toggle_full_screen(&self) {
916 let this = self.0.lock();
917 let window = this.native_window;
918 this.executor
919 .spawn(async move {
920 unsafe {
921 window.toggleFullScreen_(nil);
922 }
923 })
924 .detach();
925 }
926
927 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
928 self.0.as_ref().lock().request_frame_callback = Some(callback);
929 }
930
931 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
932 self.0.as_ref().lock().event_callback = Some(callback);
933 }
934
935 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
936 self.0.as_ref().lock().activate_callback = Some(callback);
937 }
938
939 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
940 self.0.as_ref().lock().resize_callback = Some(callback);
941 }
942
943 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
944 self.0.as_ref().lock().fullscreen_callback = Some(callback);
945 }
946
947 fn on_moved(&self, callback: Box<dyn FnMut()>) {
948 self.0.as_ref().lock().moved_callback = Some(callback);
949 }
950
951 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
952 self.0.as_ref().lock().should_close_callback = Some(callback);
953 }
954
955 fn on_close(&self, callback: Box<dyn FnOnce()>) {
956 self.0.as_ref().lock().close_callback = Some(callback);
957 }
958
959 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
960 self.0.lock().appearance_changed_callback = Some(callback);
961 }
962
963 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
964 let self_borrow = self.0.lock();
965 let self_handle = self_borrow.handle;
966
967 unsafe {
968 let app = NSApplication::sharedApplication(nil);
969
970 // Convert back to screen coordinates
971 let screen_point = self_borrow.to_screen_ns_point(position);
972
973 let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
974 let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
975
976 let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
977 let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
978 if is_panel == YES || is_window == YES {
979 let topmost_window = get_window_state(&*top_most_window).lock().handle;
980 topmost_window == self_handle
981 } else {
982 // Someone else's window is on top
983 false
984 }
985 }
986 }
987
988 fn invalidate(&self) {
989 let this = self.0.lock();
990 unsafe {
991 let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
992 }
993 }
994
995 fn draw(&self, scene: &crate::Scene) {
996 let mut this = self.0.lock();
997 this.renderer.draw(scene);
998 }
999
1000 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1001 self.0.lock().renderer.sprite_atlas().clone()
1002 }
1003}
1004
1005fn get_scale_factor(native_window: id) -> f32 {
1006 unsafe {
1007 let screen: id = msg_send![native_window, screen];
1008 NSScreen::backingScaleFactor(screen) as f32
1009 }
1010}
1011
1012unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1013 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1014 let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1015 let rc2 = rc1.clone();
1016 mem::forget(rc1);
1017 rc2
1018}
1019
1020unsafe fn drop_window_state(object: &Object) {
1021 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1022 Rc::from_raw(raw as *mut RefCell<MacWindowState>);
1023}
1024
1025extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1026 YES
1027}
1028
1029extern "C" fn dealloc_window(this: &Object, _: Sel) {
1030 unsafe {
1031 drop_window_state(this);
1032 let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1033 }
1034}
1035
1036extern "C" fn dealloc_view(this: &Object, _: Sel) {
1037 unsafe {
1038 drop_window_state(this);
1039 let _: () = msg_send![super(this, class!(NSView)), dealloc];
1040 }
1041}
1042
1043extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1044 handle_key_event(this, native_event, true)
1045}
1046
1047extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1048 handle_key_event(this, native_event, false);
1049}
1050
1051extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1052 let window_state = unsafe { get_window_state(this) };
1053 let mut lock = window_state.as_ref().lock();
1054
1055 let window_height = lock.content_size().height;
1056 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1057
1058 if let Some(PlatformInput::KeyDown(event)) = event {
1059 // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1060 // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1061 // makes no distinction between these two types of events, so we need to ignore
1062 // the "key down" event if we've already just processed its "key equivalent" version.
1063 if key_equivalent {
1064 lock.last_key_equivalent = Some(event.clone());
1065 } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1066 return NO;
1067 }
1068
1069 let keydown = event.keystroke.clone();
1070 let fn_modifier = keydown.modifiers.function;
1071 // Ignore events from held-down keys after some of the initially-pressed keys
1072 // were released.
1073 if event.is_held {
1074 if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1075 return YES;
1076 }
1077 } else {
1078 lock.last_fresh_keydown = Some(keydown);
1079 }
1080 lock.pending_key_down = Some((event, None));
1081 drop(lock);
1082
1083 // Send the event to the input context for IME handling, unless the `fn` modifier is
1084 // being pressed.
1085 if !fn_modifier {
1086 unsafe {
1087 let input_context: id = msg_send![this, inputContext];
1088 let _: BOOL = msg_send![input_context, handleEvent: native_event];
1089 }
1090 }
1091
1092 let mut handled = false;
1093 let mut lock = window_state.lock();
1094 let ime_text = lock.ime_text.clone();
1095 if let Some((event, insert_text)) = lock.pending_key_down.take() {
1096 let is_held = event.is_held;
1097 if let Some(mut callback) = lock.event_callback.take() {
1098 drop(lock);
1099
1100 let is_composing =
1101 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1102 .flatten()
1103 .is_some();
1104 if !is_composing {
1105 handled = callback(PlatformInput::KeyDown(event));
1106 }
1107
1108 if !handled {
1109 if let Some(insert) = insert_text {
1110 handled = true;
1111 with_input_handler(this, |input_handler| {
1112 input_handler
1113 .replace_text_in_range(insert.replacement_range, &insert.text)
1114 });
1115 } else if !is_composing && is_held {
1116 if let Some(last_insert_text) = ime_text {
1117 //MacOS IME is a bit funky, and even when you've told it there's nothing to
1118 //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1119 //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1120 with_input_handler(this, |input_handler| {
1121 if input_handler.selected_text_range().is_none() {
1122 handled = true;
1123 input_handler.replace_text_in_range(None, &last_insert_text)
1124 }
1125 });
1126 }
1127 }
1128 }
1129
1130 window_state.lock().event_callback = Some(callback);
1131 }
1132 } else {
1133 handled = true;
1134 }
1135
1136 handled as BOOL
1137 } else {
1138 NO
1139 }
1140}
1141
1142extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1143 let window_state = unsafe { get_window_state(this) };
1144 let weak_window_state = Arc::downgrade(&window_state);
1145 let mut lock = window_state.as_ref().lock();
1146 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1147
1148 let window_height = lock.content_size().height;
1149 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1150
1151 if let Some(mut event) = event {
1152 match &mut event {
1153 PlatformInput::MouseDown(
1154 event @ MouseDownEvent {
1155 button: MouseButton::Left,
1156 modifiers: Modifiers { control: true, .. },
1157 ..
1158 },
1159 ) => {
1160 // On mac, a ctrl-left click should be handled as a right click.
1161 *event = MouseDownEvent {
1162 button: MouseButton::Right,
1163 modifiers: Modifiers {
1164 control: false,
1165 ..event.modifiers
1166 },
1167 click_count: 1,
1168 ..*event
1169 };
1170 }
1171
1172 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1173 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1174 // user is still holding ctrl when releasing the left mouse button
1175 PlatformInput::MouseUp(
1176 event @ MouseUpEvent {
1177 button: MouseButton::Left,
1178 modifiers: Modifiers { control: true, .. },
1179 ..
1180 },
1181 ) => {
1182 *event = MouseUpEvent {
1183 button: MouseButton::Right,
1184 modifiers: Modifiers {
1185 control: false,
1186 ..event.modifiers
1187 },
1188 click_count: 1,
1189 ..*event
1190 };
1191 }
1192
1193 _ => {}
1194 };
1195
1196 match &event {
1197 PlatformInput::MouseMove(
1198 event @ MouseMoveEvent {
1199 pressed_button: Some(_),
1200 ..
1201 },
1202 ) => {
1203 // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1204 // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1205 // with these ones.
1206 if !lock.external_files_dragged {
1207 lock.synthetic_drag_counter += 1;
1208 let executor = lock.executor.clone();
1209 executor
1210 .spawn(synthetic_drag(
1211 weak_window_state,
1212 lock.synthetic_drag_counter,
1213 event.clone(),
1214 ))
1215 .detach();
1216 }
1217 }
1218
1219 PlatformInput::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1220
1221 PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1222 lock.synthetic_drag_counter += 1;
1223 }
1224
1225 PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1226 // Only raise modifiers changed event when they have actually changed
1227 if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1228 modifiers: prev_modifiers,
1229 })) = &lock.previous_modifiers_changed_event
1230 {
1231 if prev_modifiers == modifiers {
1232 return;
1233 }
1234 }
1235
1236 lock.previous_modifiers_changed_event = Some(event.clone());
1237 }
1238
1239 _ => {}
1240 }
1241
1242 if let Some(mut callback) = lock.event_callback.take() {
1243 drop(lock);
1244 callback(event);
1245 window_state.lock().event_callback = Some(callback);
1246 }
1247 }
1248}
1249
1250// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1251// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1252extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1253 let window_state = unsafe { get_window_state(this) };
1254 let mut lock = window_state.as_ref().lock();
1255
1256 let keystroke = Keystroke {
1257 modifiers: Default::default(),
1258 key: ".".into(),
1259 ime_key: None,
1260 };
1261 let event = PlatformInput::KeyDown(KeyDownEvent {
1262 keystroke: keystroke.clone(),
1263 is_held: false,
1264 });
1265
1266 lock.last_fresh_keydown = Some(keystroke);
1267 if let Some(mut callback) = lock.event_callback.take() {
1268 drop(lock);
1269 callback(event);
1270 window_state.lock().event_callback = Some(callback);
1271 }
1272}
1273
1274extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1275 let window_state = unsafe { get_window_state(this) };
1276 window_state.as_ref().lock().move_traffic_light();
1277}
1278
1279extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1280 window_fullscreen_changed(this, true);
1281}
1282
1283extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1284 window_fullscreen_changed(this, false);
1285}
1286
1287fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1288 let window_state = unsafe { get_window_state(this) };
1289 let mut lock = window_state.as_ref().lock();
1290 if let Some(mut callback) = lock.fullscreen_callback.take() {
1291 drop(lock);
1292 callback(is_fullscreen);
1293 window_state.lock().fullscreen_callback = Some(callback);
1294 }
1295}
1296
1297extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1298 let window_state = unsafe { get_window_state(this) };
1299 let mut lock = window_state.as_ref().lock();
1300 if let Some(mut callback) = lock.moved_callback.take() {
1301 drop(lock);
1302 callback();
1303 window_state.lock().moved_callback = Some(callback);
1304 }
1305}
1306
1307extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1308 let window_state = unsafe { get_window_state(this) };
1309 let lock = window_state.lock();
1310 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1311
1312 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1313 // `windowDidBecomeKey` message to the previous key window even though that window
1314 // isn't actually key. This causes a bug if the application is later activated while
1315 // the pop-up is still open, making it impossible to activate the previous key window
1316 // even if the pop-up gets closed. The only way to activate it again is to de-activate
1317 // the app and re-activate it, which is a pretty bad UX.
1318 // The following code detects the spurious event and invokes `resignKeyWindow`:
1319 // in theory, we're not supposed to invoke this method manually but it balances out
1320 // the spurious `becomeKeyWindow` event and helps us work around that bug.
1321 if selector == sel!(windowDidBecomeKey:) && !is_active {
1322 unsafe {
1323 let _: () = msg_send![lock.native_window, resignKeyWindow];
1324 return;
1325 }
1326 }
1327
1328 let executor = lock.executor.clone();
1329 drop(lock);
1330 executor
1331 .spawn(async move {
1332 let mut lock = window_state.as_ref().lock();
1333 if let Some(mut callback) = lock.activate_callback.take() {
1334 drop(lock);
1335 callback(is_active);
1336 window_state.lock().activate_callback = Some(callback);
1337 };
1338 })
1339 .detach();
1340}
1341
1342extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1343 let window_state = unsafe { get_window_state(this) };
1344 let mut lock = window_state.as_ref().lock();
1345 if let Some(mut callback) = lock.should_close_callback.take() {
1346 drop(lock);
1347 let should_close = callback();
1348 window_state.lock().should_close_callback = Some(callback);
1349 should_close as BOOL
1350 } else {
1351 YES
1352 }
1353}
1354
1355extern "C" fn close_window(this: &Object, _: Sel) {
1356 unsafe {
1357 let close_callback = {
1358 let window_state = get_window_state(this);
1359 window_state
1360 .as_ref()
1361 .try_lock()
1362 .and_then(|mut window_state| window_state.close_callback.take())
1363 };
1364
1365 if let Some(callback) = close_callback {
1366 callback();
1367 }
1368
1369 let _: () = msg_send![super(this, class!(NSWindow)), close];
1370 }
1371}
1372
1373extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1374 let window_state = unsafe { get_window_state(this) };
1375 let window_state = window_state.as_ref().lock();
1376 window_state.renderer.layer().as_ptr() as id
1377}
1378
1379extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1380 let window_state = unsafe { get_window_state(this) };
1381 let mut lock = window_state.as_ref().lock();
1382
1383 unsafe {
1384 let scale_factor = lock.scale_factor() as f64;
1385 let size = lock.content_size();
1386 let drawable_size: NSSize = NSSize {
1387 width: f64::from(size.width) * scale_factor,
1388 height: f64::from(size.height) * scale_factor,
1389 };
1390
1391 let _: () = msg_send![
1392 lock.renderer.layer(),
1393 setContentsScale: scale_factor
1394 ];
1395 let _: () = msg_send![
1396 lock.renderer.layer(),
1397 setDrawableSize: drawable_size
1398 ];
1399 }
1400
1401 if let Some(mut callback) = lock.resize_callback.take() {
1402 let content_size = lock.content_size();
1403 let scale_factor = lock.scale_factor();
1404 drop(lock);
1405 callback(content_size, scale_factor);
1406 window_state.as_ref().lock().resize_callback = Some(callback);
1407 };
1408}
1409
1410extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1411 let window_state = unsafe { get_window_state(this) };
1412 let lock = window_state.as_ref().lock();
1413
1414 if lock.content_size() == size.into() {
1415 return;
1416 }
1417
1418 unsafe {
1419 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1420 }
1421
1422 let scale_factor = lock.scale_factor() as f64;
1423 let drawable_size: NSSize = NSSize {
1424 width: size.width * scale_factor,
1425 height: size.height * scale_factor,
1426 };
1427
1428 unsafe {
1429 let _: () = msg_send![
1430 lock.renderer.layer(),
1431 setDrawableSize: drawable_size
1432 ];
1433 }
1434
1435 drop(lock);
1436 let mut lock = window_state.lock();
1437 if let Some(mut callback) = lock.resize_callback.take() {
1438 let content_size = lock.content_size();
1439 let scale_factor = lock.scale_factor();
1440 drop(lock);
1441 callback(content_size, scale_factor);
1442 window_state.lock().resize_callback = Some(callback);
1443 };
1444}
1445
1446extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1447 let window_state = unsafe { get_window_state(this) };
1448 let mut lock = window_state.lock();
1449 if let Some(mut callback) = lock.request_frame_callback.take() {
1450 drop(lock);
1451 callback();
1452 window_state.lock().request_frame_callback = Some(callback);
1453 }
1454}
1455
1456extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1457 unsafe { msg_send![class!(NSArray), array] }
1458}
1459
1460extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1461 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1462 .flatten()
1463 .is_some() as BOOL
1464}
1465
1466extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1467 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1468 .flatten()
1469 .map_or(NSRange::invalid(), |range| range.into())
1470}
1471
1472extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1473 with_input_handler(this, |input_handler| input_handler.selected_text_range())
1474 .flatten()
1475 .map_or(NSRange::invalid(), |range| range.into())
1476}
1477
1478extern "C" fn first_rect_for_character_range(
1479 this: &Object,
1480 _: Sel,
1481 range: NSRange,
1482 _: id,
1483) -> NSRect {
1484 let frame = unsafe {
1485 let window = get_window_state(this).lock().native_window;
1486 NSView::frame(window)
1487 };
1488 with_input_handler(this, |input_handler| {
1489 input_handler.bounds_for_range(range.to_range()?)
1490 })
1491 .flatten()
1492 .map_or(
1493 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1494 |bounds| {
1495 NSRect::new(
1496 NSPoint::new(
1497 frame.origin.x + bounds.origin.x.0 as f64,
1498 frame.origin.y + frame.size.height
1499 - bounds.origin.y.0 as f64
1500 - bounds.size.height.0 as f64,
1501 ),
1502 NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1503 )
1504 },
1505 )
1506}
1507
1508extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1509 unsafe {
1510 let window_state = get_window_state(this);
1511 let mut lock = window_state.lock();
1512 let pending_key_down = lock.pending_key_down.take();
1513 drop(lock);
1514
1515 let is_attributed_string: BOOL =
1516 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1517 let text: id = if is_attributed_string == YES {
1518 msg_send![text, string]
1519 } else {
1520 text
1521 };
1522 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1523 .to_str()
1524 .unwrap();
1525 let replacement_range = replacement_range.to_range();
1526
1527 window_state.lock().ime_text = Some(text.to_string());
1528 window_state.lock().ime_state = ImeState::Acted;
1529
1530 let is_composing =
1531 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1532 .flatten()
1533 .is_some();
1534
1535 if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1536 with_input_handler(this, |input_handler| {
1537 input_handler.replace_text_in_range(replacement_range, text)
1538 });
1539 } else {
1540 let mut pending_key_down = pending_key_down.unwrap();
1541 pending_key_down.1 = Some(InsertText {
1542 replacement_range,
1543 text: text.to_string(),
1544 });
1545 if text.to_string().to_ascii_lowercase() != pending_key_down.0.keystroke.key {
1546 pending_key_down.0.keystroke.ime_key = Some(text.to_string());
1547 }
1548 window_state.lock().pending_key_down = Some(pending_key_down);
1549 }
1550 }
1551}
1552
1553extern "C" fn set_marked_text(
1554 this: &Object,
1555 _: Sel,
1556 text: id,
1557 selected_range: NSRange,
1558 replacement_range: NSRange,
1559) {
1560 unsafe {
1561 let window_state = get_window_state(this);
1562 window_state.lock().pending_key_down.take();
1563
1564 let is_attributed_string: BOOL =
1565 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1566 let text: id = if is_attributed_string == YES {
1567 msg_send![text, string]
1568 } else {
1569 text
1570 };
1571 let selected_range = selected_range.to_range();
1572 let replacement_range = replacement_range.to_range();
1573 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1574 .to_str()
1575 .unwrap();
1576
1577 window_state.lock().ime_state = ImeState::Acted;
1578 window_state.lock().ime_text = Some(text.to_string());
1579
1580 with_input_handler(this, |input_handler| {
1581 input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1582 });
1583 }
1584}
1585
1586extern "C" fn unmark_text(this: &Object, _: Sel) {
1587 unsafe {
1588 let state = get_window_state(this);
1589 let mut borrow = state.lock();
1590 borrow.ime_state = ImeState::Acted;
1591 borrow.ime_text.take();
1592 }
1593
1594 with_input_handler(this, |input_handler| input_handler.unmark_text());
1595}
1596
1597extern "C" fn attributed_substring_for_proposed_range(
1598 this: &Object,
1599 _: Sel,
1600 range: NSRange,
1601 _actual_range: *mut c_void,
1602) -> id {
1603 with_input_handler(this, |input_handler| {
1604 let range = range.to_range()?;
1605 if range.is_empty() {
1606 return None;
1607 }
1608
1609 let selected_text = input_handler.text_for_range(range)?;
1610 unsafe {
1611 let string: id = msg_send![class!(NSAttributedString), alloc];
1612 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1613 Some(string)
1614 }
1615 })
1616 .flatten()
1617 .unwrap_or(nil)
1618}
1619
1620extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1621 unsafe {
1622 let state = get_window_state(this);
1623 let mut borrow = state.lock();
1624 borrow.ime_state = ImeState::Continue;
1625 borrow.ime_text.take();
1626 }
1627}
1628
1629extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1630 unsafe {
1631 let state = get_window_state(this);
1632 let mut lock = state.as_ref().lock();
1633 if let Some(mut callback) = lock.appearance_changed_callback.take() {
1634 drop(lock);
1635 callback();
1636 state.lock().appearance_changed_callback = Some(callback);
1637 }
1638 }
1639}
1640
1641extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1642 unsafe {
1643 let state = get_window_state(this);
1644 let lock = state.as_ref().lock();
1645 if lock.kind == WindowKind::PopUp {
1646 YES
1647 } else {
1648 NO
1649 }
1650 }
1651}
1652
1653extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1654 let window_state = unsafe { get_window_state(this) };
1655 if send_new_event(&window_state, {
1656 let position = drag_event_position(&window_state, dragging_info);
1657 let paths = external_paths_from_event(dragging_info);
1658 PlatformInput::FileDrop(FileDropEvent::Entered { position, paths })
1659 }) {
1660 window_state.lock().external_files_dragged = true;
1661 NSDragOperationCopy
1662 } else {
1663 NSDragOperationNone
1664 }
1665}
1666
1667extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1668 let window_state = unsafe { get_window_state(this) };
1669 let position = drag_event_position(&window_state, dragging_info);
1670 if send_new_event(
1671 &window_state,
1672 PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1673 ) {
1674 NSDragOperationCopy
1675 } else {
1676 NSDragOperationNone
1677 }
1678}
1679
1680extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1681 let window_state = unsafe { get_window_state(this) };
1682 send_new_event(
1683 &window_state,
1684 PlatformInput::FileDrop(FileDropEvent::Exited),
1685 );
1686 window_state.lock().external_files_dragged = false;
1687}
1688
1689extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1690 let window_state = unsafe { get_window_state(this) };
1691 let position = drag_event_position(&window_state, dragging_info);
1692 if send_new_event(
1693 &window_state,
1694 PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1695 ) {
1696 YES
1697 } else {
1698 NO
1699 }
1700}
1701
1702fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1703 let mut paths = SmallVec::new();
1704 let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1705 let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1706 for file in unsafe { filenames.iter() } {
1707 let path = unsafe {
1708 let f = NSString::UTF8String(file);
1709 CStr::from_ptr(f).to_string_lossy().into_owned()
1710 };
1711 paths.push(PathBuf::from(path))
1712 }
1713 ExternalPaths(paths)
1714}
1715
1716extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1717 let window_state = unsafe { get_window_state(this) };
1718 send_new_event(
1719 &window_state,
1720 PlatformInput::FileDrop(FileDropEvent::Exited),
1721 );
1722}
1723
1724async fn synthetic_drag(
1725 window_state: Weak<Mutex<MacWindowState>>,
1726 drag_id: usize,
1727 event: MouseMoveEvent,
1728) {
1729 loop {
1730 Timer::after(Duration::from_millis(16)).await;
1731 if let Some(window_state) = window_state.upgrade() {
1732 let mut lock = window_state.lock();
1733 if lock.synthetic_drag_counter == drag_id {
1734 if let Some(mut callback) = lock.event_callback.take() {
1735 drop(lock);
1736 callback(PlatformInput::MouseMove(event.clone()));
1737 window_state.lock().event_callback = Some(callback);
1738 }
1739 } else {
1740 break;
1741 }
1742 }
1743 }
1744}
1745
1746fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1747 let window_state = window_state_lock.lock().event_callback.take();
1748 if let Some(mut callback) = window_state {
1749 callback(e);
1750 window_state_lock.lock().event_callback = Some(callback);
1751 true
1752 } else {
1753 false
1754 }
1755}
1756
1757fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1758 let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1759 convert_mouse_position(drag_location, window_state.lock().content_size().height)
1760}
1761
1762fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1763where
1764 F: FnOnce(&mut dyn PlatformInputHandler) -> R,
1765{
1766 let window_state = unsafe { get_window_state(window) };
1767 let mut lock = window_state.as_ref().lock();
1768 if let Some(mut input_handler) = lock.input_handler.take() {
1769 drop(lock);
1770 let result = f(input_handler.as_mut());
1771 window_state.lock().input_handler = Some(input_handler);
1772 Some(result)
1773 } else {
1774 None
1775 }
1776}