imgui_impl_osx.mm 16 KB

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