1use super::{global_bounds_from_ns_rect, ns_string, MacDisplay, MetalRenderer, NSRange};
2use crate::{
3 global_bounds_to_ns_rect, 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 let frame = unsafe { NSWindow::frame(self.native_window) };
415 global_bounds_from_ns_rect(frame)
416 }
417
418 fn content_size(&self) -> Size<Pixels> {
419 let NSSize { width, height, .. } =
420 unsafe { NSView::frame(self.native_window.contentView()) }.size;
421 size(px(width as f32), px(height as f32))
422 }
423
424 fn scale_factor(&self) -> f32 {
425 get_scale_factor(self.native_window)
426 }
427
428 fn titlebar_height(&self) -> Pixels {
429 unsafe {
430 let frame = NSWindow::frame(self.native_window);
431 let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
432 px((frame.size.height - content_layout_rect.size.height) as f32)
433 }
434 }
435
436 fn to_screen_ns_point(&self, point: Point<Pixels>) -> NSPoint {
437 unsafe {
438 let point = NSPoint::new(
439 point.x.into(),
440 (self.content_size().height - point.y).into(),
441 );
442 msg_send![self.native_window, convertPointToScreen: point]
443 }
444 }
445}
446
447unsafe impl Send for MacWindowState {}
448
449pub struct MacWindow(Arc<Mutex<MacWindowState>>);
450
451impl MacWindow {
452 pub fn open(
453 handle: AnyWindowHandle,
454 options: WindowOptions,
455 executor: ForegroundExecutor,
456 ) -> Self {
457 unsafe {
458 let pool = NSAutoreleasePool::new(nil);
459
460 let mut style_mask;
461 if let Some(titlebar) = options.titlebar.as_ref() {
462 style_mask = NSWindowStyleMask::NSClosableWindowMask
463 | NSWindowStyleMask::NSMiniaturizableWindowMask
464 | NSWindowStyleMask::NSResizableWindowMask
465 | NSWindowStyleMask::NSTitledWindowMask;
466
467 if titlebar.appears_transparent {
468 style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
469 }
470 } else {
471 style_mask = NSWindowStyleMask::NSTitledWindowMask
472 | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
473 }
474
475 let native_window: id = match options.kind {
476 WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
477 WindowKind::PopUp => {
478 style_mask |= NSWindowStyleMaskNonactivatingPanel;
479 msg_send![PANEL_CLASS, alloc]
480 }
481 };
482
483 let display = options
484 .display_id
485 .and_then(MacDisplay::find_by_id)
486 .unwrap_or_else(MacDisplay::primary);
487
488 let mut target_screen = nil;
489 let screens = NSScreen::screens(nil);
490 let count: u64 = cocoa::foundation::NSArray::count(screens);
491 for i in 0..count {
492 let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
493 let device_description = NSScreen::deviceDescription(screen);
494 let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
495 let screen_number = device_description.objectForKey_(screen_number_key);
496 let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
497 if screen_number as u32 == display.id().0 {
498 target_screen = screen;
499 break;
500 }
501 }
502
503 let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
504 NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.)),
505 style_mask,
506 NSBackingStoreBuffered,
507 NO,
508 target_screen,
509 );
510 assert!(!native_window.is_null());
511 let () = msg_send![
512 native_window,
513 registerForDraggedTypes:
514 NSArray::arrayWithObject(nil, NSFilenamesPboardType)
515 ];
516
517 let screen = native_window.screen();
518 match options.bounds {
519 WindowBounds::Fullscreen => {
520 native_window.toggleFullScreen_(nil);
521 }
522 WindowBounds::Maximized => {
523 native_window.setFrame_display_(screen.visibleFrame(), YES);
524 }
525 WindowBounds::Fixed(bounds) => {
526 let display_bounds = display.bounds();
527 let frame = if bounds.intersects(&display_bounds) {
528 global_bounds_to_ns_rect(bounds)
529 } else {
530 global_bounds_to_ns_rect(display_bounds)
531 };
532 native_window.setFrame_display_(frame, YES);
533 }
534 }
535
536 let native_view: id = msg_send![VIEW_CLASS, alloc];
537 let native_view = NSView::init(native_view);
538
539 assert!(!native_view.is_null());
540
541 let window = Self(Arc::new(Mutex::new(MacWindowState {
542 handle,
543 executor,
544 native_window,
545 renderer: MetalRenderer::new(true),
546 kind: options.kind,
547 request_frame_callback: None,
548 event_callback: None,
549 activate_callback: None,
550 resize_callback: None,
551 fullscreen_callback: None,
552 moved_callback: None,
553 should_close_callback: None,
554 close_callback: None,
555 appearance_changed_callback: None,
556 input_handler: None,
557 pending_key_down: None,
558 last_key_equivalent: None,
559 synthetic_drag_counter: 0,
560 last_fresh_keydown: None,
561 traffic_light_position: options
562 .titlebar
563 .as_ref()
564 .and_then(|titlebar| titlebar.traffic_light_position),
565 previous_modifiers_changed_event: None,
566 ime_state: ImeState::None,
567 ime_text: None,
568 external_files_dragged: false,
569 })));
570
571 (*native_window).set_ivar(
572 WINDOW_STATE_IVAR,
573 Arc::into_raw(window.0.clone()) as *const c_void,
574 );
575 native_window.setDelegate_(native_window);
576 (*native_view).set_ivar(
577 WINDOW_STATE_IVAR,
578 Arc::into_raw(window.0.clone()) as *const c_void,
579 );
580
581 if let Some(title) = options
582 .titlebar
583 .as_ref()
584 .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
585 {
586 native_window.setTitle_(NSString::alloc(nil).init_str(title));
587 }
588
589 native_window.setMovable_(options.is_movable as BOOL);
590
591 if options
592 .titlebar
593 .map_or(true, |titlebar| titlebar.appears_transparent)
594 {
595 native_window.setTitlebarAppearsTransparent_(YES);
596 native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
597 }
598
599 native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
600 native_view.setWantsBestResolutionOpenGLSurface_(YES);
601
602 // From winit crate: On Mojave, views automatically become layer-backed shortly after
603 // being added to a native_window. Changing the layer-backedness of a view breaks the
604 // association between the view and its associated OpenGL context. To work around this,
605 // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
606 // itself and break the association with its context.
607 native_view.setWantsLayer(YES);
608 let _: () = msg_send![
609 native_view,
610 setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
611 ];
612
613 native_window.setContentView_(native_view.autorelease());
614 native_window.makeFirstResponder_(native_view);
615
616 if options.center {
617 native_window.center();
618 }
619
620 match options.kind {
621 WindowKind::Normal => {
622 native_window.setLevel_(NSNormalWindowLevel);
623 native_window.setAcceptsMouseMovedEvents_(YES);
624 }
625 WindowKind::PopUp => {
626 // Use a tracking area to allow receiving MouseMoved events even when
627 // the window or application aren't active, which is often the case
628 // e.g. for notification windows.
629 let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
630 let _: () = msg_send![
631 tracking_area,
632 initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
633 options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
634 owner: native_view
635 userInfo: nil
636 ];
637 let _: () =
638 msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
639
640 native_window.setLevel_(NSPopUpWindowLevel);
641 let _: () = msg_send![
642 native_window,
643 setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
644 ];
645 native_window.setCollectionBehavior_(
646 NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
647 NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
648 );
649 }
650 }
651 if options.focus {
652 native_window.makeKeyAndOrderFront_(nil);
653 } else if options.show {
654 native_window.orderFront_(nil);
655 }
656
657 window.0.lock().move_traffic_light();
658 pool.drain();
659
660 window
661 }
662 }
663
664 pub fn active_window() -> Option<AnyWindowHandle> {
665 unsafe {
666 let app = NSApplication::sharedApplication(nil);
667 let main_window: id = msg_send![app, mainWindow];
668 if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
669 let handle = get_window_state(&*main_window).lock().handle;
670 Some(handle)
671 } else {
672 None
673 }
674 }
675 }
676}
677
678impl Drop for MacWindow {
679 fn drop(&mut self) {
680 let this = self.0.lock();
681 let window = this.native_window;
682 this.executor
683 .spawn(async move {
684 unsafe {
685 window.close();
686 }
687 })
688 .detach();
689 }
690}
691
692impl PlatformWindow for MacWindow {
693 fn bounds(&self) -> WindowBounds {
694 self.0.as_ref().lock().bounds()
695 }
696
697 fn content_size(&self) -> Size<Pixels> {
698 self.0.as_ref().lock().content_size()
699 }
700
701 fn scale_factor(&self) -> f32 {
702 self.0.as_ref().lock().scale_factor()
703 }
704
705 fn titlebar_height(&self) -> Pixels {
706 self.0.as_ref().lock().titlebar_height()
707 }
708
709 fn appearance(&self) -> WindowAppearance {
710 unsafe {
711 let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
712 WindowAppearance::from_native(appearance)
713 }
714 }
715
716 fn display(&self) -> Rc<dyn PlatformDisplay> {
717 unsafe {
718 let screen = self.0.lock().native_window.screen();
719 let device_description: id = msg_send![screen, deviceDescription];
720 let screen_number: id = NSDictionary::valueForKey_(
721 device_description,
722 NSString::alloc(nil).init_str("NSScreenNumber"),
723 );
724
725 let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
726
727 Rc::new(MacDisplay(screen_number))
728 }
729 }
730
731 fn mouse_position(&self) -> Point<Pixels> {
732 let position = unsafe {
733 self.0
734 .lock()
735 .native_window
736 .mouseLocationOutsideOfEventStream()
737 };
738 convert_mouse_position(position, self.content_size().height)
739 }
740
741 fn modifiers(&self) -> Modifiers {
742 unsafe {
743 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
744
745 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
746 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
747 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
748 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
749 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
750
751 Modifiers {
752 control,
753 alt,
754 shift,
755 command,
756 function,
757 }
758 }
759 }
760
761 fn as_any_mut(&mut self) -> &mut dyn Any {
762 self
763 }
764
765 fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>) {
766 self.0.as_ref().lock().input_handler = Some(input_handler);
767 }
768
769 fn take_input_handler(&mut self) -> Option<Box<dyn PlatformInputHandler>> {
770 self.0.as_ref().lock().input_handler.take()
771 }
772
773 fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize> {
774 // macOs applies overrides to modal window buttons after they are added.
775 // Two most important for this logic are:
776 // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
777 // * Last button added to the modal via `addButtonWithTitle` stays focused
778 // * Focused buttons react on "space"/" " keypresses
779 // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
780 //
781 // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
782 // ```
783 // By default, the first button has a key equivalent of Return,
784 // any button with a title of “Cancel” has a key equivalent of Escape,
785 // 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).
786 // ```
787 //
788 // To avoid situations when the last element added is "Cancel" and it gets the focus
789 // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
790 // last, so it gets focus and a Space shortcut.
791 // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
792 let latest_non_cancel_label = answers
793 .iter()
794 .enumerate()
795 .rev()
796 .find(|(_, &label)| label != "Cancel")
797 .filter(|&(label_index, _)| label_index > 0);
798
799 unsafe {
800 let alert: id = msg_send![class!(NSAlert), alloc];
801 let alert: id = msg_send![alert, init];
802 let alert_style = match level {
803 PromptLevel::Info => 1,
804 PromptLevel::Warning => 0,
805 PromptLevel::Critical => 2,
806 };
807 let _: () = msg_send![alert, setAlertStyle: alert_style];
808 let _: () = msg_send![alert, setMessageText: ns_string(msg)];
809
810 for (ix, answer) in answers
811 .iter()
812 .enumerate()
813 .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
814 {
815 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
816 let _: () = msg_send![button, setTag: ix as NSInteger];
817 }
818 if let Some((ix, answer)) = latest_non_cancel_label {
819 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
820 let _: () = msg_send![button, setTag: ix as NSInteger];
821 }
822
823 let (done_tx, done_rx) = oneshot::channel();
824 let done_tx = Cell::new(Some(done_tx));
825 let block = ConcreteBlock::new(move |answer: NSInteger| {
826 if let Some(done_tx) = done_tx.take() {
827 let _ = done_tx.send(answer.try_into().unwrap());
828 }
829 });
830 let block = block.copy();
831 let native_window = self.0.lock().native_window;
832 let executor = self.0.lock().executor.clone();
833 executor
834 .spawn(async move {
835 let _: () = msg_send![
836 alert,
837 beginSheetModalForWindow: native_window
838 completionHandler: block
839 ];
840 })
841 .detach();
842
843 done_rx
844 }
845 }
846
847 fn activate(&self) {
848 let window = self.0.lock().native_window;
849 let executor = self.0.lock().executor.clone();
850 executor
851 .spawn(async move {
852 unsafe {
853 let _: () = msg_send![window, makeKeyAndOrderFront: nil];
854 }
855 })
856 .detach();
857 }
858
859 fn set_title(&mut self, title: &str) {
860 unsafe {
861 let app = NSApplication::sharedApplication(nil);
862 let window = self.0.lock().native_window;
863 let title = ns_string(title);
864 let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
865 let _: () = msg_send![window, setTitle: title];
866 self.0.lock().move_traffic_light();
867 }
868 }
869
870 fn set_edited(&mut self, edited: bool) {
871 unsafe {
872 let window = self.0.lock().native_window;
873 msg_send![window, setDocumentEdited: edited as BOOL]
874 }
875
876 // Changing the document edited state resets the traffic light position,
877 // so we have to move it again.
878 self.0.lock().move_traffic_light();
879 }
880
881 fn show_character_palette(&self) {
882 let this = self.0.lock();
883 let window = this.native_window;
884 this.executor
885 .spawn(async move {
886 unsafe {
887 let app = NSApplication::sharedApplication(nil);
888 let _: () = msg_send![app, orderFrontCharacterPalette: window];
889 }
890 })
891 .detach();
892 }
893
894 fn minimize(&self) {
895 let window = self.0.lock().native_window;
896 unsafe {
897 window.miniaturize_(nil);
898 }
899 }
900
901 fn zoom(&self) {
902 let this = self.0.lock();
903 let window = this.native_window;
904 this.executor
905 .spawn(async move {
906 unsafe {
907 window.zoom_(nil);
908 }
909 })
910 .detach();
911 }
912
913 fn toggle_full_screen(&self) {
914 let this = self.0.lock();
915 let window = this.native_window;
916 this.executor
917 .spawn(async move {
918 unsafe {
919 window.toggleFullScreen_(nil);
920 }
921 })
922 .detach();
923 }
924
925 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
926 self.0.as_ref().lock().request_frame_callback = Some(callback);
927 }
928
929 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
930 self.0.as_ref().lock().event_callback = Some(callback);
931 }
932
933 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
934 self.0.as_ref().lock().activate_callback = Some(callback);
935 }
936
937 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
938 self.0.as_ref().lock().resize_callback = Some(callback);
939 }
940
941 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
942 self.0.as_ref().lock().fullscreen_callback = Some(callback);
943 }
944
945 fn on_moved(&self, callback: Box<dyn FnMut()>) {
946 self.0.as_ref().lock().moved_callback = Some(callback);
947 }
948
949 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
950 self.0.as_ref().lock().should_close_callback = Some(callback);
951 }
952
953 fn on_close(&self, callback: Box<dyn FnOnce()>) {
954 self.0.as_ref().lock().close_callback = Some(callback);
955 }
956
957 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
958 self.0.lock().appearance_changed_callback = Some(callback);
959 }
960
961 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
962 let self_borrow = self.0.lock();
963 let self_handle = self_borrow.handle;
964
965 unsafe {
966 let app = NSApplication::sharedApplication(nil);
967
968 // Convert back to screen coordinates
969 let screen_point = self_borrow.to_screen_ns_point(position);
970
971 let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
972 let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
973
974 let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
975 let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
976 if is_panel == YES || is_window == YES {
977 let topmost_window = get_window_state(&*top_most_window).lock().handle;
978 topmost_window == self_handle
979 } else {
980 // Someone else's window is on top
981 false
982 }
983 }
984 }
985
986 fn invalidate(&self) {
987 let this = self.0.lock();
988 unsafe {
989 let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
990 }
991 }
992
993 fn draw(&self, scene: &crate::Scene) {
994 let mut this = self.0.lock();
995 this.renderer.draw(scene);
996 }
997
998 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
999 self.0.lock().renderer.sprite_atlas().clone()
1000 }
1001}
1002
1003fn get_scale_factor(native_window: id) -> f32 {
1004 unsafe {
1005 let screen: id = msg_send![native_window, screen];
1006 NSScreen::backingScaleFactor(screen) as f32
1007 }
1008}
1009
1010unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1011 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1012 let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1013 let rc2 = rc1.clone();
1014 mem::forget(rc1);
1015 rc2
1016}
1017
1018unsafe fn drop_window_state(object: &Object) {
1019 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1020 Rc::from_raw(raw as *mut RefCell<MacWindowState>);
1021}
1022
1023extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1024 YES
1025}
1026
1027extern "C" fn dealloc_window(this: &Object, _: Sel) {
1028 unsafe {
1029 drop_window_state(this);
1030 let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1031 }
1032}
1033
1034extern "C" fn dealloc_view(this: &Object, _: Sel) {
1035 unsafe {
1036 drop_window_state(this);
1037 let _: () = msg_send![super(this, class!(NSView)), dealloc];
1038 }
1039}
1040
1041extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1042 handle_key_event(this, native_event, true)
1043}
1044
1045extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1046 handle_key_event(this, native_event, false);
1047}
1048
1049extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1050 let window_state = unsafe { get_window_state(this) };
1051 let mut lock = window_state.as_ref().lock();
1052
1053 let window_height = lock.content_size().height;
1054 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1055
1056 if let Some(PlatformInput::KeyDown(event)) = event {
1057 // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1058 // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1059 // makes no distinction between these two types of events, so we need to ignore
1060 // the "key down" event if we've already just processed its "key equivalent" version.
1061 if key_equivalent {
1062 lock.last_key_equivalent = Some(event.clone());
1063 } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1064 return NO;
1065 }
1066
1067 let keydown = event.keystroke.clone();
1068 let fn_modifier = keydown.modifiers.function;
1069 // Ignore events from held-down keys after some of the initially-pressed keys
1070 // were released.
1071 if event.is_held {
1072 if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1073 return YES;
1074 }
1075 } else {
1076 lock.last_fresh_keydown = Some(keydown);
1077 }
1078 lock.pending_key_down = Some((event, None));
1079 drop(lock);
1080
1081 // Send the event to the input context for IME handling, unless the `fn` modifier is
1082 // being pressed.
1083 if !fn_modifier {
1084 unsafe {
1085 let input_context: id = msg_send![this, inputContext];
1086 let _: BOOL = msg_send![input_context, handleEvent: native_event];
1087 }
1088 }
1089
1090 let mut handled = false;
1091 let mut lock = window_state.lock();
1092 let ime_text = lock.ime_text.clone();
1093 if let Some((event, insert_text)) = lock.pending_key_down.take() {
1094 let is_held = event.is_held;
1095 if let Some(mut callback) = lock.event_callback.take() {
1096 drop(lock);
1097
1098 let is_composing =
1099 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1100 .flatten()
1101 .is_some();
1102 if !is_composing {
1103 handled = callback(PlatformInput::KeyDown(event));
1104 }
1105
1106 if !handled {
1107 if let Some(insert) = insert_text {
1108 handled = true;
1109 with_input_handler(this, |input_handler| {
1110 input_handler
1111 .replace_text_in_range(insert.replacement_range, &insert.text)
1112 });
1113 } else if !is_composing && is_held {
1114 if let Some(last_insert_text) = ime_text {
1115 //MacOS IME is a bit funky, and even when you've told it there's nothing to
1116 //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1117 //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1118 with_input_handler(this, |input_handler| {
1119 if input_handler.selected_text_range().is_none() {
1120 handled = true;
1121 input_handler.replace_text_in_range(None, &last_insert_text)
1122 }
1123 });
1124 }
1125 }
1126 }
1127
1128 window_state.lock().event_callback = Some(callback);
1129 }
1130 } else {
1131 handled = true;
1132 }
1133
1134 handled as BOOL
1135 } else {
1136 NO
1137 }
1138}
1139
1140extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1141 let window_state = unsafe { get_window_state(this) };
1142 let weak_window_state = Arc::downgrade(&window_state);
1143 let mut lock = window_state.as_ref().lock();
1144 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1145
1146 let window_height = lock.content_size().height;
1147 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1148
1149 if let Some(mut event) = event {
1150 match &mut event {
1151 PlatformInput::MouseDown(
1152 event @ MouseDownEvent {
1153 button: MouseButton::Left,
1154 modifiers: Modifiers { control: true, .. },
1155 ..
1156 },
1157 ) => {
1158 // On mac, a ctrl-left click should be handled as a right click.
1159 *event = MouseDownEvent {
1160 button: MouseButton::Right,
1161 modifiers: Modifiers {
1162 control: false,
1163 ..event.modifiers
1164 },
1165 click_count: 1,
1166 ..*event
1167 };
1168 }
1169
1170 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1171 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1172 // user is still holding ctrl when releasing the left mouse button
1173 PlatformInput::MouseUp(
1174 event @ MouseUpEvent {
1175 button: MouseButton::Left,
1176 modifiers: Modifiers { control: true, .. },
1177 ..
1178 },
1179 ) => {
1180 *event = MouseUpEvent {
1181 button: MouseButton::Right,
1182 modifiers: Modifiers {
1183 control: false,
1184 ..event.modifiers
1185 },
1186 click_count: 1,
1187 ..*event
1188 };
1189 }
1190
1191 _ => {}
1192 };
1193
1194 match &event {
1195 PlatformInput::MouseMove(
1196 event @ MouseMoveEvent {
1197 pressed_button: Some(_),
1198 ..
1199 },
1200 ) => {
1201 // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1202 // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1203 // with these ones.
1204 if !lock.external_files_dragged {
1205 lock.synthetic_drag_counter += 1;
1206 let executor = lock.executor.clone();
1207 executor
1208 .spawn(synthetic_drag(
1209 weak_window_state,
1210 lock.synthetic_drag_counter,
1211 event.clone(),
1212 ))
1213 .detach();
1214 }
1215 }
1216
1217 PlatformInput::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1218
1219 PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1220 lock.synthetic_drag_counter += 1;
1221 }
1222
1223 PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1224 // Only raise modifiers changed event when they have actually changed
1225 if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1226 modifiers: prev_modifiers,
1227 })) = &lock.previous_modifiers_changed_event
1228 {
1229 if prev_modifiers == modifiers {
1230 return;
1231 }
1232 }
1233
1234 lock.previous_modifiers_changed_event = Some(event.clone());
1235 }
1236
1237 _ => {}
1238 }
1239
1240 if let Some(mut callback) = lock.event_callback.take() {
1241 drop(lock);
1242 callback(event);
1243 window_state.lock().event_callback = Some(callback);
1244 }
1245 }
1246}
1247
1248// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1249// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1250extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1251 let window_state = unsafe { get_window_state(this) };
1252 let mut lock = window_state.as_ref().lock();
1253
1254 let keystroke = Keystroke {
1255 modifiers: Default::default(),
1256 key: ".".into(),
1257 ime_key: None,
1258 };
1259 let event = PlatformInput::KeyDown(KeyDownEvent {
1260 keystroke: keystroke.clone(),
1261 is_held: false,
1262 });
1263
1264 lock.last_fresh_keydown = Some(keystroke);
1265 if let Some(mut callback) = lock.event_callback.take() {
1266 drop(lock);
1267 callback(event);
1268 window_state.lock().event_callback = Some(callback);
1269 }
1270}
1271
1272extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1273 let window_state = unsafe { get_window_state(this) };
1274 window_state.as_ref().lock().move_traffic_light();
1275}
1276
1277extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1278 window_fullscreen_changed(this, true);
1279}
1280
1281extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1282 window_fullscreen_changed(this, false);
1283}
1284
1285fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1286 let window_state = unsafe { get_window_state(this) };
1287 let mut lock = window_state.as_ref().lock();
1288 if let Some(mut callback) = lock.fullscreen_callback.take() {
1289 drop(lock);
1290 callback(is_fullscreen);
1291 window_state.lock().fullscreen_callback = Some(callback);
1292 }
1293}
1294
1295extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1296 let window_state = unsafe { get_window_state(this) };
1297 let mut lock = window_state.as_ref().lock();
1298 if let Some(mut callback) = lock.moved_callback.take() {
1299 drop(lock);
1300 callback();
1301 window_state.lock().moved_callback = Some(callback);
1302 }
1303}
1304
1305extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1306 let window_state = unsafe { get_window_state(this) };
1307 let lock = window_state.lock();
1308 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1309
1310 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1311 // `windowDidBecomeKey` message to the previous key window even though that window
1312 // isn't actually key. This causes a bug if the application is later activated while
1313 // the pop-up is still open, making it impossible to activate the previous key window
1314 // even if the pop-up gets closed. The only way to activate it again is to de-activate
1315 // the app and re-activate it, which is a pretty bad UX.
1316 // The following code detects the spurious event and invokes `resignKeyWindow`:
1317 // in theory, we're not supposed to invoke this method manually but it balances out
1318 // the spurious `becomeKeyWindow` event and helps us work around that bug.
1319 if selector == sel!(windowDidBecomeKey:) && !is_active {
1320 unsafe {
1321 let _: () = msg_send![lock.native_window, resignKeyWindow];
1322 return;
1323 }
1324 }
1325
1326 let executor = lock.executor.clone();
1327 drop(lock);
1328 executor
1329 .spawn(async move {
1330 let mut lock = window_state.as_ref().lock();
1331 if let Some(mut callback) = lock.activate_callback.take() {
1332 drop(lock);
1333 callback(is_active);
1334 window_state.lock().activate_callback = Some(callback);
1335 };
1336 })
1337 .detach();
1338}
1339
1340extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1341 let window_state = unsafe { get_window_state(this) };
1342 let mut lock = window_state.as_ref().lock();
1343 if let Some(mut callback) = lock.should_close_callback.take() {
1344 drop(lock);
1345 let should_close = callback();
1346 window_state.lock().should_close_callback = Some(callback);
1347 should_close as BOOL
1348 } else {
1349 YES
1350 }
1351}
1352
1353extern "C" fn close_window(this: &Object, _: Sel) {
1354 unsafe {
1355 let close_callback = {
1356 let window_state = get_window_state(this);
1357 window_state
1358 .as_ref()
1359 .try_lock()
1360 .and_then(|mut window_state| window_state.close_callback.take())
1361 };
1362
1363 if let Some(callback) = close_callback {
1364 callback();
1365 }
1366
1367 let _: () = msg_send![super(this, class!(NSWindow)), close];
1368 }
1369}
1370
1371extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1372 let window_state = unsafe { get_window_state(this) };
1373 let window_state = window_state.as_ref().lock();
1374 window_state.renderer.layer().as_ptr() as id
1375}
1376
1377extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1378 let window_state = unsafe { get_window_state(this) };
1379 let mut lock = window_state.as_ref().lock();
1380
1381 unsafe {
1382 let scale_factor = lock.scale_factor() as f64;
1383 let size = lock.content_size();
1384 let drawable_size: NSSize = NSSize {
1385 width: f64::from(size.width) * scale_factor,
1386 height: f64::from(size.height) * scale_factor,
1387 };
1388
1389 let _: () = msg_send![
1390 lock.renderer.layer(),
1391 setContentsScale: scale_factor
1392 ];
1393 let _: () = msg_send![
1394 lock.renderer.layer(),
1395 setDrawableSize: drawable_size
1396 ];
1397 }
1398
1399 if let Some(mut callback) = lock.resize_callback.take() {
1400 let content_size = lock.content_size();
1401 let scale_factor = lock.scale_factor();
1402 drop(lock);
1403 callback(content_size, scale_factor);
1404 window_state.as_ref().lock().resize_callback = Some(callback);
1405 };
1406}
1407
1408extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1409 let window_state = unsafe { get_window_state(this) };
1410 let lock = window_state.as_ref().lock();
1411
1412 if lock.content_size() == size.into() {
1413 return;
1414 }
1415
1416 unsafe {
1417 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1418 }
1419
1420 let scale_factor = lock.scale_factor() as f64;
1421 let drawable_size: NSSize = NSSize {
1422 width: size.width * scale_factor,
1423 height: size.height * scale_factor,
1424 };
1425
1426 unsafe {
1427 let _: () = msg_send![
1428 lock.renderer.layer(),
1429 setDrawableSize: drawable_size
1430 ];
1431 }
1432
1433 drop(lock);
1434 let mut lock = window_state.lock();
1435 if let Some(mut callback) = lock.resize_callback.take() {
1436 let content_size = lock.content_size();
1437 let scale_factor = lock.scale_factor();
1438 drop(lock);
1439 callback(content_size, scale_factor);
1440 window_state.lock().resize_callback = Some(callback);
1441 };
1442}
1443
1444extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1445 let window_state = unsafe { get_window_state(this) };
1446 let mut lock = window_state.lock();
1447 if let Some(mut callback) = lock.request_frame_callback.take() {
1448 drop(lock);
1449 callback();
1450 window_state.lock().request_frame_callback = Some(callback);
1451 }
1452}
1453
1454extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1455 unsafe { msg_send![class!(NSArray), array] }
1456}
1457
1458extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1459 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1460 .flatten()
1461 .is_some() as BOOL
1462}
1463
1464extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1465 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1466 .flatten()
1467 .map_or(NSRange::invalid(), |range| range.into())
1468}
1469
1470extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1471 with_input_handler(this, |input_handler| input_handler.selected_text_range())
1472 .flatten()
1473 .map_or(NSRange::invalid(), |range| range.into())
1474}
1475
1476extern "C" fn first_rect_for_character_range(
1477 this: &Object,
1478 _: Sel,
1479 range: NSRange,
1480 _: id,
1481) -> NSRect {
1482 let frame = unsafe {
1483 let window = get_window_state(this).lock().native_window;
1484 NSView::frame(window)
1485 };
1486 with_input_handler(this, |input_handler| {
1487 input_handler.bounds_for_range(range.to_range()?)
1488 })
1489 .flatten()
1490 .map_or(
1491 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1492 |bounds| {
1493 NSRect::new(
1494 NSPoint::new(
1495 frame.origin.x + bounds.origin.x.0 as f64,
1496 frame.origin.y + frame.size.height
1497 - bounds.origin.y.0 as f64
1498 - bounds.size.height.0 as f64,
1499 ),
1500 NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1501 )
1502 },
1503 )
1504}
1505
1506extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1507 unsafe {
1508 let window_state = get_window_state(this);
1509 let mut lock = window_state.lock();
1510 let pending_key_down = lock.pending_key_down.take();
1511 drop(lock);
1512
1513 let is_attributed_string: BOOL =
1514 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1515 let text: id = if is_attributed_string == YES {
1516 msg_send![text, string]
1517 } else {
1518 text
1519 };
1520 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1521 .to_str()
1522 .unwrap();
1523 let replacement_range = replacement_range.to_range();
1524
1525 window_state.lock().ime_text = Some(text.to_string());
1526 window_state.lock().ime_state = ImeState::Acted;
1527
1528 let is_composing =
1529 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1530 .flatten()
1531 .is_some();
1532
1533 if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1534 with_input_handler(this, |input_handler| {
1535 input_handler.replace_text_in_range(replacement_range, text)
1536 });
1537 } else {
1538 let mut pending_key_down = pending_key_down.unwrap();
1539 pending_key_down.1 = Some(InsertText {
1540 replacement_range,
1541 text: text.to_string(),
1542 });
1543 if text.to_string().to_ascii_lowercase() != pending_key_down.0.keystroke.key {
1544 pending_key_down.0.keystroke.ime_key = Some(text.to_string());
1545 }
1546 window_state.lock().pending_key_down = Some(pending_key_down);
1547 }
1548 }
1549}
1550
1551extern "C" fn set_marked_text(
1552 this: &Object,
1553 _: Sel,
1554 text: id,
1555 selected_range: NSRange,
1556 replacement_range: NSRange,
1557) {
1558 unsafe {
1559 let window_state = get_window_state(this);
1560 window_state.lock().pending_key_down.take();
1561
1562 let is_attributed_string: BOOL =
1563 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1564 let text: id = if is_attributed_string == YES {
1565 msg_send![text, string]
1566 } else {
1567 text
1568 };
1569 let selected_range = selected_range.to_range();
1570 let replacement_range = replacement_range.to_range();
1571 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1572 .to_str()
1573 .unwrap();
1574
1575 window_state.lock().ime_state = ImeState::Acted;
1576 window_state.lock().ime_text = Some(text.to_string());
1577
1578 with_input_handler(this, |input_handler| {
1579 input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1580 });
1581 }
1582}
1583
1584extern "C" fn unmark_text(this: &Object, _: Sel) {
1585 unsafe {
1586 let state = get_window_state(this);
1587 let mut borrow = state.lock();
1588 borrow.ime_state = ImeState::Acted;
1589 borrow.ime_text.take();
1590 }
1591
1592 with_input_handler(this, |input_handler| input_handler.unmark_text());
1593}
1594
1595extern "C" fn attributed_substring_for_proposed_range(
1596 this: &Object,
1597 _: Sel,
1598 range: NSRange,
1599 _actual_range: *mut c_void,
1600) -> id {
1601 with_input_handler(this, |input_handler| {
1602 let range = range.to_range()?;
1603 if range.is_empty() {
1604 return None;
1605 }
1606
1607 let selected_text = input_handler.text_for_range(range)?;
1608 unsafe {
1609 let string: id = msg_send![class!(NSAttributedString), alloc];
1610 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1611 Some(string)
1612 }
1613 })
1614 .flatten()
1615 .unwrap_or(nil)
1616}
1617
1618extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1619 unsafe {
1620 let state = get_window_state(this);
1621 let mut borrow = state.lock();
1622 borrow.ime_state = ImeState::Continue;
1623 borrow.ime_text.take();
1624 }
1625}
1626
1627extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1628 unsafe {
1629 let state = get_window_state(this);
1630 let mut lock = state.as_ref().lock();
1631 if let Some(mut callback) = lock.appearance_changed_callback.take() {
1632 drop(lock);
1633 callback();
1634 state.lock().appearance_changed_callback = Some(callback);
1635 }
1636 }
1637}
1638
1639extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1640 unsafe {
1641 let state = get_window_state(this);
1642 let lock = state.as_ref().lock();
1643 if lock.kind == WindowKind::PopUp {
1644 YES
1645 } else {
1646 NO
1647 }
1648 }
1649}
1650
1651extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1652 let window_state = unsafe { get_window_state(this) };
1653 if send_new_event(&window_state, {
1654 let position = drag_event_position(&window_state, dragging_info);
1655 let paths = external_paths_from_event(dragging_info);
1656 PlatformInput::FileDrop(FileDropEvent::Entered { position, paths })
1657 }) {
1658 window_state.lock().external_files_dragged = true;
1659 NSDragOperationCopy
1660 } else {
1661 NSDragOperationNone
1662 }
1663}
1664
1665extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1666 let window_state = unsafe { get_window_state(this) };
1667 let position = drag_event_position(&window_state, dragging_info);
1668 if send_new_event(
1669 &window_state,
1670 PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1671 ) {
1672 NSDragOperationCopy
1673 } else {
1674 NSDragOperationNone
1675 }
1676}
1677
1678extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1679 let window_state = unsafe { get_window_state(this) };
1680 send_new_event(
1681 &window_state,
1682 PlatformInput::FileDrop(FileDropEvent::Exited),
1683 );
1684 window_state.lock().external_files_dragged = false;
1685}
1686
1687extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1688 let window_state = unsafe { get_window_state(this) };
1689 let position = drag_event_position(&window_state, dragging_info);
1690 if send_new_event(
1691 &window_state,
1692 PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1693 ) {
1694 YES
1695 } else {
1696 NO
1697 }
1698}
1699
1700fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1701 let mut paths = SmallVec::new();
1702 let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1703 let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1704 for file in unsafe { filenames.iter() } {
1705 let path = unsafe {
1706 let f = NSString::UTF8String(file);
1707 CStr::from_ptr(f).to_string_lossy().into_owned()
1708 };
1709 paths.push(PathBuf::from(path))
1710 }
1711 ExternalPaths(paths)
1712}
1713
1714extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1715 let window_state = unsafe { get_window_state(this) };
1716 send_new_event(
1717 &window_state,
1718 PlatformInput::FileDrop(FileDropEvent::Exited),
1719 );
1720}
1721
1722async fn synthetic_drag(
1723 window_state: Weak<Mutex<MacWindowState>>,
1724 drag_id: usize,
1725 event: MouseMoveEvent,
1726) {
1727 loop {
1728 Timer::after(Duration::from_millis(16)).await;
1729 if let Some(window_state) = window_state.upgrade() {
1730 let mut lock = window_state.lock();
1731 if lock.synthetic_drag_counter == drag_id {
1732 if let Some(mut callback) = lock.event_callback.take() {
1733 drop(lock);
1734 callback(PlatformInput::MouseMove(event.clone()));
1735 window_state.lock().event_callback = Some(callback);
1736 }
1737 } else {
1738 break;
1739 }
1740 }
1741 }
1742}
1743
1744fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1745 let window_state = window_state_lock.lock().event_callback.take();
1746 if let Some(mut callback) = window_state {
1747 callback(e);
1748 window_state_lock.lock().event_callback = Some(callback);
1749 true
1750 } else {
1751 false
1752 }
1753}
1754
1755fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1756 let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1757 convert_mouse_position(drag_location, window_state.lock().content_size().height)
1758}
1759
1760fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1761where
1762 F: FnOnce(&mut dyn PlatformInputHandler) -> R,
1763{
1764 let window_state = unsafe { get_window_state(window) };
1765 let mut lock = window_state.as_ref().lock();
1766 if let Some(mut input_handler) = lock.input_handler.take() {
1767 drop(lock);
1768 let result = f(input_handler.as_mut());
1769 window_state.lock().input_handler = Some(input_handler);
1770 Some(result)
1771 } else {
1772 None
1773 }
1774}