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, Modifiers, ModifiersChangedEvent, MouseButton,
14 MouseButtonEvent, 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
1057 if let Some(mut event) = event {
1058 let synthesized_second_event = match &mut event {
1059 Event::MouseDown(
1060 event @ MouseButtonEvent {
1061 button: MouseButton::Left,
1062 modifiers: Modifiers { ctrl: true, .. },
1063 ..
1064 },
1065 ) => {
1066 *event = MouseButtonEvent {
1067 button: MouseButton::Right,
1068 modifiers: Modifiers {
1069 ctrl: false,
1070 ..event.modifiers
1071 },
1072 click_count: 1,
1073 ..*event
1074 };
1075
1076 Some(Event::MouseUp(MouseButtonEvent {
1077 button: MouseButton::Right,
1078 ..*event
1079 }))
1080 }
1081
1082 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1083 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1084 // user is still holding ctrl when releasing the left mouse button
1085 Event::MouseUp(MouseButtonEvent {
1086 button: MouseButton::Left,
1087 modifiers: Modifiers { ctrl: true, .. },
1088 ..
1089 }) => return,
1090
1091 _ => None,
1092 };
1093
1094 match &event {
1095 Event::MouseMoved(
1096 event @ MouseMovedEvent {
1097 pressed_button: Some(_),
1098 ..
1099 },
1100 ) => {
1101 window_state_borrow.synthetic_drag_counter += 1;
1102 window_state_borrow
1103 .executor
1104 .spawn(synthetic_drag(
1105 weak_window_state,
1106 window_state_borrow.synthetic_drag_counter,
1107 *event,
1108 ))
1109 .detach();
1110 }
1111
1112 Event::MouseMoved(_)
1113 if !(is_active || window_state_borrow.kind == WindowKind::PopUp) =>
1114 {
1115 return
1116 }
1117
1118 Event::MouseUp(MouseButtonEvent {
1119 button: MouseButton::Left,
1120 ..
1121 }) => {
1122 window_state_borrow.synthetic_drag_counter += 1;
1123 }
1124
1125 Event::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1126 // Only raise modifiers changed event when they have actually changed
1127 if let Some(Event::ModifiersChanged(ModifiersChangedEvent {
1128 modifiers: prev_modifiers,
1129 })) = &window_state_borrow.previous_modifiers_changed_event
1130 {
1131 if prev_modifiers == modifiers {
1132 return;
1133 }
1134 }
1135
1136 window_state_borrow.previous_modifiers_changed_event = Some(event.clone());
1137 }
1138
1139 _ => {}
1140 }
1141
1142 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1143 drop(window_state_borrow);
1144 callback(event);
1145 if let Some(event) = synthesized_second_event {
1146 callback(event);
1147 }
1148 window_state.borrow_mut().event_callback = Some(callback);
1149 }
1150 }
1151}
1152
1153// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1154// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1155extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1156 let window_state = unsafe { get_window_state(this) };
1157 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1158
1159 let keystroke = Keystroke {
1160 cmd: true,
1161 ctrl: false,
1162 alt: false,
1163 shift: false,
1164 function: false,
1165 key: ".".into(),
1166 };
1167 let event = Event::KeyDown(KeyDownEvent {
1168 keystroke: keystroke.clone(),
1169 is_held: false,
1170 });
1171
1172 window_state_borrow.last_fresh_keydown = Some(keystroke);
1173 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1174 drop(window_state_borrow);
1175 callback(event);
1176 window_state.borrow_mut().event_callback = Some(callback);
1177 }
1178}
1179
1180extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1181 let window_state = unsafe { get_window_state(this) };
1182 window_state.as_ref().borrow().move_traffic_light();
1183}
1184
1185extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1186 window_fullscreen_changed(this, true);
1187}
1188
1189extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1190 window_fullscreen_changed(this, false);
1191}
1192
1193fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1194 let window_state = unsafe { get_window_state(this) };
1195 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1196 if let Some(mut callback) = window_state_borrow.fullscreen_callback.take() {
1197 drop(window_state_borrow);
1198 callback(is_fullscreen);
1199 window_state.borrow_mut().fullscreen_callback = Some(callback);
1200 }
1201}
1202
1203extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1204 let window_state = unsafe { get_window_state(this) };
1205 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1206 if let Some(mut callback) = window_state_borrow.moved_callback.take() {
1207 drop(window_state_borrow);
1208 callback();
1209 window_state.borrow_mut().moved_callback = Some(callback);
1210 }
1211}
1212
1213extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1214 let window_state = unsafe { get_window_state(this) };
1215 let window_state_borrow = window_state.borrow();
1216 let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1217
1218 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1219 // `windowDidBecomeKey` message to the previous key window even though that window
1220 // isn't actually key. This causes a bug if the application is later activated while
1221 // the pop-up is still open, making it impossible to activate the previous key window
1222 // even if the pop-up gets closed. The only way to activate it again is to de-activate
1223 // the app and re-activate it, which is a pretty bad UX.
1224 // The following code detects the spurious event and invokes `resignKeyWindow`:
1225 // in theory, we're not supposed to invoke this method manually but it balances out
1226 // the spurious `becomeKeyWindow` event and helps us work around that bug.
1227 if selector == sel!(windowDidBecomeKey:) {
1228 if !is_active {
1229 unsafe {
1230 let _: () = msg_send![window_state_borrow.native_window, resignKeyWindow];
1231 return;
1232 }
1233 }
1234 }
1235
1236 let executor = window_state_borrow.executor.clone();
1237 drop(window_state_borrow);
1238 executor
1239 .spawn(async move {
1240 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1241 if let Some(mut callback) = window_state_borrow.activate_callback.take() {
1242 drop(window_state_borrow);
1243 callback(is_active);
1244 window_state.borrow_mut().activate_callback = Some(callback);
1245 };
1246 })
1247 .detach();
1248}
1249
1250extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1251 let window_state = unsafe { get_window_state(this) };
1252 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1253 if let Some(mut callback) = window_state_borrow.should_close_callback.take() {
1254 drop(window_state_borrow);
1255 let should_close = callback();
1256 window_state.borrow_mut().should_close_callback = Some(callback);
1257 should_close as BOOL
1258 } else {
1259 YES
1260 }
1261}
1262
1263extern "C" fn close_window(this: &Object, _: Sel) {
1264 unsafe {
1265 let close_callback = {
1266 let window_state = get_window_state(this);
1267 window_state
1268 .as_ref()
1269 .try_borrow_mut()
1270 .ok()
1271 .and_then(|mut window_state| window_state.close_callback.take())
1272 };
1273
1274 if let Some(callback) = close_callback {
1275 callback();
1276 }
1277
1278 let _: () = msg_send![super(this, class!(NSWindow)), close];
1279 }
1280}
1281
1282extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1283 let window_state = unsafe { get_window_state(this) };
1284 let window_state = window_state.as_ref().borrow();
1285 window_state.renderer.layer().as_ptr() as id
1286}
1287
1288extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1289 let window_state = unsafe { get_window_state(this) };
1290 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1291
1292 unsafe {
1293 let scale_factor = window_state_borrow.scale_factor() as f64;
1294 let size = window_state_borrow.content_size();
1295 let drawable_size: NSSize = NSSize {
1296 width: size.x() as f64 * scale_factor,
1297 height: size.y() as f64 * scale_factor,
1298 };
1299
1300 let _: () = msg_send![
1301 window_state_borrow.renderer.layer(),
1302 setContentsScale: scale_factor
1303 ];
1304 let _: () = msg_send![
1305 window_state_borrow.renderer.layer(),
1306 setDrawableSize: drawable_size
1307 ];
1308 }
1309
1310 if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1311 drop(window_state_borrow);
1312 callback();
1313 window_state.as_ref().borrow_mut().resize_callback = Some(callback);
1314 };
1315}
1316
1317extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1318 let window_state = unsafe { get_window_state(this) };
1319 let window_state_borrow = window_state.as_ref().borrow();
1320
1321 if window_state_borrow.content_size() == vec2f(size.width as f32, size.height as f32) {
1322 return;
1323 }
1324
1325 unsafe {
1326 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1327 }
1328
1329 let scale_factor = window_state_borrow.scale_factor() as f64;
1330 let drawable_size: NSSize = NSSize {
1331 width: size.width * scale_factor,
1332 height: size.height * scale_factor,
1333 };
1334
1335 unsafe {
1336 let _: () = msg_send![
1337 window_state_borrow.renderer.layer(),
1338 setDrawableSize: drawable_size
1339 ];
1340 }
1341
1342 drop(window_state_borrow);
1343 let mut window_state_borrow = window_state.borrow_mut();
1344 if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1345 drop(window_state_borrow);
1346 callback();
1347 window_state.borrow_mut().resize_callback = Some(callback);
1348 };
1349}
1350
1351extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1352 unsafe {
1353 let window_state = get_window_state(this);
1354 let mut window_state = window_state.as_ref().borrow_mut();
1355 if let Some(scene) = window_state.scene_to_render.take() {
1356 window_state.renderer.render(&scene);
1357 };
1358 }
1359}
1360
1361extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1362 unsafe { msg_send![class!(NSArray), array] }
1363}
1364
1365extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1366 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1367 .flatten()
1368 .is_some() as BOOL
1369}
1370
1371extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1372 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1373 .flatten()
1374 .map_or(NSRange::invalid(), |range| range.into())
1375}
1376
1377extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1378 with_input_handler(this, |input_handler| input_handler.selected_text_range())
1379 .flatten()
1380 .map_or(NSRange::invalid(), |range| range.into())
1381}
1382
1383extern "C" fn first_rect_for_character_range(
1384 this: &Object,
1385 _: Sel,
1386 range: NSRange,
1387 _: id,
1388) -> NSRect {
1389 let frame = unsafe {
1390 let window = get_window_state(this).borrow().native_window;
1391 NSView::frame(window)
1392 };
1393 with_input_handler(this, |input_handler| {
1394 input_handler.rect_for_range(range.to_range()?)
1395 })
1396 .flatten()
1397 .map_or(
1398 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1399 |rect| {
1400 NSRect::new(
1401 NSPoint::new(
1402 frame.origin.x + rect.origin_x() as f64,
1403 frame.origin.y + frame.size.height - rect.origin_y() as f64,
1404 ),
1405 NSSize::new(rect.width() as f64, rect.height() as f64),
1406 )
1407 },
1408 )
1409}
1410
1411extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1412 unsafe {
1413 let window_state = get_window_state(this);
1414 let mut window_state_borrow = window_state.borrow_mut();
1415 let pending_key_down = window_state_borrow.pending_key_down.take();
1416 drop(window_state_borrow);
1417
1418 let is_attributed_string: BOOL =
1419 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1420 let text: id = if is_attributed_string == YES {
1421 msg_send![text, string]
1422 } else {
1423 text
1424 };
1425 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1426 .to_str()
1427 .unwrap();
1428 let replacement_range = replacement_range.to_range();
1429
1430 window_state.borrow_mut().ime_text = Some(text.to_string());
1431 window_state.borrow_mut().ime_state = ImeState::Acted;
1432
1433 let is_composing =
1434 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1435 .flatten()
1436 .is_some();
1437
1438 if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1439 with_input_handler(this, |input_handler| {
1440 input_handler.replace_text_in_range(replacement_range, text)
1441 });
1442 } else {
1443 let mut pending_key_down = pending_key_down.unwrap();
1444 pending_key_down.1 = Some(InsertText {
1445 replacement_range,
1446 text: text.to_string(),
1447 });
1448 window_state.borrow_mut().pending_key_down = Some(pending_key_down);
1449 }
1450 }
1451}
1452
1453extern "C" fn set_marked_text(
1454 this: &Object,
1455 _: Sel,
1456 text: id,
1457 selected_range: NSRange,
1458 replacement_range: NSRange,
1459) {
1460 unsafe {
1461 let window_state = get_window_state(this);
1462 window_state.borrow_mut().pending_key_down.take();
1463
1464 let is_attributed_string: BOOL =
1465 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1466 let text: id = if is_attributed_string == YES {
1467 msg_send![text, string]
1468 } else {
1469 text
1470 };
1471 let selected_range = selected_range.to_range();
1472 let replacement_range = replacement_range.to_range();
1473 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1474 .to_str()
1475 .unwrap();
1476
1477 window_state.borrow_mut().ime_state = ImeState::Acted;
1478 window_state.borrow_mut().ime_text = Some(text.to_string());
1479
1480 with_input_handler(this, |input_handler| {
1481 input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1482 });
1483 }
1484}
1485
1486extern "C" fn unmark_text(this: &Object, _: Sel) {
1487 unsafe {
1488 let state = get_window_state(this);
1489 let mut borrow = state.borrow_mut();
1490 borrow.ime_state = ImeState::Acted;
1491 borrow.ime_text.take();
1492 }
1493
1494 with_input_handler(this, |input_handler| input_handler.unmark_text());
1495}
1496
1497extern "C" fn attributed_substring_for_proposed_range(
1498 this: &Object,
1499 _: Sel,
1500 range: NSRange,
1501 _actual_range: *mut c_void,
1502) -> id {
1503 with_input_handler(this, |input_handler| {
1504 let range = range.to_range()?;
1505 if range.is_empty() {
1506 return None;
1507 }
1508
1509 let selected_text = input_handler.text_for_range(range)?;
1510 unsafe {
1511 let string: id = msg_send![class!(NSAttributedString), alloc];
1512 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1513 Some(string)
1514 }
1515 })
1516 .flatten()
1517 .unwrap_or(nil)
1518}
1519
1520extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1521 unsafe {
1522 let state = get_window_state(this);
1523 let mut borrow = state.borrow_mut();
1524 borrow.ime_state = ImeState::Continue;
1525 borrow.ime_text.take();
1526 }
1527}
1528
1529extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1530 unsafe {
1531 let state = get_window_state(this);
1532 let mut state_borrow = state.as_ref().borrow_mut();
1533 if let Some(mut callback) = state_borrow.appearance_changed_callback.take() {
1534 drop(state_borrow);
1535 callback();
1536 state.borrow_mut().appearance_changed_callback = Some(callback);
1537 }
1538 }
1539}
1540
1541extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1542 unsafe {
1543 let state = get_window_state(this);
1544 let state_borrow = state.as_ref().borrow();
1545 return if state_borrow.kind == WindowKind::PopUp {
1546 YES
1547 } else {
1548 NO
1549 };
1550 }
1551}
1552
1553async fn synthetic_drag(
1554 window_state: Weak<RefCell<WindowState>>,
1555 drag_id: usize,
1556 event: MouseMovedEvent,
1557) {
1558 loop {
1559 Timer::after(Duration::from_millis(16)).await;
1560 if let Some(window_state) = window_state.upgrade() {
1561 let mut window_state_borrow = window_state.borrow_mut();
1562 if window_state_borrow.synthetic_drag_counter == drag_id {
1563 if let Some(mut callback) = window_state_borrow.event_callback.take() {
1564 drop(window_state_borrow);
1565 callback(Event::MouseMoved(event));
1566 window_state.borrow_mut().event_callback = Some(callback);
1567 }
1568 } else {
1569 break;
1570 }
1571 }
1572 }
1573}
1574
1575fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1576where
1577 F: FnOnce(&mut dyn InputHandler) -> R,
1578{
1579 let window_state = unsafe { get_window_state(window) };
1580 let mut window_state_borrow = window_state.as_ref().borrow_mut();
1581 if let Some(mut input_handler) = window_state_borrow.input_handler.take() {
1582 drop(window_state_borrow);
1583 let result = f(input_handler.as_mut());
1584 window_state.borrow_mut().input_handler = Some(input_handler);
1585 Some(result)
1586 } else {
1587 None
1588 }
1589}