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