Debian Codegraph @

subprojects/imgui-1.91.6/backends/imgui_impl_osx.mm

raw
1 // dear imgui: Platform Backend for OSX / Cocoa
2 // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..)
3 // - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
4 // - Requires linking with the GameController framework ("-framework GameController").
5
6 // Implemented features:
7 // [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
8 // [X] Platform: Mouse support. Can discriminate Mouse/Pen.
9 // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
10 // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
11 // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12 // [X] Platform: IME support.
13
14 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
15 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
16 // Learn about Dear ImGui:
17 // - FAQ https://dearimgui.com/faq
18 // - Getting Started https://dearimgui.com/getting-started
19 // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
20 // - Introduction, links and more at the top of imgui.cpp
21
22 #import "imgui.h"
23 #ifndef IMGUI_DISABLE
24 #import "imgui_impl_osx.h"
25 #import <Cocoa/Cocoa.h>
26 #import <Carbon/Carbon.h>
27 #import <GameController/GameController.h>
28 #import <time.h>
29
30 // CHANGELOG
31 // (minor and older changes stripped away, please see git history for details)
32 // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
33 // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
34 // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
35 // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
36 // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library.
37 // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen.
38 // 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen.
39 // 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices).
40 // 2022-11-02: Fixed mouse coordinates before clicking the host window.
41 // 2022-10-06: Fixed mouse inputs on flipped views.
42 // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
43 // 2022-05-03: Inputs: Removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture.
44 // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
45 // 2022-03-22: Inputs: Monitor NSKeyUp events to catch missing keyUp for key when user press Cmd + key
46 // 2022-02-07: Inputs: Forward keyDown/keyUp events to OS when unused by dear imgui.
47 // 2022-01-31: Fixed building with old Xcode versions that are missing gamepad features.
48 // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
49 // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
50 // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
51 // 2022-01-12: Inputs: Added basic Platform IME support, hooking the io.SetPlatformImeDataFn() function.
52 // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
53 // 2021-12-13: *BREAKING CHANGE* Add NSView parameter to ImGui_ImplOSX_Init(). Generally fix keyboard support. Using kVK_* codes for keyboard keys.
54 // 2021-12-13: Add game controller support.
55 // 2021-09-21: Use mach_absolute_time as CFAbsoluteTimeGetCurrent can jump backwards.
56 // 2021-08-17: Calling io.AddFocusEvent() on NSApplicationDidBecomeActiveNotification/NSApplicationDidResignActiveNotification events.
57 // 2021-06-23: Inputs: Added a fix for shortcuts using CTRL key instead of CMD key.
58 // 2021-04-19: Inputs: Added a fix for keys remaining stuck in pressed state when CMD-tabbing into different application.
59 // 2021-01-27: Inputs: Added a fix for mouse position not being reported when mouse buttons other than left one are down.
60 // 2020-10-28: Inputs: Added a fix for handling keypad-enter key.
61 // 2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap".
62 // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
63 // 2019-10-11: Inputs: Fix using Backspace key.
64 // 2019-07-21: Re-added clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change).
65 // 2019-05-28: Inputs: Added mouse cursor shape and visibility support.
66 // 2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp.
67 // 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range.
68 // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
69 // 2018-07-07: Initial version.
70
71 #define APPLE_HAS_BUTTON_OPTIONS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 130000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500 || __TV_OS_VERSION_MIN_REQUIRED >= 130000)
72 #define APPLE_HAS_CONTROLLER (__IPHONE_OS_VERSION_MIN_REQUIRED >= 140000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 110000 || __TV_OS_VERSION_MIN_REQUIRED >= 140000)
73 #define APPLE_HAS_THUMBSTICKS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 120100 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101401 || __TV_OS_VERSION_MIN_REQUIRED >= 120100)
74
75 @class ImGuiObserver;
76 @class KeyEventResponder;
77
78 // Data
79 struct ImGui_ImplOSX_Data
80 {
81 CFTimeInterval Time;
82 NSCursor* MouseCursors[ImGuiMouseCursor_COUNT];
83 bool MouseCursorHidden;
84 ImGuiObserver* Observer;
85 KeyEventResponder* KeyEventResponder;
86 NSTextInputContext* InputContext;
87 id Monitor;
88 NSWindow* Window;
89
90 ImGui_ImplOSX_Data() { memset((void*)this, 0, sizeof(*this)); }
91 };
92
93 static ImGui_ImplOSX_Data* ImGui_ImplOSX_GetBackendData() { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; }
94 static void ImGui_ImplOSX_DestroyBackendData() { IM_DELETE(ImGui_ImplOSX_GetBackendData()); }
95
96 static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
97
98 // Forward Declarations
99 static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view);
100 static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view);
101
102 // Undocumented methods for creating cursors.
103 @interface NSCursor()
104 + (id)_windowResizeNorthWestSouthEastCursor;
105 + (id)_windowResizeNorthEastSouthWestCursor;
106 + (id)_windowResizeNorthSouthCursor;
107 + (id)_windowResizeEastWestCursor;
108 @end
109
110 /**
111 KeyEventResponder implements the NSTextInputClient protocol as is required by the macOS text input manager.
112
113 The macOS text input manager is invoked by calling the interpretKeyEvents method from the keyDown method.
114 Keyboard events are then evaluated by the macOS input manager and valid text input is passed back via the
115 insertText:replacementRange method.
116
117 This is the same approach employed by other cross-platform libraries such as SDL2:
118 https://github.com/spurious/SDL-mirror/blob/e17aacbd09e65a4fd1e166621e011e581fb017a8/src/video/cocoa/SDL_cocoakeyboard.m#L53
119 and GLFW:
120 https://github.com/glfw/glfw/blob/b55a517ae0c7b5127dffa79a64f5406021bf9076/src/cocoa_window.m#L722-L723
121 */
122 @interface KeyEventResponder: NSView<NSTextInputClient>
123 @end
124
125 @implementation KeyEventResponder
126 {
127 float _posX;
128 float _posY;
129 NSRect _imeRect;
130 }
131
132 #pragma mark - Public
133
134 - (void)setImePosX:(float)posX imePosY:(float)posY
135 {
136 _posX = posX;
137 _posY = posY;
138 }
139
140 - (void)updateImePosWithView:(NSView *)view
141 {
142 NSWindow* window = view.window;
143 if (!window)
144 return;
145 NSRect contentRect = [window contentRectForFrameRect:window.frame];
146 NSRect rect = NSMakeRect(_posX, contentRect.size.height - _posY, 0, 0);
147 _imeRect = [window convertRectToScreen:rect];
148 }
149
150 - (void)viewDidMoveToWindow
151 {
152 // Ensure self is a first responder to receive the input events.
153 [self.window makeFirstResponder:self];
154 }
155
156 - (void)keyDown:(NSEvent*)event
157 {
158 if (!ImGui_ImplOSX_HandleEvent(event, self))
159 [super keyDown:event];
160
161 // Call to the macOS input manager system.
162 [self interpretKeyEvents:@[event]];
163 }
164
165 - (void)keyUp:(NSEvent*)event
166 {
167 if (!ImGui_ImplOSX_HandleEvent(event, self))
168 [super keyUp:event];
169 }
170
171 - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
172 {
173 ImGuiIO& io = ImGui::GetIO();
174
175 NSString* characters;
176 if ([aString isKindOfClass:[NSAttributedString class]])
177 characters = [aString string];
178 else
179 characters = (NSString*)aString;
180
181 io.AddInputCharactersUTF8(characters.UTF8String);
182 }
183
184 - (BOOL)acceptsFirstResponder
185 {
186 return YES;
187 }
188
189 - (void)doCommandBySelector:(SEL)myselector
190 {
191 }
192
193 - (nullable NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange
194 {
195 return nil;
196 }
197
198 - (NSUInteger)characterIndexForPoint:(NSPoint)point
199 {
200 return 0;
201 }
202
203 - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange
204 {
205 return _imeRect;
206 }
207
208 - (BOOL)hasMarkedText
209 {
210 return NO;
211 }
212
213 - (NSRange)markedRange
214 {
215 return NSMakeRange(NSNotFound, 0);
216 }
217
218 - (NSRange)selectedRange
219 {
220 return NSMakeRange(NSNotFound, 0);
221 }
222
223 - (void)setMarkedText:(nonnull id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
224 {
225 }
226
227 - (void)unmarkText
228 {
229 }
230
231 - (nonnull NSArray<NSAttributedStringKey>*)validAttributesForMarkedText
232 {
233 return @[];
234 }
235
236 @end
237
238 @interface ImGuiObserver : NSObject
239
240 - (void)onApplicationBecomeActive:(NSNotification*)aNotification;
241 - (void)onApplicationBecomeInactive:(NSNotification*)aNotification;
242
243 @end
244
245 @implementation ImGuiObserver
246
247 - (void)onApplicationBecomeActive:(NSNotification*)aNotification
248 {
249 ImGuiIO& io = ImGui::GetIO();
250 io.AddFocusEvent(true);
251 }
252
253 - (void)onApplicationBecomeInactive:(NSNotification*)aNotification
254 {
255 ImGuiIO& io = ImGui::GetIO();
256 io.AddFocusEvent(false);
257 }
258
259 @end
260
261 // Functions
262
263 // Not static to allow third-party code to use that if they want to (but undocumented)
264 ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code);
265 ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
266 {
267 switch (key_code)
268 {
269 case kVK_ANSI_A: return ImGuiKey_A;
270 case kVK_ANSI_S: return ImGuiKey_S;
271 case kVK_ANSI_D: return ImGuiKey_D;
272 case kVK_ANSI_F: return ImGuiKey_F;
273 case kVK_ANSI_H: return ImGuiKey_H;
274 case kVK_ANSI_G: return ImGuiKey_G;
275 case kVK_ANSI_Z: return ImGuiKey_Z;
276 case kVK_ANSI_X: return ImGuiKey_X;
277 case kVK_ANSI_C: return ImGuiKey_C;
278 case kVK_ANSI_V: return ImGuiKey_V;
279 case kVK_ANSI_B: return ImGuiKey_B;
280 case kVK_ANSI_Q: return ImGuiKey_Q;
281 case kVK_ANSI_W: return ImGuiKey_W;
282 case kVK_ANSI_E: return ImGuiKey_E;
283 case kVK_ANSI_R: return ImGuiKey_R;
284 case kVK_ANSI_Y: return ImGuiKey_Y;
285 case kVK_ANSI_T: return ImGuiKey_T;
286 case kVK_ANSI_1: return ImGuiKey_1;
287 case kVK_ANSI_2: return ImGuiKey_2;
288 case kVK_ANSI_3: return ImGuiKey_3;
289 case kVK_ANSI_4: return ImGuiKey_4;
290 case kVK_ANSI_6: return ImGuiKey_6;
291 case kVK_ANSI_5: return ImGuiKey_5;
292 case kVK_ANSI_Equal: return ImGuiKey_Equal;
293 case kVK_ANSI_9: return ImGuiKey_9;
294 case kVK_ANSI_7: return ImGuiKey_7;
295 case kVK_ANSI_Minus: return ImGuiKey_Minus;
296 case kVK_ANSI_8: return ImGuiKey_8;
297 case kVK_ANSI_0: return ImGuiKey_0;
298 case kVK_ANSI_RightBracket: return ImGuiKey_RightBracket;
299 case kVK_ANSI_O: return ImGuiKey_O;
300 case kVK_ANSI_U: return ImGuiKey_U;
301 case kVK_ANSI_LeftBracket: return ImGuiKey_LeftBracket;
302 case kVK_ANSI_I: return ImGuiKey_I;
303 case kVK_ANSI_P: return ImGuiKey_P;
304 case kVK_ANSI_L: return ImGuiKey_L;
305 case kVK_ANSI_J: return ImGuiKey_J;
306 case kVK_ANSI_Quote: return ImGuiKey_Apostrophe;
307 case kVK_ANSI_K: return ImGuiKey_K;
308 case kVK_ANSI_Semicolon: return ImGuiKey_Semicolon;
309 case kVK_ANSI_Backslash: return ImGuiKey_Backslash;
310 case kVK_ANSI_Comma: return ImGuiKey_Comma;
311 case kVK_ANSI_Slash: return ImGuiKey_Slash;
312 case kVK_ANSI_N: return ImGuiKey_N;
313 case kVK_ANSI_M: return ImGuiKey_M;
314 case kVK_ANSI_Period: return ImGuiKey_Period;
315 case kVK_ANSI_Grave: return ImGuiKey_GraveAccent;
316 case kVK_ANSI_KeypadDecimal: return ImGuiKey_KeypadDecimal;
317 case kVK_ANSI_KeypadMultiply: return ImGuiKey_KeypadMultiply;
318 case kVK_ANSI_KeypadPlus: return ImGuiKey_KeypadAdd;
319 case kVK_ANSI_KeypadClear: return ImGuiKey_NumLock;
320 case kVK_ANSI_KeypadDivide: return ImGuiKey_KeypadDivide;
321 case kVK_ANSI_KeypadEnter: return ImGuiKey_KeypadEnter;
322 case kVK_ANSI_KeypadMinus: return ImGuiKey_KeypadSubtract;
323 case kVK_ANSI_KeypadEquals: return ImGuiKey_KeypadEqual;
324 case kVK_ANSI_Keypad0: return ImGuiKey_Keypad0;
325 case kVK_ANSI_Keypad1: return ImGuiKey_Keypad1;
326 case kVK_ANSI_Keypad2: return ImGuiKey_Keypad2;
327 case kVK_ANSI_Keypad3: return ImGuiKey_Keypad3;
328 case kVK_ANSI_Keypad4: return ImGuiKey_Keypad4;
329 case kVK_ANSI_Keypad5: return ImGuiKey_Keypad5;
330 case kVK_ANSI_Keypad6: return ImGuiKey_Keypad6;
331 case kVK_ANSI_Keypad7: return ImGuiKey_Keypad7;
332 case kVK_ANSI_Keypad8: return ImGuiKey_Keypad8;
333 case kVK_ANSI_Keypad9: return ImGuiKey_Keypad9;
334 case kVK_Return: return ImGuiKey_Enter;
335 case kVK_Tab: return ImGuiKey_Tab;
336 case kVK_Space: return ImGuiKey_Space;
337 case kVK_Delete: return ImGuiKey_Backspace;
338 case kVK_Escape: return ImGuiKey_Escape;
339 case kVK_CapsLock: return ImGuiKey_CapsLock;
340 case kVK_Control: return ImGuiKey_LeftCtrl;
341 case kVK_Shift: return ImGuiKey_LeftShift;
342 case kVK_Option: return ImGuiKey_LeftAlt;
343 case kVK_Command: return ImGuiKey_LeftSuper;
344 case kVK_RightControl: return ImGuiKey_RightCtrl;
345 case kVK_RightShift: return ImGuiKey_RightShift;
346 case kVK_RightOption: return ImGuiKey_RightAlt;
347 case kVK_RightCommand: return ImGuiKey_RightSuper;
348 // case kVK_Function: return ImGuiKey_;
349 // case kVK_VolumeUp: return ImGuiKey_;
350 // case kVK_VolumeDown: return ImGuiKey_;
351 // case kVK_Mute: return ImGuiKey_;
352 case kVK_F1: return ImGuiKey_F1;
353 case kVK_F2: return ImGuiKey_F2;
354 case kVK_F3: return ImGuiKey_F3;
355 case kVK_F4: return ImGuiKey_F4;
356 case kVK_F5: return ImGuiKey_F5;
357 case kVK_F6: return ImGuiKey_F6;
358 case kVK_F7: return ImGuiKey_F7;
359 case kVK_F8: return ImGuiKey_F8;
360 case kVK_F9: return ImGuiKey_F9;
361 case kVK_F10: return ImGuiKey_F10;
362 case kVK_F11: return ImGuiKey_F11;
363 case kVK_F12: return ImGuiKey_F12;
364 case kVK_F13: return ImGuiKey_F13;
365 case kVK_F14: return ImGuiKey_F14;
366 case kVK_F15: return ImGuiKey_F15;
367 case kVK_F16: return ImGuiKey_F16;
368 case kVK_F17: return ImGuiKey_F17;
369 case kVK_F18: return ImGuiKey_F18;
370 case kVK_F19: return ImGuiKey_F19;
371 case kVK_F20: return ImGuiKey_F20;
372 case 0x6E: return ImGuiKey_Menu;
373 case kVK_Help: return ImGuiKey_Insert;
374 case kVK_Home: return ImGuiKey_Home;
375 case kVK_PageUp: return ImGuiKey_PageUp;
376 case kVK_ForwardDelete: return ImGuiKey_Delete;
377 case kVK_End: return ImGuiKey_End;
378 case kVK_PageDown: return ImGuiKey_PageDown;
379 case kVK_LeftArrow: return ImGuiKey_LeftArrow;
380 case kVK_RightArrow: return ImGuiKey_RightArrow;
381 case kVK_DownArrow: return ImGuiKey_DownArrow;
382 case kVK_UpArrow: return ImGuiKey_UpArrow;
383 default: return ImGuiKey_None;
384 }
385 }
386
387 #ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS
388
389 IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view) {
390 return ImGui_ImplOSX_Init((__bridge NSView*)(view));
391 }
392
393 IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view) {
394 return ImGui_ImplOSX_NewFrame((__bridge NSView*)(view));
395 }
396
397 #endif
398
399
400 bool ImGui_ImplOSX_Init(NSView* view)
401 {
402 ImGuiIO& io = ImGui::GetIO();
403 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
404 IMGUI_CHECKVERSION();
405 IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
406
407 // Setup backend capabilities flags
408 ImGui_ImplOSX_Data* bd = IM_NEW(ImGui_ImplOSX_Data)();
409 io.BackendPlatformUserData = (void*)bd;
410 io.BackendPlatformName = "imgui_impl_osx";
411 io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
412 //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
413
414 bd->Observer = [ImGuiObserver new];
415 bd->Window = view.window ?: NSApp.orderedWindows.firstObject;
416 ImGuiViewport* main_viewport = ImGui::GetMainViewport();
417 main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (__bridge_retained void*)bd->Window;
418
419 // Load cursors. Some of them are undocumented.
420 bd->MouseCursorHidden = false;
421 bd->MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor];
422 bd->MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor];
423 bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor];
424 bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor];
425 bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor];
426 bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
427 bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
428 bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
429 bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
430
431 // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled
432 // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line.
433 // Since we are already in ObjC land here, it is easy for us to add a clipboard handler using the NSPasteboard api.
434 platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* str) -> void
435 {
436 NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
437 [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
438 [pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString];
439 };
440
441 platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) -> const char*
442 {
443 NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
444 NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]];
445 if (![available isEqualToString:NSPasteboardTypeString])
446 return nullptr;
447
448 NSString* string = [pasteboard stringForType:NSPasteboardTypeString];
449 if (string == nil)
450 return nullptr;
451
452 const char* string_c = (const char*)[string UTF8String];
453 size_t string_len = strlen(string_c);
454 static ImVector<char> s_clipboard;
455 s_clipboard.resize((int)string_len + 1);
456 strcpy(s_clipboard.Data, string_c);
457 return s_clipboard.Data;
458 };
459
460 [[NSNotificationCenter defaultCenter] addObserver:bd->Observer
461 selector:@selector(onApplicationBecomeActive:)
462 name:NSApplicationDidBecomeActiveNotification
463 object:nil];
464 [[NSNotificationCenter defaultCenter] addObserver:bd->Observer
465 selector:@selector(onApplicationBecomeInactive:)
466 name:NSApplicationDidResignActiveNotification
467 object:nil];
468
469 // Add the NSTextInputClient to the view hierarchy,
470 // to receive keyboard events and translate them to input text.
471 bd->KeyEventResponder = [[KeyEventResponder alloc] initWithFrame:NSZeroRect];
472 bd->InputContext = [[NSTextInputContext alloc] initWithClient:bd->KeyEventResponder];
473 [view addSubview:bd->KeyEventResponder];
474 ImGui_ImplOSX_AddTrackingArea(view);
475
476 platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void
477 {
478 ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
479 if (data->WantVisible)
480 {
481 [bd->InputContext activate];
482 }
483 else
484 {
485 [bd->InputContext discardMarkedText];
486 [bd->InputContext invalidateCharacterCoordinates];
487 [bd->InputContext deactivate];
488 }
489 [bd->KeyEventResponder setImePosX:data->InputPos.x imePosY:data->InputPos.y + data->InputLineHeight];
490 };
491
492 return true;
493 }
494
495 void ImGui_ImplOSX_Shutdown()
496 {
497 ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
498 IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
499
500 bd->Observer = nullptr;
501 if (bd->Monitor != nullptr)
502 {
503 [NSEvent removeMonitor:bd->Monitor];
504 bd->Monitor = nullptr;
505 }
506
507 ImGui_ImplOSX_DestroyBackendData();
508
509 ImGuiIO& io = ImGui::GetIO();
510 io.BackendPlatformName = nullptr;
511 io.BackendPlatformUserData = nullptr;
512 io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasGamepad);
513 }
514
515 static void ImGui_ImplOSX_UpdateMouseCursor()
516 {
517 ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
518 ImGuiIO& io = ImGui::GetIO();
519 if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
520 return;
521
522 ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
523 if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
524 {
525 // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
526 if (!bd->MouseCursorHidden)
527 {
528 bd->MouseCursorHidden = true;
529 [NSCursor hide];
530 }
531 }
532 else
533 {
534 NSCursor* desired = bd->MouseCursors[imgui_cursor] ?: bd->MouseCursors[ImGuiMouseCursor_Arrow];
535 // -[NSCursor set] generates measureable overhead if called unconditionally.
536 if (desired != NSCursor.currentCursor)
537 {
538 [desired set];
539 }
540 if (bd->MouseCursorHidden)
541 {
542 bd->MouseCursorHidden = false;
543 [NSCursor unhide];
544 }
545 }
546 }
547
548 static void ImGui_ImplOSX_UpdateGamepads()
549 {
550 ImGuiIO& io = ImGui::GetIO();
551 if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
552 return;
553
554 #if APPLE_HAS_CONTROLLER
555 GCController* controller = GCController.current;
556 #else
557 GCController* controller = GCController.controllers.firstObject;
558 #endif
559 if (controller == nil || controller.extendedGamepad == nil)
560 {
561 io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
562 return;
563 }
564
565 GCExtendedGamepad* gp = controller.extendedGamepad;
566
567 // Update gamepad inputs
568 #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V)
569 #define MAP_BUTTON(KEY_NO, BUTTON_NAME) { io.AddKeyEvent(KEY_NO, gp.BUTTON_NAME.isPressed); }
570 #define MAP_ANALOG(KEY_NO, AXIS_NAME, V0, V1) { float vn = (float)(gp.AXIS_NAME.value - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); }
571 const float thumb_dead_zone = 0.0f;
572
573 #if APPLE_HAS_BUTTON_OPTIONS
574 MAP_BUTTON(ImGuiKey_GamepadBack, buttonOptions);
575 #endif
576 MAP_BUTTON(ImGuiKey_GamepadFaceLeft, buttonX); // Xbox X, PS Square
577 MAP_BUTTON(ImGuiKey_GamepadFaceRight, buttonB); // Xbox B, PS Circle
578 MAP_BUTTON(ImGuiKey_GamepadFaceUp, buttonY); // Xbox Y, PS Triangle
579 MAP_BUTTON(ImGuiKey_GamepadFaceDown, buttonA); // Xbox A, PS Cross
580 MAP_BUTTON(ImGuiKey_GamepadDpadLeft, dpad.left);
581 MAP_BUTTON(ImGuiKey_GamepadDpadRight, dpad.right);
582 MAP_BUTTON(ImGuiKey_GamepadDpadUp, dpad.up);
583 MAP_BUTTON(ImGuiKey_GamepadDpadDown, dpad.down);
584 MAP_ANALOG(ImGuiKey_GamepadL1, leftShoulder, 0.0f, 1.0f);
585 MAP_ANALOG(ImGuiKey_GamepadR1, rightShoulder, 0.0f, 1.0f);
586 MAP_ANALOG(ImGuiKey_GamepadL2, leftTrigger, 0.0f, 1.0f);
587 MAP_ANALOG(ImGuiKey_GamepadR2, rightTrigger, 0.0f, 1.0f);
588 #if APPLE_HAS_THUMBSTICKS
589 MAP_BUTTON(ImGuiKey_GamepadL3, leftThumbstickButton);
590 MAP_BUTTON(ImGuiKey_GamepadR3, rightThumbstickButton);
591 #endif
592 MAP_ANALOG(ImGuiKey_GamepadLStickLeft, leftThumbstick.xAxis, -thumb_dead_zone, -1.0f);
593 MAP_ANALOG(ImGuiKey_GamepadLStickRight, leftThumbstick.xAxis, +thumb_dead_zone, +1.0f);
594 MAP_ANALOG(ImGuiKey_GamepadLStickUp, leftThumbstick.yAxis, +thumb_dead_zone, +1.0f);
595 MAP_ANALOG(ImGuiKey_GamepadLStickDown, leftThumbstick.yAxis, -thumb_dead_zone, -1.0f);
596 MAP_ANALOG(ImGuiKey_GamepadRStickLeft, rightThumbstick.xAxis, -thumb_dead_zone, -1.0f);
597 MAP_ANALOG(ImGuiKey_GamepadRStickRight, rightThumbstick.xAxis, +thumb_dead_zone, +1.0f);
598 MAP_ANALOG(ImGuiKey_GamepadRStickUp, rightThumbstick.yAxis, +thumb_dead_zone, +1.0f);
599 MAP_ANALOG(ImGuiKey_GamepadRStickDown, rightThumbstick.yAxis, -thumb_dead_zone, -1.0f);
600 #undef MAP_BUTTON
601 #undef MAP_ANALOG
602
603 io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
604 }
605
606 static void ImGui_ImplOSX_UpdateImePosWithView(NSView* view)
607 {
608 ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
609 ImGuiIO& io = ImGui::GetIO();
610 if (io.WantTextInput)
611 [bd->KeyEventResponder updateImePosWithView:view];
612 }
613
614 void ImGui_ImplOSX_NewFrame(NSView* view)
615 {
616 ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
617 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOSX_Init()?");
618 ImGuiIO& io = ImGui::GetIO();
619
620 // Setup display size
621 if (view)
622 {
623 const float dpi = (float)[view.window backingScaleFactor];
624 io.DisplaySize = ImVec2((float)view.bounds.size.width, (float)view.bounds.size.height);
625 io.DisplayFramebufferScale = ImVec2(dpi, dpi);
626 }
627
628 // Setup time step
629 if (bd->Time == 0.0)
630 bd->Time = GetMachAbsoluteTimeInSeconds();
631
632 double current_time = GetMachAbsoluteTimeInSeconds();
633 io.DeltaTime = (float)(current_time - bd->Time);
634 bd->Time = current_time;
635
636 ImGui_ImplOSX_UpdateMouseCursor();
637 ImGui_ImplOSX_UpdateGamepads();
638 ImGui_ImplOSX_UpdateImePosWithView(view);
639 }
640
641 // Must only be called for a mouse event, otherwise an exception occurs
642 // (Note that NSEventTypeScrollWheel is considered "other input". Oddly enough an exception does not occur with it, but the value will sometimes be wrong!)
643 static ImGuiMouseSource GetMouseSource(NSEvent* event)
644 {
645 switch (event.subtype)
646 {
647 case NSEventSubtypeTabletPoint:
648 return ImGuiMouseSource_Pen;
649 // macOS considers input from relative touch devices (like the trackpad or Apple Magic Mouse) to be touch input.
650 // This doesn't really make sense for Dear ImGui, which expects absolute touch devices only.
651 // There does not seem to be a simple way to disambiguate things here so we consider NSEventSubtypeTouch events to always come from mice.
652 // See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW24
653 //case NSEventSubtypeTouch:
654 // return ImGuiMouseSource_TouchScreen;
655 case NSEventSubtypeMouseEvent:
656 default:
657 return ImGuiMouseSource_Mouse;
658 }
659 }
660
661 static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view)
662 {
663 ImGuiIO& io = ImGui::GetIO();
664
665 if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown)
666 {
667 int button = (int)[event buttonNumber];
668 if (button >= 0 && button < ImGuiMouseButton_COUNT)
669 {
670 io.AddMouseSourceEvent(GetMouseSource(event));
671 io.AddMouseButtonEvent(button, true);
672 }
673 return io.WantCaptureMouse;
674 }
675
676 if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp)
677 {
678 int button = (int)[event buttonNumber];
679 if (button >= 0 && button < ImGuiMouseButton_COUNT)
680 {
681 io.AddMouseSourceEvent(GetMouseSource(event));
682 io.AddMouseButtonEvent(button, false);
683 }
684 return io.WantCaptureMouse;
685 }
686
687 if (event.type == NSEventTypeMouseMoved || event.type == NSEventTypeLeftMouseDragged || event.type == NSEventTypeRightMouseDragged || event.type == NSEventTypeOtherMouseDragged)
688 {
689 NSPoint mousePoint = event.locationInWindow;
690 if (event.window == nil)
691 mousePoint = [[view window] convertPointFromScreen:mousePoint];
692 mousePoint = [view convertPoint:mousePoint fromView:nil];
693 if ([view isFlipped])
694 mousePoint = NSMakePoint(mousePoint.x, mousePoint.y);
695 else
696 mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y);
697 io.AddMouseSourceEvent(GetMouseSource(event));
698 io.AddMousePosEvent((float)mousePoint.x, (float)mousePoint.y);
699 return io.WantCaptureMouse;
700 }
701
702 if (event.type == NSEventTypeScrollWheel)
703 {
704 // Ignore canceled events.
705 //
706 // From macOS 12.1, scrolling with two fingers and then decelerating
707 // by tapping two fingers results in two events appearing:
708 //
709 // 1. A scroll wheel NSEvent, with a phase == NSEventPhaseMayBegin, when the user taps
710 // two fingers to decelerate or stop the scroll events.
711 //
712 // 2. A scroll wheel NSEvent, with a phase == NSEventPhaseCancelled, when the user releases the
713 // two-finger tap. It is this event that sometimes contains large values for scrollingDeltaX and
714 // scrollingDeltaY. When these are added to the current x and y positions of the scrolling view,
715 // it appears to jump up or down. It can be observed in Preview, various JetBrains IDEs and here.
716 if (event.phase == NSEventPhaseCancelled)
717 return false;
718
719 double wheel_dx = 0.0;
720 double wheel_dy = 0.0;
721
722 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
723 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
724 {
725 wheel_dx = [event scrollingDeltaX];
726 wheel_dy = [event scrollingDeltaY];
727 if ([event hasPreciseScrollingDeltas])
728 {
729 wheel_dx *= 0.01;
730 wheel_dy *= 0.01;
731 }
732 }
733 else
734 #endif // MAC_OS_X_VERSION_MAX_ALLOWED
735 {
736 wheel_dx = [event deltaX] * 0.1;
737 wheel_dy = [event deltaY] * 0.1;
738 }
739 if (wheel_dx != 0.0 || wheel_dy != 0.0)
740 io.AddMouseWheelEvent((float)wheel_dx, (float)wheel_dy);
741
742 return io.WantCaptureMouse;
743 }
744
745 if (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp)
746 {
747 if ([event isARepeat])
748 return io.WantCaptureKeyboard;
749
750 int key_code = (int)[event keyCode];
751 ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code);
752 io.AddKeyEvent(key, event.type == NSEventTypeKeyDown);
753 io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code)
754
755 return io.WantCaptureKeyboard;
756 }
757
758 if (event.type == NSEventTypeFlagsChanged)
759 {
760 unsigned short key_code = [event keyCode];
761 NSEventModifierFlags modifier_flags = [event modifierFlags];
762
763 io.AddKeyEvent(ImGuiMod_Shift, (modifier_flags & NSEventModifierFlagShift) != 0);
764 io.AddKeyEvent(ImGuiMod_Ctrl, (modifier_flags & NSEventModifierFlagControl) != 0);
765 io.AddKeyEvent(ImGuiMod_Alt, (modifier_flags & NSEventModifierFlagOption) != 0);
766 io.AddKeyEvent(ImGuiMod_Super, (modifier_flags & NSEventModifierFlagCommand) != 0);
767
768 ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code);
769 if (key != ImGuiKey_None)
770 {
771 // macOS does not generate down/up event for modifiers. We're trying
772 // to use hardware dependent masks to extract that information.
773 // 'imgui_mask' is left as a fallback.
774 NSEventModifierFlags mask = 0;
775 switch (key)
776 {
777 case ImGuiKey_LeftCtrl: mask = 0x0001; break;
778 case ImGuiKey_RightCtrl: mask = 0x2000; break;
779 case ImGuiKey_LeftShift: mask = 0x0002; break;
780 case ImGuiKey_RightShift: mask = 0x0004; break;
781 case ImGuiKey_LeftSuper: mask = 0x0008; break;
782 case ImGuiKey_RightSuper: mask = 0x0010; break;
783 case ImGuiKey_LeftAlt: mask = 0x0020; break;
784 case ImGuiKey_RightAlt: mask = 0x0040; break;
785 default:
786 return io.WantCaptureKeyboard;
787 }
788
789 NSEventModifierFlags modifier_flags = [event modifierFlags];
790 io.AddKeyEvent(key, (modifier_flags & mask) != 0);
791 io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code)
792 }
793
794 return io.WantCaptureKeyboard;
795 }
796
797 return false;
798 }
799
800 static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view)
801 {
802 // If we want to receive key events, we either need to be in the responder chain of the key view,
803 // or else we can install a local monitor. The consequence of this heavy-handed approach is that
804 // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our
805 // window, we'd want to be much more careful than just ingesting the complete event stream.
806 // To match the behavior of other backends, we pass every event down to the OS.
807 ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
808 if (bd->Monitor)
809 return;
810 NSEventMask eventMask = 0;
811 eventMask |= NSEventMaskMouseMoved | NSEventMaskScrollWheel;
812 eventMask |= NSEventMaskLeftMouseDown | NSEventMaskLeftMouseUp | NSEventMaskLeftMouseDragged;
813 eventMask |= NSEventMaskRightMouseDown | NSEventMaskRightMouseUp | NSEventMaskRightMouseDragged;
814 eventMask |= NSEventMaskOtherMouseDown | NSEventMaskOtherMouseUp | NSEventMaskOtherMouseDragged;
815 eventMask |= NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
816 bd->Monitor = [NSEvent addLocalMonitorForEventsMatchingMask:eventMask
817 handler:^NSEvent* _Nullable(NSEvent* event)
818 {
819 ImGui_ImplOSX_HandleEvent(event, view);
820 return event;
821 }];
822 }
823
824 //-----------------------------------------------------------------------------
825
826 #endif // #ifndef IMGUI_DISABLE