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// [ALPHA] Early backend, not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
4
5// Implemented features:
6//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
7//  [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend).
8// Issues:
9//  [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters]..
10//  [ ] Platform: Multi-viewport / platform windows.
11
12// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
13// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
14// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
15// Read online: https://github.com/ocornut/imgui/tree/master/docs
16
17#include "imgui.h"
18#include "imgui_impl_osx.h"
19#import <Cocoa/Cocoa.h>
20
21// CHANGELOG
22// (minor and older changes stripped away, please see git history for details)
23//  2021-06-23: Inputs: Added a fix for shortcuts using CTRL key instead of CMD key.
24//  2021-04-19: Inputs: Added a fix for keys remaining stuck in pressed state when CMD-tabbing into different application.
25//  2021-01-27: Inputs: Added a fix for mouse position not being reported when mouse buttons other than left one are down.
26//  2020-10-28: Inputs: Added a fix for handling keypad-enter key.
27//  2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap".
28//  2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
29//  2019-10-11: Inputs:  Fix using Backspace key.
30//  2019-07-21: Re-added clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change).
31//  2019-05-28: Inputs: Added mouse cursor shape and visibility support.
32//  2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp.
33//  2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range.
34//  2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
35//  2018-07-07: Initial version.
36
37@class ImFocusObserver;
38
39// Data
40static CFAbsoluteTime g_Time = 0.0;
41static NSCursor*      g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
42static bool           g_MouseCursorHidden = false;
43static bool           g_MouseJustPressed[ImGuiMouseButton_COUNT] = {};
44static bool           g_MouseDown[ImGuiMouseButton_COUNT] = {};
45static ImFocusObserver* g_FocusObserver = NULL;
46
47// Undocumented methods for creating cursors.
48@interface NSCursor()
49+ (id)_windowResizeNorthWestSouthEastCursor;
50+ (id)_windowResizeNorthEastSouthWestCursor;
51+ (id)_windowResizeNorthSouthCursor;
52+ (id)_windowResizeEastWestCursor;
53@end
54
55static void resetKeys()
56{
57    ImGuiIO& io = ImGui::GetIO();
58    memset(io.KeysDown, 0, sizeof(io.KeysDown));
59    io.KeyCtrl = io.KeyShift = io.KeyAlt = io.KeySuper = false;
60}
61
62@interface ImFocusObserver : NSObject
63
64- (void)onApplicationBecomeInactive:(NSNotification*)aNotification;
65
66@end
67
68@implementation ImFocusObserver
69
70- (void)onApplicationBecomeInactive:(NSNotification*)aNotification
71{
72    // Unfocused applications do not receive input events, therefore we must manually
73    // release any pressed keys when application loses focus, otherwise they would remain
74    // stuck in a pressed state. https://github.com/ocornut/imgui/issues/3832
75    resetKeys();
76}
77
78@end
79
80// Functions
81bool ImGui_ImplOSX_Init()
82{
83    ImGuiIO& io = ImGui::GetIO();
84
85    // Setup backend capabilities flags
86    io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;           // We can honor GetMouseCursor() values (optional)
87    //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;          // We can honor io.WantSetMousePos requests (optional, rarely used)
88    //io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports;    // We can create multi-viewports on the Platform side (optional)
89    //io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy)
90    io.BackendPlatformName = "imgui_impl_osx";
91
92    // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeyDown[] array.
93    const int offset_for_function_keys = 256 - 0xF700;
94    io.KeyMap[ImGuiKey_Tab]             = '\t';
95    io.KeyMap[ImGuiKey_LeftArrow]       = NSLeftArrowFunctionKey + offset_for_function_keys;
96    io.KeyMap[ImGuiKey_RightArrow]      = NSRightArrowFunctionKey + offset_for_function_keys;
97    io.KeyMap[ImGuiKey_UpArrow]         = NSUpArrowFunctionKey + offset_for_function_keys;
98    io.KeyMap[ImGuiKey_DownArrow]       = NSDownArrowFunctionKey + offset_for_function_keys;
99    io.KeyMap[ImGuiKey_PageUp]          = NSPageUpFunctionKey + offset_for_function_keys;
100    io.KeyMap[ImGuiKey_PageDown]        = NSPageDownFunctionKey + offset_for_function_keys;
101    io.KeyMap[ImGuiKey_Home]            = NSHomeFunctionKey + offset_for_function_keys;
102    io.KeyMap[ImGuiKey_End]             = NSEndFunctionKey + offset_for_function_keys;
103    io.KeyMap[ImGuiKey_Insert]          = NSInsertFunctionKey + offset_for_function_keys;
104    io.KeyMap[ImGuiKey_Delete]          = NSDeleteFunctionKey + offset_for_function_keys;
105    io.KeyMap[ImGuiKey_Backspace]       = 127;
106    io.KeyMap[ImGuiKey_Space]           = 32;
107    io.KeyMap[ImGuiKey_Enter]           = 13;
108    io.KeyMap[ImGuiKey_Escape]          = 27;
109    io.KeyMap[ImGuiKey_KeyPadEnter]     = 3;
110    io.KeyMap[ImGuiKey_A]               = 'A';
111    io.KeyMap[ImGuiKey_C]               = 'C';
112    io.KeyMap[ImGuiKey_V]               = 'V';
113    io.KeyMap[ImGuiKey_X]               = 'X';
114    io.KeyMap[ImGuiKey_Y]               = 'Y';
115    io.KeyMap[ImGuiKey_Z]               = 'Z';
116
117    // Load cursors. Some of them are undocumented.
118    g_MouseCursorHidden = false;
119    g_MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor];
120    g_MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor];
121    g_MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor];
122    g_MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor];
123    g_MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor];
124    g_MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
125    g_MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
126    g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
127    g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
128
129    // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled
130    // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line.
131    // Since we are already in ObjC land here, it is easy for us to add a clipboard handler using the NSPasteboard api.
132    io.SetClipboardTextFn = [](void*, const char* str) -> void
133    {
134        NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
135        [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
136        [pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString];
137    };
138
139    io.GetClipboardTextFn = [](void*) -> const char*
140    {
141        NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
142        NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]];
143        if (![available isEqualToString:NSPasteboardTypeString])
144            return NULL;
145
146        NSString* string = [pasteboard stringForType:NSPasteboardTypeString];
147        if (string == nil)
148            return NULL;
149
150        const char* string_c = (const char*)[string UTF8String];
151        size_t string_len = strlen(string_c);
152        static ImVector<char> s_clipboard;
153        s_clipboard.resize((int)string_len + 1);
154        strcpy(s_clipboard.Data, string_c);
155        return s_clipboard.Data;
156    };
157
158    g_FocusObserver = [[ImFocusObserver alloc] init];
159    [[NSNotificationCenter defaultCenter] addObserver:g_FocusObserver
160                                             selector:@selector(onApplicationBecomeInactive:)
161                                                 name:NSApplicationDidResignActiveNotification
162                                               object:nil];
163
164    return true;
165}
166
167void ImGui_ImplOSX_Shutdown()
168{
169    g_FocusObserver = NULL;
170}
171
172static void ImGui_ImplOSX_UpdateMouseCursorAndButtons()
173{
174    // Update buttons
175    ImGuiIO& io = ImGui::GetIO();
176    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
177    {
178        // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
179        io.MouseDown[i] = g_MouseJustPressed[i] || g_MouseDown[i];
180        g_MouseJustPressed[i] = false;
181    }
182
183    if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
184        return;
185
186    ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
187    if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
188    {
189        // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
190        if (!g_MouseCursorHidden)
191        {
192            g_MouseCursorHidden = true;
193            [NSCursor hide];
194        }
195    }
196    else
197    {
198        // Show OS mouse cursor
199        [g_MouseCursors[g_MouseCursors[imgui_cursor] ? imgui_cursor : ImGuiMouseCursor_Arrow] set];
200        if (g_MouseCursorHidden)
201        {
202            g_MouseCursorHidden = false;
203            [NSCursor unhide];
204        }
205    }
206}
207
208void ImGui_ImplOSX_NewFrame(NSView* view)
209{
210    // Setup display size
211    ImGuiIO& io = ImGui::GetIO();
212    if (view)
213    {
214        const float dpi = (float)[view.window backingScaleFactor];
215        io.DisplaySize = ImVec2((float)view.bounds.size.width, (float)view.bounds.size.height);
216        io.DisplayFramebufferScale = ImVec2(dpi, dpi);
217    }
218
219    // Setup time step
220    if (g_Time == 0.0)
221        g_Time = CFAbsoluteTimeGetCurrent();
222    CFAbsoluteTime current_time = CFAbsoluteTimeGetCurrent();
223    io.DeltaTime = (float)(current_time - g_Time);
224    g_Time = current_time;
225
226    ImGui_ImplOSX_UpdateMouseCursorAndButtons();
227}
228
229static int mapCharacterToKey(int c)
230{
231    if (c >= 'a' && c <= 'z')
232        return c - 'a' + 'A';
233    if (c == 25) // SHIFT+TAB -> TAB
234        return 9;
235    if (c >= 0 && c < 256)
236        return c;
237    if (c >= 0xF700 && c < 0xF700 + 256)
238        return c - 0xF700 + 256;
239    return -1;
240}
241
242bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view)
243{
244    ImGuiIO& io = ImGui::GetIO();
245
246    if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown)
247    {
248        int button = (int)[event buttonNumber];
249        if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown))
250            g_MouseDown[button] = g_MouseJustPressed[button] = true;
251        return io.WantCaptureMouse;
252    }
253
254    if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp)
255    {
256        int button = (int)[event buttonNumber];
257        if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown))
258            g_MouseDown[button] = false;
259        return io.WantCaptureMouse;
260    }
261
262    if (event.type == NSEventTypeMouseMoved || event.type == NSEventTypeLeftMouseDragged || event.type == NSEventTypeRightMouseDragged || event.type == NSEventTypeOtherMouseDragged)
263    {
264        NSPoint mousePoint = event.locationInWindow;
265        mousePoint = [view convertPoint:mousePoint fromView:nil];
266        mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y);
267        io.MousePos = ImVec2((float)mousePoint.x, (float)mousePoint.y);
268    }
269
270    if (event.type == NSEventTypeScrollWheel)
271    {
272        double wheel_dx = 0.0;
273        double wheel_dy = 0.0;
274
275        #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
276        if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
277        {
278            wheel_dx = [event scrollingDeltaX];
279            wheel_dy = [event scrollingDeltaY];
280            if ([event hasPreciseScrollingDeltas])
281            {
282                wheel_dx *= 0.1;
283                wheel_dy *= 0.1;
284            }
285        }
286        else
287        #endif // MAC_OS_X_VERSION_MAX_ALLOWED
288        {
289            wheel_dx = [event deltaX];
290            wheel_dy = [event deltaY];
291        }
292
293        if (fabs(wheel_dx) > 0.0)
294            io.MouseWheelH += (float)wheel_dx * 0.1f;
295        if (fabs(wheel_dy) > 0.0)
296            io.MouseWheel += (float)wheel_dy * 0.1f;
297        return io.WantCaptureMouse;
298    }
299
300    // FIXME: All the key handling is wrong and broken. Refer to GLFW's cocoa_init.mm and cocoa_window.mm.
301    if (event.type == NSEventTypeKeyDown)
302    {
303        NSString* str = [event characters];
304        NSUInteger len = [str length];
305        for (NSUInteger i = 0; i < len; i++)
306        {
307            int c = [str characterAtIndex:i];
308            if (!io.KeySuper && !(c >= 0xF700 && c <= 0xFFFF) && c != 127)
309                io.AddInputCharacter((unsigned int)c);
310
311            // We must reset in case we're pressing a sequence of special keys while keeping the command pressed
312            int key = mapCharacterToKey(c);
313            if (key != -1 && key < 256 && !io.KeySuper)
314                resetKeys();
315            if (key != -1)
316                io.KeysDown[key] = true;
317        }
318        return io.WantCaptureKeyboard;
319    }
320
321    if (event.type == NSEventTypeKeyUp)
322    {
323        NSString* str = [event characters];
324        NSUInteger len = [str length];
325        for (NSUInteger i = 0; i < len; i++)
326        {
327            int c = [str characterAtIndex:i];
328            int key = mapCharacterToKey(c);
329            if (key != -1)
330                io.KeysDown[key] = false;
331        }
332        return io.WantCaptureKeyboard;
333    }
334
335    if (event.type == NSEventTypeFlagsChanged)
336    {
337        unsigned int flags = [event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
338
339        bool oldKeyCtrl = io.KeyCtrl;
340        bool oldKeyShift = io.KeyShift;
341        bool oldKeyAlt = io.KeyAlt;
342        bool oldKeySuper = io.KeySuper;
343        io.KeyCtrl      = flags & NSEventModifierFlagControl;
344        io.KeyShift     = flags & NSEventModifierFlagShift;
345        io.KeyAlt       = flags & NSEventModifierFlagOption;
346        io.KeySuper     = flags & NSEventModifierFlagCommand;
347
348        // We must reset them as we will not receive any keyUp event if they where pressed with a modifier
349        if ((oldKeyShift && !io.KeyShift) || (oldKeyCtrl && !io.KeyCtrl) || (oldKeyAlt && !io.KeyAlt) || (oldKeySuper && !io.KeySuper))
350            resetKeys();
351        return io.WantCaptureKeyboard;
352    }
353
354    return false;
355}
356