1use crate::{
2 executor,
3 geometry::{
4 rect::RectF,
5 vector::{vec2f, Vector2F},
6 },
7 keymap_matcher::Keystroke,
8 platform::{
9 self,
10 mac::{
11 platform::NSViewLayerContentsRedrawDuringViewResize, renderer::Renderer, screen::Screen,
12 },
13 Event, InputHandler, KeyDownEvent, ModifiersChangedEvent, MouseButton, MouseButtonEvent,
14 MouseMovedEvent, Scene, WindowBounds, WindowKind,
15 },
16};
17use block::ConcreteBlock;
18use cocoa::{
19 appkit::{
20 CGPoint, NSApplication, NSBackingStoreBuffered, NSScreen, NSView, NSViewHeightSizable,
21 NSViewWidthSizable, NSWindow, NSWindowButton, NSWindowCollectionBehavior,
22 NSWindowStyleMask, NSWindowTitleVisibility,
23 },
24 base::{id, nil},
25 foundation::{NSAutoreleasePool, NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger},
26};
27use core_graphics::display::CGRect;
28use ctor::ctor;
29use foreign_types::ForeignTypeRef;
30use objc::{
31 class,
32 declare::ClassDecl,
33 msg_send,
34 runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
35 sel, sel_impl,
36};
37use postage::oneshot;
38use smol::Timer;
39use std::{
40 any::Any,
41 cell::{Cell, RefCell},
42 convert::TryInto,
43 ffi::{c_void, CStr},
44 mem,
45 ops::Range,
46 os::raw::c_char,
47 ptr,
48 rc::{Rc, Weak},
49 sync::Arc,
50 time::Duration,
51};
52
53use super::{
54 geometry::{NSRectExt, Vector2FExt},
55 ns_string, NSRange,
56};
57
58const WINDOW_STATE_IVAR: &str = "windowState";
59
60static mut WINDOW_CLASS: *const Class = ptr::null();
61static mut PANEL_CLASS: *const Class = ptr::null();
62static mut VIEW_CLASS: *const Class = ptr::null();
63
64#[allow(non_upper_case_globals)]
65const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
66 unsafe { NSWindowStyleMask::from_bits_unchecked(1 << 7) };
67#[allow(non_upper_case_globals)]
68const NSNormalWindowLevel: NSInteger = 0;
69#[allow(non_upper_case_globals)]
70const NSPopUpWindowLevel: NSInteger = 101;
71#[allow(non_upper_case_globals)]
72const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
73#[allow(non_upper_case_globals)]
74const NSTrackingMouseMoved: NSUInteger = 0x02;
75#[allow(non_upper_case_globals)]
76const NSTrackingActiveAlways: NSUInteger = 0x80;
77#[allow(non_upper_case_globals)]
78const NSTrackingInVisibleRect: NSUInteger = 0x200;
79#[allow(non_upper_case_globals)]
80const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
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
223unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
224 let mut decl = ClassDecl::new(name, superclass).unwrap();
225 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
226 decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
227 decl.add_method(
228 sel!(canBecomeMainWindow),
229 yes as extern "C" fn(&Object, Sel) -> BOOL,
230 );
231 decl.add_method(
232 sel!(canBecomeKeyWindow),
233 yes as extern "C" fn(&Object, Sel) -> BOOL,
234 );
235 decl.add_method(
236 sel!(windowDidResize:),
237 window_did_resize as extern "C" fn(&Object, Sel, id),
238 );
239 decl.add_method(
240 sel!(windowWillEnterFullScreen:),
241 window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
242 );
243 decl.add_method(
244 sel!(windowWillExitFullScreen:),
245 window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
246 );
247 decl.add_method(
248 sel!(windowDidMove:),
249 window_did_move as extern "C" fn(&Object, Sel, id),
250 );
251 decl.add_method(
252 sel!(windowDidBecomeKey:),
253 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
254 );
255 decl.add_method(
256 sel!(windowDidResignKey:),
257 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
258 );
259 decl.add_method(
260 sel!(windowShouldClose:),
261 window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
262 );
263 decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
264 decl.register()
265}
266
267///Used to track what the IME does when we send it a keystroke.
268///This is only used to handle the case where the IME mysteriously
269///swallows certain keys.
270///
271///Basically a direct copy of the approach that WezTerm uses in:
272///github.com/wez/wezterm : d5755f3e : window/src/os/macos/window.rs
273enum ImeState {
274 Continue,
275 Acted,
276 None,
277}
278
279struct InsertText {
280 replacement_range: Option<Range<usize>>,
281 text: String,
282}
283
284struct WindowState {
285 id: usize,
286 native_window: id,
287 kind: WindowKind,
288 event_callback: Option<Box<dyn FnMut(Event) -> bool>>,
289 activate_callback: Option<Box<dyn FnMut(bool)>>,
290 resize_callback: Option<Box<dyn FnMut()>>,
291 fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
292 moved_callback: Option<Box<dyn FnMut()>>,
293 should_close_callback: Option<Box<dyn FnMut() -> bool>>,
294 close_callback: Option<Box<dyn FnOnce()>>,
295 appearance_changed_callback: Option<Box<dyn FnMut()>>,
296 input_handler: Option<Box<dyn InputHandler>>,
297 pending_key_down: Option<(KeyDownEvent, Option<InsertText>)>,
298 last_key_equivalent: Option<KeyDownEvent>,
299 synthetic_drag_counter: usize,
300 executor: Rc<executor::Foreground>,
301 scene_to_render: Option<Scene>,
302 renderer: Renderer,
303 last_fresh_keydown: Option<Keystroke>,
304 traffic_light_position: Option<Vector2F>,
305 previous_modifiers_changed_event: Option<Event>,
306 //State tracking what the IME did after the last request
307 ime_state: ImeState,
308 //Retains the last IME Text
309 ime_text: Option<String>,
310}
311
312impl WindowState {
313 fn move_traffic_light(&self) {
314 if let Some(traffic_light_position) = self.traffic_light_position {
315 let titlebar_height = self.titlebar_height();
316
317 unsafe {
318 let close_button: id = msg_send![
319 self.native_window,
320 standardWindowButton: NSWindowButton::NSWindowCloseButton
321 ];
322 let min_button: id = msg_send![
323 self.native_window,
324 standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
325 ];
326 let zoom_button: id = msg_send![
327 self.native_window,
328 standardWindowButton: NSWindowButton::NSWindowZoomButton
329 ];
330
331 let mut close_button_frame: CGRect = msg_send![close_button, frame];
332 let mut min_button_frame: CGRect = msg_send![min_button, frame];
333 let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
334 let mut origin = vec2f(
335 traffic_light_position.x(),
336 titlebar_height
337 - traffic_light_position.y()
338 - close_button_frame.size.height as f32,
339 );
340 let button_spacing =
341 (min_button_frame.origin.x - close_button_frame.origin.x) as f32;
342
343 close_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
344 let _: () = msg_send![close_button, setFrame: close_button_frame];
345 origin.set_x(origin.x() + button_spacing);
346
347 min_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
348 let _: () = msg_send![min_button, setFrame: min_button_frame];
349 origin.set_x(origin.x() + button_spacing);
350
351 zoom_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
352 let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
353 }
354 }
355 }
356
357 fn is_fullscreen(&self) -> bool {
358 unsafe {
359 let style_mask = self.native_window.styleMask();
360 style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
361 }
362 }
363
364 fn bounds(&self) -> WindowBounds {
365 unsafe {
366 if self.is_fullscreen() {
367 return WindowBounds::Fullscreen;
368 }
369
370 let window_frame = self.frame();
371 let screen_frame = self.native_window.screen().visibleFrame().to_rectf();
372 if window_frame.size() == screen_frame.size() {
373 WindowBounds::Maximized
374 } else {
375 WindowBounds::Fixed(window_frame)
376 }
377 }
378 }
379
380 // Returns the window bounds in window coordinates
381 fn frame(&self) -> RectF {
382 unsafe {
383 let screen_frame = self.native_window.screen().visibleFrame();
384 let window_frame = NSWindow::frame(self.native_window);
385 RectF::new(
386 vec2f(
387 window_frame.origin.x as f32,
388 (screen_frame.size.height - window_frame.origin.y - window_frame.size.height)
389 as f32,
390 ),
391 vec2f(
392 window_frame.size.width as f32,
393 window_frame.size.height as f32,
394 ),
395 )
396 }
397 }
398
399 fn content_size(&self) -> Vector2F {
400 let NSSize { width, height, .. } =
401 unsafe { NSView::frame(self.native_window.contentView()) }.size;
402 vec2f(width as f32, height as f32)
403 }
404
405 fn scale_factor(&self) -> f32 {
406 get_scale_factor(self.native_window)
407 }
408
409 fn titlebar_height(&self) -> f32 {
410 unsafe {
411 let frame = NSWindow::frame(self.native_window);
412 let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
413 (frame.size.height - content_layout_rect.size.height) as f32
414 }
415 }
416
417 fn present_scene(&mut self, scene: Scene) {
418 self.scene_to_render = Some(scene);
419 unsafe {
420 let _: () = msg_send![self.native_window.contentView(), setNeedsDisplay: YES];
421 }
422 }
423}
424
425pub struct Window(Rc<RefCell<WindowState>>);
426
427impl Window {
428 pub fn open(
429 id: usize,
430 options: platform::WindowOptions,
431 executor: Rc<executor::Foreground>,
432 fonts: Arc<dyn platform::FontSystem>,
433 ) -> Self {
434 unsafe {
435 let pool = NSAutoreleasePool::new(nil);
436
437 let mut style_mask;
438 if let Some(titlebar) = options.titlebar.as_ref() {
439 style_mask = NSWindowStyleMask::NSClosableWindowMask
440 | NSWindowStyleMask::NSMiniaturizableWindowMask
441 | NSWindowStyleMask::NSResizableWindowMask
442 | NSWindowStyleMask::NSTitledWindowMask;
443
444 if titlebar.appears_transparent {
445 style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
446 }
447 } else {
448 style_mask = NSWindowStyleMask::NSTitledWindowMask
449 | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
450 }
451
452 let native_window: id = match options.kind {
453 WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
454 WindowKind::PopUp => {
455 style_mask |= NSWindowStyleMaskNonactivatingPanel;
456 msg_send![PANEL_CLASS, alloc]
457 }
458 };
459 let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
460 NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.)),
461 style_mask,
462 NSBackingStoreBuffered,
463 NO,
464 options
465 .screen
466 .and_then(|screen| {
467 Some(screen.as_any().downcast_ref::<Screen>()?.native_screen)
468 })
469 .unwrap_or(nil),
470 );
471 assert!(!native_window.is_null());
472
473 let screen = native_window.screen();
474 match options.bounds {
475 WindowBounds::Fullscreen => {
476 native_window.toggleFullScreen_(nil);
477 }
478 WindowBounds::Maximized => {
479 native_window.setFrame_display_(screen.visibleFrame(), YES);
480 }
481 WindowBounds::Fixed(rect) => {
482 let screen_frame = screen.visibleFrame();
483 let ns_rect = NSRect::new(
484 NSPoint::new(
485 rect.origin_x() as f64,
486 screen_frame.size.height
487 - rect.origin_y() as f64
488 - rect.height() as f64,
489 ),
490 NSSize::new(rect.width() as f64, rect.height() as f64),
491 );
492
493 if ns_rect.intersects(screen_frame) {
494 native_window.setFrame_display_(ns_rect, YES);
495 } else {
496 native_window.setFrame_display_(screen_frame, YES);
497 }
498 }
499 }
500
501 let native_view: id = msg_send![VIEW_CLASS, alloc];
502 let native_view = NSView::init(native_view);
503
504 assert!(!native_view.is_null());
505
506 let window = Self(Rc::new(RefCell::new(WindowState {
507 id,
508 native_window,
509 kind: options.kind,
510 event_callback: None,
511 resize_callback: None,
512 should_close_callback: None,
513 close_callback: None,
514 activate_callback: None,
515 fullscreen_callback: None,
516 moved_callback: None,
517 appearance_changed_callback: None,
518 input_handler: None,
519 pending_key_down: None,
520 last_key_equivalent: None,
521 synthetic_drag_counter: 0,
522 executor,
523 scene_to_render: Default::default(),
524 renderer: Renderer::new(true, fonts),
525 last_fresh_keydown: None,
526 traffic_light_position: options
527 .titlebar
528 .as_ref()
529 .and_then(|titlebar| titlebar.traffic_light_position),
530 previous_modifiers_changed_event: None,
531 ime_state: ImeState::None,
532 ime_text: None,
533 })));
534
535 (*native_window).set_ivar(
536 WINDOW_STATE_IVAR,
537 Rc::into_raw(window.0.clone()) as *const c_void,
538 );
539 native_window.setDelegate_(native_window);
540 (*native_view).set_ivar(
541 WINDOW_STATE_IVAR,
542 Rc::into_raw(window.0.clone()) as *const c_void,
543 );
544
545 if let Some(title) = options.titlebar.as_ref().and_then(|t| t.title) {
546 native_window.setTitle_(NSString::alloc(nil).init_str(title));
547 }
548
549 native_window.setMovable_(options.is_movable as BOOL);
550
551 if options
552 .titlebar
553 .map_or(true, |titlebar| titlebar.appears_transparent)
554 {
555 native_window.setTitlebarAppearsTransparent_(YES);
556 native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
557 }
558
559 native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
560 native_view.setWantsBestResolutionOpenGLSurface_(YES);
561
562 // From winit crate: On Mojave, views automatically become layer-backed shortly after
563 // being added to a native_window. Changing the layer-backedness of a view breaks the
564 // association between the view and its associated OpenGL context. To work around this,
565 // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
566 // itself and break the association with its context.
567 native_view.setWantsLayer(YES);
568 let _: () = msg_send![
569 native_view,
570 setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
571 ];
572
573 native_window.setContentView_(native_view.autorelease());
574 native_window.makeFirstResponder_(native_view);
575
576 if options.center {
577 native_window.center();
578 }
579
580 match options.kind {
581 WindowKind::Normal => {
582 native_window.setLevel_(NSNormalWindowLevel);
583 native_window.setAcceptsMouseMovedEvents_(YES);
584 }
585 WindowKind::PopUp => {
586 // Use a tracking area to allow receiving MouseMoved events even when
587 // the window or application aren't active, which is often the case
588 // e.g. for notification windows.
589 let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
590 let _: () = msg_send![
591 tracking_area,
592 initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
593 options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
594 owner: native_view
595 userInfo: nil
596 ];
597 let _: () =
598 msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
599
600 native_window.setLevel_(NSPopUpWindowLevel);
601 let _: () = msg_send![
602 native_window,
603 setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
604 ];
605 native_window.setCollectionBehavior_(
606 NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
607 NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
608 );
609 }
610 }
611 if options.focus {
612 native_window.makeKeyAndOrderFront_(nil);
613 } else if options.show {
614 native_window.orderFront_(nil);
615 }
616
617 window.0.borrow().move_traffic_light();
618 pool.drain();
619
620 window
621 }
622 }
623
624 pub fn main_window_id() -> Option<usize> {
625 unsafe {
626 let app = NSApplication::sharedApplication(nil);
627 let main_window: id = msg_send![app, mainWindow];
628 if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
629 let id = get_window_state(&*main_window).borrow().id;
630 Some(id)
631 } else {
632 None
633 }
634 }
635 }
636}
637
638impl Drop for Window {
639 fn drop(&mut self) {
640 let this = self.0.borrow();
641 let window = this.native_window;
642 this.executor
643 .spawn(async move {
644 unsafe {
645 window.close();
646 }
647 })
648 .detach();
649 }
650}
651
652impl platform::Window for Window {
653 fn bounds(&self) -> WindowBounds {
654 self.0.as_ref().borrow().bounds()
655 }
656
657 fn content_size(&self) -> Vector2F {
658 self.0.as_ref().borrow().content_size()
659 }
660
661 fn scale_factor(&self) -> f32 {
662 self.0.as_ref().borrow().scale_factor()
663 }
664
665 fn titlebar_height(&self) -> f32 {
666 self.0.as_ref().borrow().titlebar_height()
667 }
668
669 fn appearance(&self) -> platform::Appearance {
670 unsafe {
671 let appearance: id = msg_send![self.0.borrow().native_window, effectiveAppearance];
672 platform::Appearance::from_native(appearance)
673 }
674 }
675
676 fn screen(&self) -> Rc<dyn platform::Screen> {
677 unsafe {
678 Rc::new(Screen {
679 native_screen: self.0.as_ref().borrow().native_window.screen(),
680 })
681 }
682 }
683
684 fn as_any_mut(&mut self) -> &mut dyn Any {
685 self
686 }
687
688 fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>) {
689 self.0.as_ref().borrow_mut().input_handler = Some(input_handler);
690 }
691
692 fn prompt(
693 &self,
694 level: platform::PromptLevel,
695 msg: &str,
696 answers: &[&str],
697 ) -> oneshot::Receiver<usize> {
698 // macOs applies overrides to modal window buttons after they are added.
699 // Two most important for this logic are:
700 // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
701 // * Last button added to the modal via `addButtonWithTitle` stays focused
702 // * Focused buttons react on "space"/" " keypresses
703 // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
704 //
705 // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
706 // ```
707 // By default, the first button has a key equivalent of Return,
708 // any button with a title of “Cancel” has a key equivalent of Escape,
709 // 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).
710 // ```
711 //
712 // To avoid situations when the last element added is "Cancel" and it gets the focus
713 // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
714 // last, so it gets focus and a Space shortcut.
715 // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
716 let latest_non_cancel_label = answers
717 .iter()
718 .enumerate()
719 .rev()
720 .find(|(_, &label)| label != "Cancel")
721 .filter(|&(label_index, _)| label_index > 0);
722
723 unsafe {
724 let alert: id = msg_send![class!(NSAlert), alloc];
725 let alert: id = msg_send![alert, init];
726 let alert_style = match level {
727 platform::PromptLevel::Info => 1,
728 platform::PromptLevel::Warning => 0,
729 platform::PromptLevel::Critical => 2,
730 };
731 let _: () = msg_send![alert, setAlertStyle: alert_style];
732 let _: () = msg_send![alert, setMessageText: ns_string(msg)];
733
734 for (ix, answer) in answers
735 .iter()
736 .enumerate()
737 .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
738 {
739 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
740 let _: () = msg_send![button, setTag: ix as NSInteger];
741 }
742 if let Some((ix, answer)) = latest_non_cancel_label {
743 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
744 let _: () = msg_send![button, setTag: ix as NSInteger];
745 }
746
747 let (done_tx, done_rx) = oneshot::channel();
748 let done_tx = Cell::new(Some(done_tx));
749 let block = ConcreteBlock::new(move |answer: NSInteger| {
750 if let Some(mut done_tx) = done_tx.take() {
751 let _ = postage::sink::Sink::try_send(&mut done_tx, answer.try_into().unwrap());
752 }
753 });
754 let block = block.copy();
755 let native_window = self.0.borrow().native_window;
756 self.0
757 .borrow()
758 .executor
759 .spawn(async move {
760 let _: () = msg_send![
761 alert,
762 beginSheetModalForWindow: native_window
763 completionHandler: block
764 ];
765 })
766 .detach();
767
768 done_rx
769 }
770 }
771
772 fn activate(&self) {
773 let window = self.0.borrow().native_window;
774 self.0
775 .borrow()
776 .executor
777 .spawn(async move {
778 unsafe {
779 let _: () = msg_send![window, makeKeyAndOrderFront: nil];
780 }
781 })
782 .detach();
783 }
784
785 fn set_title(&mut self, title: &str) {
786 unsafe {
787 let app = NSApplication::sharedApplication(nil);
788 let window = self.0.borrow().native_window;
789 let title = ns_string(title);
790 let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
791 let _: () = msg_send![window, setTitle: title];
792 self.0.borrow().move_traffic_light();
793 }
794 }
795
796 fn set_edited(&mut self, edited: bool) {
797 unsafe {
798 let window = self.0.borrow().native_window;
799 msg_send![window, setDocumentEdited: edited as BOOL]
800 }
801
802 // Changing the document edited state resets the traffic light position,
803 // so we have to move it again.
804 self.0.borrow().move_traffic_light();
805 }
806
807 fn show_character_palette(&self) {
808 unsafe {
809 let app = NSApplication::sharedApplication(nil);
810 let window = self.0.borrow().native_window;
811 let _: () = msg_send![app, orderFrontCharacterPalette: window];
812 }
813 }
814
815 fn minimize(&self) {
816 let window = self.0.borrow().native_window;
817 unsafe {
818 window.miniaturize_(nil);
819 }
820 }
821
822 fn zoom(&self) {
823 let this = self.0.borrow();
824 let window = this.native_window;
825 this.executor
826 .spawn(async move {
827 unsafe {
828 window.zoom_(nil);
829 }
830 })
831 .detach();
832 }
833
834 fn present_scene(&mut self, scene: Scene) {
835 self.0.as_ref().borrow_mut().present_scene(scene);
836 }
837
838 fn toggle_full_screen(&self) {
839 let this = self.0.borrow();
840 let window = this.native_window;
841 this.executor
842 .spawn(async move {
843 unsafe {
844 window.toggleFullScreen_(nil);
845 }
846 })
847 .detach();
848 }
849
850 fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>) {
851 self.0.as_ref().borrow_mut().event_callback = Some(callback);
852 }
853
854 fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
855 self.0.as_ref().borrow_mut().activate_callback = Some(callback);
856 }
857
858 fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
859 self.0.as_ref().borrow_mut().resize_callback = Some(callback);
860 }
861
862 fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
863 self.0.as_ref().borrow_mut().fullscreen_callback = Some(callback);
864 }
865
866 fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
867 self.0.as_ref().borrow_mut().moved_callback = Some(callback);
868 }
869
870 fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
871 self.0.as_ref().borrow_mut().should_close_callback = Some(callback);
872 }
873
874 fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
875 self.0.as_ref().borrow_mut().close_callback = Some(callback);
876 }
877
878 fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>) {
879 self.0.borrow_mut().appearance_changed_callback = Some(callback);
880 }
881
882 fn is_topmost_for_position(&self, position: Vector2F) -> bool {
883 let self_borrow = self.0.borrow();
884 let self_id = self_borrow.id;
885
886 unsafe {
887 let app = NSApplication::sharedApplication(nil);
888
889 // Convert back to screen coordinates
890 let screen_point = position.to_screen_ns_point(
891 self_borrow.native_window,
892 self_borrow.content_size().y() as f64,
893 );
894
895 let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
896 let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
897
898 let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
899 let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
900 if is_panel == YES || is_window == YES {
901 let topmost_window_id = get_window_state(&*top_most_window).borrow().id;
902 topmost_window_id == self_id
903 } else {
904 // Someone else's window is on top
905 false
906 }
907 }
908 }
909}
910
911fn get_scale_factor(native_window: id) -> f32 {
912 unsafe {
913 let screen: id = msg_send![native_window, screen];
914 NSScreen::backingScaleFactor(screen) as f32
915 }
916}
917
918unsafe fn get_window_state(object: &Object) -> Rc<RefCell<WindowState>> {
919 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
920 let rc1 = Rc::from_raw(raw as *mut RefCell<WindowState>);
921 let rc2 = rc1.clone();
922 mem::forget(rc1);
923 rc2
924}
925
926unsafe fn drop_window_state(object: &Object) {
927 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
928 Rc::from_raw(raw as *mut RefCell<WindowState>);
929}
930
931extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
932 YES
933}
934
935extern "C" fn dealloc_window(this: &Object, _: Sel) {
936 unsafe {
937 drop_window_state(this);
938 let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
939 }
940}
941
942extern "C" fn dealloc_view(this: &Object, _: Sel) {
943 unsafe {
944 drop_window_state(this);
945 let _: () = msg_send![super(this, class!(NSView)), dealloc];
946 }
947}
948
949extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
950 handle_key_event(this, native_event, true)
951}
952
953extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
954 handle_key_event(this, native_event, false);
955}
956
957extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
958 let window_state = unsafe { get_window_state(this) };
959 let mut window_state_borrow = window_state.as_ref().borrow_mut();
960
961 let window_height = window_state_borrow.content_size().y();
962 let event = unsafe { Event::from_native(native_event, Some(window_height)) };
963
964 if let Some(Event::KeyDown(event)) = event {
965 // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
966 // If that event isn't handled, it will then dispatch a "key down" event. GPUI
967 // makes no distinction between these two types of events, so we need to ignore
968 // the "key down" event if we've already just processed its "key equivalent" version.
969 if key_equivalent {
970 window_state_borrow.last_key_equivalent = Some(event.clone());
971 } else if window_state_borrow.last_key_equivalent.take().as_ref() == Some(&event) {
972 return NO;
973 }
974
975 let keydown = event.keystroke.clone();
976 let fn_modifier = keydown.function;
977 // Ignore events from held-down keys after some of the initially-pressed keys
978 // were released.
979 if event.is_held {
980 if window_state_borrow.last_fresh_keydown.as_ref() != Some(&keydown) {
981 return YES;
982 }
983 } else {
984 window_state_borrow.last_fresh_keydown = Some(keydown);
985 }
986 window_state_borrow.pending_key_down = Some((event, None));
987 drop(window_state_borrow);
988
989 // Send the event to the input context for IME handling, unless the `fn` modifier is
990 // being pressed.
991 if !fn_modifier {
992 unsafe {
993 let input_context: id = msg_send![this, inputContext];
994 let _: BOOL = msg_send![input_context, handleEvent: native_event];
995 }
996 }
997
998 let mut handled = false;
999 let mut window_state_borrow = window_state.borrow_mut();
1000 let ime_text = window_state_borrow.ime_text.clone();
1001 if let Some((event, insert_text)) = window_state_borrow.pending_key_down.take() {
1002 let is_held = event.is_held;
1003 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1004 drop(window_state_borrow);
1005
1006 let is_composing =
1007 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1008 .flatten()
1009 .is_some();
1010 if !is_composing {
1011 handled = callback(Event::KeyDown(event));
1012 }
1013
1014 if !handled {
1015 if let Some(insert) = insert_text {
1016 handled = true;
1017 with_input_handler(this, |input_handler| {
1018 input_handler
1019 .replace_text_in_range(insert.replacement_range, &insert.text)
1020 });
1021 } else if !is_composing && is_held {
1022 if let Some(last_insert_text) = ime_text {
1023 //MacOS IME is a bit funky, and even when you've told it there's nothing to
1024 //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1025 //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1026 with_input_handler(this, |input_handler| {
1027 if input_handler.selected_text_range().is_none() {
1028 handled = true;
1029 input_handler.replace_text_in_range(None, &last_insert_text)
1030 }
1031 });
1032 }
1033 }
1034 }
1035
1036 window_state.borrow_mut().event_callback = Some(callback);
1037 }
1038 } else {
1039 handled = true;
1040 }
1041
1042 handled as BOOL
1043 } else {
1044 NO
1045 }
1046}
1047
1048extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1049 let window_state = unsafe { get_window_state(this) };
1050 let weak_window_state = Rc::downgrade(&window_state);
1051 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1052 let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1053
1054 let window_height = window_state_borrow.content_size().y();
1055 let event = unsafe { Event::from_native(native_event, Some(window_height)) };
1056 if let Some(event) = event {
1057 match &event {
1058 Event::MouseMoved(
1059 event @ MouseMovedEvent {
1060 pressed_button: Some(_),
1061 ..
1062 },
1063 ) => {
1064 window_state_borrow.synthetic_drag_counter += 1;
1065 window_state_borrow
1066 .executor
1067 .spawn(synthetic_drag(
1068 weak_window_state,
1069 window_state_borrow.synthetic_drag_counter,
1070 *event,
1071 ))
1072 .detach();
1073 }
1074
1075 Event::MouseMoved(_)
1076 if !(is_active || window_state_borrow.kind == WindowKind::PopUp) =>
1077 {
1078 return
1079 }
1080
1081 Event::MouseUp(MouseButtonEvent {
1082 button: MouseButton::Left,
1083 ..
1084 }) => {
1085 window_state_borrow.synthetic_drag_counter += 1;
1086 }
1087
1088 Event::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1089 // Only raise modifiers changed event when they have actually changed
1090 if let Some(Event::ModifiersChanged(ModifiersChangedEvent {
1091 modifiers: prev_modifiers,
1092 })) = &window_state_borrow.previous_modifiers_changed_event
1093 {
1094 if prev_modifiers == modifiers {
1095 return;
1096 }
1097 }
1098
1099 window_state_borrow.previous_modifiers_changed_event = Some(event.clone());
1100 }
1101
1102 _ => {}
1103 }
1104
1105 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1106 drop(window_state_borrow);
1107 callback(event);
1108 window_state.borrow_mut().event_callback = Some(callback);
1109 }
1110 }
1111}
1112
1113// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1114// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1115extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1116 let window_state = unsafe { get_window_state(this) };
1117 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1118
1119 let keystroke = Keystroke {
1120 cmd: true,
1121 ctrl: false,
1122 alt: false,
1123 shift: false,
1124 function: false,
1125 key: ".".into(),
1126 };
1127 let event = Event::KeyDown(KeyDownEvent {
1128 keystroke: keystroke.clone(),
1129 is_held: false,
1130 });
1131
1132 window_state_borrow.last_fresh_keydown = Some(keystroke);
1133 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1134 drop(window_state_borrow);
1135 callback(event);
1136 window_state.borrow_mut().event_callback = Some(callback);
1137 }
1138}
1139
1140extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1141 let window_state = unsafe { get_window_state(this) };
1142 window_state.as_ref().borrow().move_traffic_light();
1143}
1144
1145extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1146 window_fullscreen_changed(this, true);
1147}
1148
1149extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1150 window_fullscreen_changed(this, false);
1151}
1152
1153fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1154 let window_state = unsafe { get_window_state(this) };
1155 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1156 if let Some(mut callback) = window_state_borrow.fullscreen_callback.take() {
1157 drop(window_state_borrow);
1158 callback(is_fullscreen);
1159 window_state.borrow_mut().fullscreen_callback = Some(callback);
1160 }
1161}
1162
1163extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1164 let window_state = unsafe { get_window_state(this) };
1165 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1166 if let Some(mut callback) = window_state_borrow.moved_callback.take() {
1167 drop(window_state_borrow);
1168 callback();
1169 window_state.borrow_mut().moved_callback = Some(callback);
1170 }
1171}
1172
1173extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1174 let window_state = unsafe { get_window_state(this) };
1175 let window_state_borrow = window_state.borrow();
1176 let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1177
1178 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1179 // `windowDidBecomeKey` message to the previous key window even though that window
1180 // isn't actually key. This causes a bug if the application is later activated while
1181 // the pop-up is still open, making it impossible to activate the previous key window
1182 // even if the pop-up gets closed. The only way to activate it again is to de-activate
1183 // the app and re-activate it, which is a pretty bad UX.
1184 // The following code detects the spurious event and invokes `resignKeyWindow`:
1185 // in theory, we're not supposed to invoke this method manually but it balances out
1186 // the spurious `becomeKeyWindow` event and helps us work around that bug.
1187 if selector == sel!(windowDidBecomeKey:) {
1188 if !is_active {
1189 unsafe {
1190 let _: () = msg_send![window_state_borrow.native_window, resignKeyWindow];
1191 return;
1192 }
1193 }
1194 }
1195
1196 let executor = window_state_borrow.executor.clone();
1197 drop(window_state_borrow);
1198 executor
1199 .spawn(async move {
1200 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1201 if let Some(mut callback) = window_state_borrow.activate_callback.take() {
1202 drop(window_state_borrow);
1203 callback(is_active);
1204 window_state.borrow_mut().activate_callback = Some(callback);
1205 };
1206 })
1207 .detach();
1208}
1209
1210extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1211 let window_state = unsafe { get_window_state(this) };
1212 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1213 if let Some(mut callback) = window_state_borrow.should_close_callback.take() {
1214 drop(window_state_borrow);
1215 let should_close = callback();
1216 window_state.borrow_mut().should_close_callback = Some(callback);
1217 should_close as BOOL
1218 } else {
1219 YES
1220 }
1221}
1222
1223extern "C" fn close_window(this: &Object, _: Sel) {
1224 unsafe {
1225 let close_callback = {
1226 let window_state = get_window_state(this);
1227 window_state
1228 .as_ref()
1229 .try_borrow_mut()
1230 .ok()
1231 .and_then(|mut window_state| window_state.close_callback.take())
1232 };
1233
1234 if let Some(callback) = close_callback {
1235 callback();
1236 }
1237
1238 let _: () = msg_send![super(this, class!(NSWindow)), close];
1239 }
1240}
1241
1242extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1243 let window_state = unsafe { get_window_state(this) };
1244 let window_state = window_state.as_ref().borrow();
1245 window_state.renderer.layer().as_ptr() as id
1246}
1247
1248extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1249 let window_state = unsafe { get_window_state(this) };
1250 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1251
1252 unsafe {
1253 let scale_factor = window_state_borrow.scale_factor() as f64;
1254 let size = window_state_borrow.content_size();
1255 let drawable_size: NSSize = NSSize {
1256 width: size.x() as f64 * scale_factor,
1257 height: size.y() as f64 * scale_factor,
1258 };
1259
1260 let _: () = msg_send![
1261 window_state_borrow.renderer.layer(),
1262 setContentsScale: scale_factor
1263 ];
1264 let _: () = msg_send![
1265 window_state_borrow.renderer.layer(),
1266 setDrawableSize: drawable_size
1267 ];
1268 }
1269
1270 if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1271 drop(window_state_borrow);
1272 callback();
1273 window_state.as_ref().borrow_mut().resize_callback = Some(callback);
1274 };
1275}
1276
1277extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1278 let window_state = unsafe { get_window_state(this) };
1279 let window_state_borrow = window_state.as_ref().borrow();
1280
1281 if window_state_borrow.content_size() == vec2f(size.width as f32, size.height as f32) {
1282 return;
1283 }
1284
1285 unsafe {
1286 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1287 }
1288
1289 let scale_factor = window_state_borrow.scale_factor() as f64;
1290 let drawable_size: NSSize = NSSize {
1291 width: size.width * scale_factor,
1292 height: size.height * scale_factor,
1293 };
1294
1295 unsafe {
1296 let _: () = msg_send![
1297 window_state_borrow.renderer.layer(),
1298 setDrawableSize: drawable_size
1299 ];
1300 }
1301
1302 drop(window_state_borrow);
1303 let mut window_state_borrow = window_state.borrow_mut();
1304 if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1305 drop(window_state_borrow);
1306 callback();
1307 window_state.borrow_mut().resize_callback = Some(callback);
1308 };
1309}
1310
1311extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1312 unsafe {
1313 let window_state = get_window_state(this);
1314 let mut window_state = window_state.as_ref().borrow_mut();
1315 if let Some(scene) = window_state.scene_to_render.take() {
1316 window_state.renderer.render(&scene);
1317 };
1318 }
1319}
1320
1321extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1322 unsafe { msg_send![class!(NSArray), array] }
1323}
1324
1325extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1326 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1327 .flatten()
1328 .is_some() as BOOL
1329}
1330
1331extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1332 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1333 .flatten()
1334 .map_or(NSRange::invalid(), |range| range.into())
1335}
1336
1337extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1338 with_input_handler(this, |input_handler| input_handler.selected_text_range())
1339 .flatten()
1340 .map_or(NSRange::invalid(), |range| range.into())
1341}
1342
1343extern "C" fn first_rect_for_character_range(
1344 this: &Object,
1345 _: Sel,
1346 range: NSRange,
1347 _: id,
1348) -> NSRect {
1349 let frame = unsafe {
1350 let window = get_window_state(this).borrow().native_window;
1351 NSView::frame(window)
1352 };
1353 with_input_handler(this, |input_handler| {
1354 input_handler.rect_for_range(range.to_range()?)
1355 })
1356 .flatten()
1357 .map_or(
1358 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1359 |rect| {
1360 NSRect::new(
1361 NSPoint::new(
1362 frame.origin.x + rect.origin_x() as f64,
1363 frame.origin.y + frame.size.height - rect.origin_y() as f64,
1364 ),
1365 NSSize::new(rect.width() as f64, rect.height() as f64),
1366 )
1367 },
1368 )
1369}
1370
1371extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1372 unsafe {
1373 let window_state = get_window_state(this);
1374 let mut window_state_borrow = window_state.borrow_mut();
1375 let pending_key_down = window_state_borrow.pending_key_down.take();
1376 drop(window_state_borrow);
1377
1378 let is_attributed_string: BOOL =
1379 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1380 let text: id = if is_attributed_string == YES {
1381 msg_send![text, string]
1382 } else {
1383 text
1384 };
1385 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1386 .to_str()
1387 .unwrap();
1388 let replacement_range = replacement_range.to_range();
1389
1390 window_state.borrow_mut().ime_text = Some(text.to_string());
1391 window_state.borrow_mut().ime_state = ImeState::Acted;
1392
1393 let is_composing =
1394 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1395 .flatten()
1396 .is_some();
1397
1398 if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1399 with_input_handler(this, |input_handler| {
1400 input_handler.replace_text_in_range(replacement_range, text)
1401 });
1402 } else {
1403 let mut pending_key_down = pending_key_down.unwrap();
1404 pending_key_down.1 = Some(InsertText {
1405 replacement_range,
1406 text: text.to_string(),
1407 });
1408 window_state.borrow_mut().pending_key_down = Some(pending_key_down);
1409 }
1410 }
1411}
1412
1413extern "C" fn set_marked_text(
1414 this: &Object,
1415 _: Sel,
1416 text: id,
1417 selected_range: NSRange,
1418 replacement_range: NSRange,
1419) {
1420 unsafe {
1421 let window_state = get_window_state(this);
1422 window_state.borrow_mut().pending_key_down.take();
1423
1424 let is_attributed_string: BOOL =
1425 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1426 let text: id = if is_attributed_string == YES {
1427 msg_send![text, string]
1428 } else {
1429 text
1430 };
1431 let selected_range = selected_range.to_range();
1432 let replacement_range = replacement_range.to_range();
1433 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1434 .to_str()
1435 .unwrap();
1436
1437 window_state.borrow_mut().ime_state = ImeState::Acted;
1438 window_state.borrow_mut().ime_text = Some(text.to_string());
1439
1440 with_input_handler(this, |input_handler| {
1441 input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1442 });
1443 }
1444}
1445
1446extern "C" fn unmark_text(this: &Object, _: Sel) {
1447 unsafe {
1448 let state = get_window_state(this);
1449 let mut borrow = state.borrow_mut();
1450 borrow.ime_state = ImeState::Acted;
1451 borrow.ime_text.take();
1452 }
1453
1454 with_input_handler(this, |input_handler| input_handler.unmark_text());
1455}
1456
1457extern "C" fn attributed_substring_for_proposed_range(
1458 this: &Object,
1459 _: Sel,
1460 range: NSRange,
1461 _actual_range: *mut c_void,
1462) -> id {
1463 with_input_handler(this, |input_handler| {
1464 let range = range.to_range()?;
1465 if range.is_empty() {
1466 return None;
1467 }
1468
1469 let selected_text = input_handler.text_for_range(range)?;
1470 unsafe {
1471 let string: id = msg_send![class!(NSAttributedString), alloc];
1472 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1473 Some(string)
1474 }
1475 })
1476 .flatten()
1477 .unwrap_or(nil)
1478}
1479
1480extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1481 unsafe {
1482 let state = get_window_state(this);
1483 let mut borrow = state.borrow_mut();
1484 borrow.ime_state = ImeState::Continue;
1485 borrow.ime_text.take();
1486 }
1487}
1488
1489extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1490 unsafe {
1491 let state = get_window_state(this);
1492 let mut state_borrow = state.as_ref().borrow_mut();
1493 if let Some(mut callback) = state_borrow.appearance_changed_callback.take() {
1494 drop(state_borrow);
1495 callback();
1496 state.borrow_mut().appearance_changed_callback = Some(callback);
1497 }
1498 }
1499}
1500
1501extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1502 unsafe {
1503 let state = get_window_state(this);
1504 let state_borrow = state.as_ref().borrow();
1505 return if state_borrow.kind == WindowKind::PopUp {
1506 YES
1507 } else {
1508 NO
1509 };
1510 }
1511}
1512
1513async fn synthetic_drag(
1514 window_state: Weak<RefCell<WindowState>>,
1515 drag_id: usize,
1516 event: MouseMovedEvent,
1517) {
1518 loop {
1519 Timer::after(Duration::from_millis(16)).await;
1520 if let Some(window_state) = window_state.upgrade() {
1521 let mut window_state_borrow = window_state.borrow_mut();
1522 if window_state_borrow.synthetic_drag_counter == drag_id {
1523 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1524 drop(window_state_borrow);
1525 callback(Event::MouseMoved(event));
1526 window_state.borrow_mut().event_callback = Some(callback);
1527 }
1528 } else {
1529 break;
1530 }
1531 }
1532 }
1533}
1534
1535fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1536where
1537 F: FnOnce(&mut dyn InputHandler) -> R,
1538{
1539 let window_state = unsafe { get_window_state(window) };
1540 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1541 if let Some(mut input_handler) = window_state_borrow.input_handler.take() {
1542 drop(window_state_borrow);
1543 let result = f(input_handler.as_mut());
1544 window_state.borrow_mut().input_handler = Some(input_handler);
1545 Some(result)
1546 } else {
1547 None
1548 }
1549}