imgui_impl_glfw.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. // dear imgui: Platform Backend for GLFW
  2. // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
  3. // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
  4. // (Requires: GLFW 3.1+. Prefer GLFW 3.3+ or GLFW 3.4+ for full feature support.)
  5. // Implemented features:
  6. // [X] Platform: Clipboard support.
  7. // [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 GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
  8. // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
  9. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
  10. // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  11. // Issues:
  12. // [ ] Platform: Multi-viewport support: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
  13. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  14. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  15. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  16. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  17. // CHANGELOG
  18. // (minor and older changes stripped away, please see git history for details)
  19. // 2023-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  20. // 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034)
  21. // 2023-03-14: Emscripten: Avoid using glfwGetError() and glfwGetGamepadState() which are not correctly implemented in Emscripten emulation. (#6240)
  22. // 2023-02-03: Emscripten: Registering custom low-level mouse wheel handler to get more accurate scrolling impulses on Emscripten. (#4019, #6096)
  23. // 2023-01-18: Handle unsupported glfwGetVideoMode() call on e.g. Emscripten.
  24. // 2023-01-04: Inputs: Fixed mods state on Linux when using Alt-GR text input (e.g. German keyboard layout), could lead to broken text input. Revert a 2022/01/17 change were we resumed using mods provided by GLFW, turns out they were faulty.
  25. // 2022-11-22: Perform a dummy glfwGetError() read to cancel missing names with glfwGetKeyName(). (#5908)
  26. // 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785)
  27. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  28. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
  29. // 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position.
  30. // 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX.
  31. // 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11.
  32. // 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend.
  33. // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
  34. // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
  35. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
  36. // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
  37. // 2022-01-12: *BREAKING CHANGE*: Now using glfwSetCursorPosCallback(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetCursorPosCallback() and forward it to the backend via ImGui_ImplGlfw_CursorPosCallback().
  38. // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
  39. // 2022-01-05: Inputs: Converting GLFW untranslated keycodes back to translated keycodes (in the ImGui_ImplGlfw_KeyCallback() function) in order to match the behavior of every other backend, and facilitate the use of GLFW with lettered-shortcuts API.
  40. // 2021-08-17: *BREAKING CHANGE*: Now using glfwSetWindowFocusCallback() to calling io.AddFocusEvent(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() and forward it to the backend via ImGui_ImplGlfw_WindowFocusCallback().
  41. // 2021-07-29: *BREAKING CHANGE*: Now using glfwSetCursorEnterCallback(). MousePos is correctly reported when the host platform window is hovered but not focused. If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() callback and forward it to the backend via ImGui_ImplGlfw_CursorEnterCallback().
  42. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
  43. // 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
  44. // 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
  45. // 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
  46. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
  47. // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
  48. // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
  49. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
  50. // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
  51. // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
  52. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
  53. // 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
  54. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  55. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
  56. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  57. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  58. // 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
  59. // 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
  60. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  61. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
  62. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
  63. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
  64. #include "imgui.h"
  65. #include "imgui_impl_glfw.h"
  66. // Clang warnings with -Weverything
  67. #if defined(__clang__)
  68. #pragma clang diagnostic push
  69. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
  70. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  71. #endif
  72. // GLFW
  73. #include <GLFW/glfw3.h>
  74. #ifdef _WIN32
  75. #undef APIENTRY
  76. #define GLFW_EXPOSE_NATIVE_WIN32
  77. #include <GLFW/glfw3native.h> // for glfwGetWin32Window()
  78. #endif
  79. #ifdef __APPLE__
  80. #define GLFW_EXPOSE_NATIVE_COCOA
  81. #include <GLFW/glfw3native.h> // for glfwGetCocoaWindow()
  82. #endif
  83. #ifdef __EMSCRIPTEN__
  84. #include <emscripten.h>
  85. #include <emscripten/html5.h>
  86. #endif
  87. // We gather version tests as define in order to easily see which features are version-dependent.
  88. #define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION)
  89. #define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_COMBINED >= 3200) // 3.2+ GLFW_FLOATING
  90. #define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_COMBINED >= 3300) // 3.3+ GLFW_HOVERED
  91. #define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwSetWindowOpacity
  92. #define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorContentScale
  93. #define GLFW_HAS_VULKAN (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwCreateWindowSurface
  94. #define GLFW_HAS_FOCUS_WINDOW (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwFocusWindow
  95. #define GLFW_HAS_FOCUS_ON_SHOW (GLFW_VERSION_COMBINED >= 3300) // 3.3+ GLFW_FOCUS_ON_SHOW
  96. #define GLFW_HAS_MONITOR_WORK_AREA (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorWorkarea
  97. #define GLFW_HAS_OSX_WINDOW_POS_FIX (GLFW_VERSION_COMBINED >= 3301) // 3.3.1+ Fixed: Resizing window repositions it on MacOS #1553
  98. #ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released?
  99. #define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR
  100. #else
  101. #define GLFW_HAS_NEW_CURSORS (0)
  102. #endif
  103. #ifdef GLFW_MOUSE_PASSTHROUGH // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2020-07-17 (passthrough)
  104. #define GLFW_HAS_MOUSE_PASSTHROUGH (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_MOUSE_PASSTHROUGH
  105. #else
  106. #define GLFW_HAS_MOUSE_PASSTHROUGH (0)
  107. #endif
  108. #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api
  109. #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName()
  110. #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError()
  111. // GLFW data
  112. enum GlfwClientApi
  113. {
  114. GlfwClientApi_Unknown,
  115. GlfwClientApi_OpenGL,
  116. GlfwClientApi_Vulkan
  117. };
  118. struct ImGui_ImplGlfw_Data
  119. {
  120. GLFWwindow* Window;
  121. GlfwClientApi ClientApi;
  122. double Time;
  123. GLFWwindow* MouseWindow;
  124. GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT];
  125. ImVec2 LastValidMousePos;
  126. GLFWwindow* KeyOwnerWindows[GLFW_KEY_LAST];
  127. bool InstalledCallbacks;
  128. bool CallbacksChainForAllWindows;
  129. bool WantUpdateMonitors;
  130. #ifdef _WIN32
  131. WNDPROC GlfwWndProc;
  132. #endif
  133. // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
  134. GLFWwindowfocusfun PrevUserCallbackWindowFocus;
  135. GLFWcursorposfun PrevUserCallbackCursorPos;
  136. GLFWcursorenterfun PrevUserCallbackCursorEnter;
  137. GLFWmousebuttonfun PrevUserCallbackMousebutton;
  138. GLFWscrollfun PrevUserCallbackScroll;
  139. GLFWkeyfun PrevUserCallbackKey;
  140. GLFWcharfun PrevUserCallbackChar;
  141. GLFWmonitorfun PrevUserCallbackMonitor;
  142. ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); }
  143. };
  144. // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
  145. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  146. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
  147. // - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks
  148. // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks.
  149. // - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it.
  150. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
  151. static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
  152. {
  153. return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
  154. }
  155. // Forward Declarations
  156. static void ImGui_ImplGlfw_UpdateMonitors();
  157. static void ImGui_ImplGlfw_InitPlatformInterface();
  158. static void ImGui_ImplGlfw_ShutdownPlatformInterface();
  159. // Functions
  160. static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
  161. {
  162. return glfwGetClipboardString((GLFWwindow*)user_data);
  163. }
  164. static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
  165. {
  166. glfwSetClipboardString((GLFWwindow*)user_data, text);
  167. }
  168. static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key)
  169. {
  170. switch (key)
  171. {
  172. case GLFW_KEY_TAB: return ImGuiKey_Tab;
  173. case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow;
  174. case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow;
  175. case GLFW_KEY_UP: return ImGuiKey_UpArrow;
  176. case GLFW_KEY_DOWN: return ImGuiKey_DownArrow;
  177. case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp;
  178. case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
  179. case GLFW_KEY_HOME: return ImGuiKey_Home;
  180. case GLFW_KEY_END: return ImGuiKey_End;
  181. case GLFW_KEY_INSERT: return ImGuiKey_Insert;
  182. case GLFW_KEY_DELETE: return ImGuiKey_Delete;
  183. case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace;
  184. case GLFW_KEY_SPACE: return ImGuiKey_Space;
  185. case GLFW_KEY_ENTER: return ImGuiKey_Enter;
  186. case GLFW_KEY_ESCAPE: return ImGuiKey_Escape;
  187. case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe;
  188. case GLFW_KEY_COMMA: return ImGuiKey_Comma;
  189. case GLFW_KEY_MINUS: return ImGuiKey_Minus;
  190. case GLFW_KEY_PERIOD: return ImGuiKey_Period;
  191. case GLFW_KEY_SLASH: return ImGuiKey_Slash;
  192. case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon;
  193. case GLFW_KEY_EQUAL: return ImGuiKey_Equal;
  194. case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket;
  195. case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash;
  196. case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket;
  197. case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent;
  198. case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock;
  199. case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock;
  200. case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock;
  201. case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen;
  202. case GLFW_KEY_PAUSE: return ImGuiKey_Pause;
  203. case GLFW_KEY_KP_0: return ImGuiKey_Keypad0;
  204. case GLFW_KEY_KP_1: return ImGuiKey_Keypad1;
  205. case GLFW_KEY_KP_2: return ImGuiKey_Keypad2;
  206. case GLFW_KEY_KP_3: return ImGuiKey_Keypad3;
  207. case GLFW_KEY_KP_4: return ImGuiKey_Keypad4;
  208. case GLFW_KEY_KP_5: return ImGuiKey_Keypad5;
  209. case GLFW_KEY_KP_6: return ImGuiKey_Keypad6;
  210. case GLFW_KEY_KP_7: return ImGuiKey_Keypad7;
  211. case GLFW_KEY_KP_8: return ImGuiKey_Keypad8;
  212. case GLFW_KEY_KP_9: return ImGuiKey_Keypad9;
  213. case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal;
  214. case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide;
  215. case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
  216. case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract;
  217. case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd;
  218. case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter;
  219. case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual;
  220. case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift;
  221. case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl;
  222. case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt;
  223. case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper;
  224. case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift;
  225. case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl;
  226. case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt;
  227. case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper;
  228. case GLFW_KEY_MENU: return ImGuiKey_Menu;
  229. case GLFW_KEY_0: return ImGuiKey_0;
  230. case GLFW_KEY_1: return ImGuiKey_1;
  231. case GLFW_KEY_2: return ImGuiKey_2;
  232. case GLFW_KEY_3: return ImGuiKey_3;
  233. case GLFW_KEY_4: return ImGuiKey_4;
  234. case GLFW_KEY_5: return ImGuiKey_5;
  235. case GLFW_KEY_6: return ImGuiKey_6;
  236. case GLFW_KEY_7: return ImGuiKey_7;
  237. case GLFW_KEY_8: return ImGuiKey_8;
  238. case GLFW_KEY_9: return ImGuiKey_9;
  239. case GLFW_KEY_A: return ImGuiKey_A;
  240. case GLFW_KEY_B: return ImGuiKey_B;
  241. case GLFW_KEY_C: return ImGuiKey_C;
  242. case GLFW_KEY_D: return ImGuiKey_D;
  243. case GLFW_KEY_E: return ImGuiKey_E;
  244. case GLFW_KEY_F: return ImGuiKey_F;
  245. case GLFW_KEY_G: return ImGuiKey_G;
  246. case GLFW_KEY_H: return ImGuiKey_H;
  247. case GLFW_KEY_I: return ImGuiKey_I;
  248. case GLFW_KEY_J: return ImGuiKey_J;
  249. case GLFW_KEY_K: return ImGuiKey_K;
  250. case GLFW_KEY_L: return ImGuiKey_L;
  251. case GLFW_KEY_M: return ImGuiKey_M;
  252. case GLFW_KEY_N: return ImGuiKey_N;
  253. case GLFW_KEY_O: return ImGuiKey_O;
  254. case GLFW_KEY_P: return ImGuiKey_P;
  255. case GLFW_KEY_Q: return ImGuiKey_Q;
  256. case GLFW_KEY_R: return ImGuiKey_R;
  257. case GLFW_KEY_S: return ImGuiKey_S;
  258. case GLFW_KEY_T: return ImGuiKey_T;
  259. case GLFW_KEY_U: return ImGuiKey_U;
  260. case GLFW_KEY_V: return ImGuiKey_V;
  261. case GLFW_KEY_W: return ImGuiKey_W;
  262. case GLFW_KEY_X: return ImGuiKey_X;
  263. case GLFW_KEY_Y: return ImGuiKey_Y;
  264. case GLFW_KEY_Z: return ImGuiKey_Z;
  265. case GLFW_KEY_F1: return ImGuiKey_F1;
  266. case GLFW_KEY_F2: return ImGuiKey_F2;
  267. case GLFW_KEY_F3: return ImGuiKey_F3;
  268. case GLFW_KEY_F4: return ImGuiKey_F4;
  269. case GLFW_KEY_F5: return ImGuiKey_F5;
  270. case GLFW_KEY_F6: return ImGuiKey_F6;
  271. case GLFW_KEY_F7: return ImGuiKey_F7;
  272. case GLFW_KEY_F8: return ImGuiKey_F8;
  273. case GLFW_KEY_F9: return ImGuiKey_F9;
  274. case GLFW_KEY_F10: return ImGuiKey_F10;
  275. case GLFW_KEY_F11: return ImGuiKey_F11;
  276. case GLFW_KEY_F12: return ImGuiKey_F12;
  277. default: return ImGuiKey_None;
  278. }
  279. }
  280. // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW
  281. // See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630
  282. static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window)
  283. {
  284. ImGuiIO& io = ImGui::GetIO();
  285. io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS));
  286. io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS));
  287. io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS));
  288. io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS));
  289. }
  290. static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window)
  291. {
  292. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  293. return bd->CallbacksChainForAllWindows ? true : (window == bd->Window);
  294. }
  295. void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
  296. {
  297. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  298. if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  299. bd->PrevUserCallbackMousebutton(window, button, action, mods);
  300. ImGui_ImplGlfw_UpdateKeyModifiers(window);
  301. ImGuiIO& io = ImGui::GetIO();
  302. if (button >= 0 && button < ImGuiMouseButton_COUNT)
  303. io.AddMouseButtonEvent(button, action == GLFW_PRESS);
  304. }
  305. void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
  306. {
  307. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  308. if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  309. bd->PrevUserCallbackScroll(window, xoffset, yoffset);
  310. #ifdef __EMSCRIPTEN__
  311. // Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback().
  312. return;
  313. #endif
  314. ImGuiIO& io = ImGui::GetIO();
  315. io.AddMouseWheelEvent((float)xoffset, (float)yoffset);
  316. }
  317. static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode)
  318. {
  319. #if GLFW_HAS_GETKEYNAME && !defined(__EMSCRIPTEN__)
  320. // GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult.
  321. // (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently)
  322. // See https://github.com/glfw/glfw/issues/1502 for details.
  323. // Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process).
  324. // This won't cover edge cases but this is at least going to cover common cases.
  325. if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL)
  326. return key;
  327. GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
  328. const char* key_name = glfwGetKeyName(key, scancode);
  329. glfwSetErrorCallback(prev_error_callback);
  330. #if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908)
  331. (void)glfwGetError(NULL);
  332. #endif
  333. if (key_name && key_name[0] != 0 && key_name[1] == 0)
  334. {
  335. const char char_names[] = "`-=[]\\,;\'./";
  336. const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 };
  337. IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys));
  338. if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); }
  339. else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); }
  340. else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); }
  341. else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; }
  342. }
  343. // if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name);
  344. #else
  345. IM_UNUSED(scancode);
  346. #endif
  347. return key;
  348. }
  349. void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods)
  350. {
  351. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  352. if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  353. bd->PrevUserCallbackKey(window, keycode, scancode, action, mods);
  354. if (action != GLFW_PRESS && action != GLFW_RELEASE)
  355. return;
  356. ImGui_ImplGlfw_UpdateKeyModifiers(window);
  357. if (keycode >= 0 && keycode < IM_ARRAYSIZE(bd->KeyOwnerWindows))
  358. bd->KeyOwnerWindows[keycode] = (action == GLFW_PRESS) ? window : nullptr;
  359. keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode);
  360. ImGuiIO& io = ImGui::GetIO();
  361. ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode);
  362. io.AddKeyEvent(imgui_key, (action == GLFW_PRESS));
  363. io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code)
  364. }
  365. void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused)
  366. {
  367. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  368. if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  369. bd->PrevUserCallbackWindowFocus(window, focused);
  370. ImGuiIO& io = ImGui::GetIO();
  371. io.AddFocusEvent(focused != 0);
  372. }
  373. void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y)
  374. {
  375. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  376. if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  377. bd->PrevUserCallbackCursorPos(window, x, y);
  378. if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
  379. return;
  380. ImGuiIO& io = ImGui::GetIO();
  381. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  382. {
  383. int window_x, window_y;
  384. glfwGetWindowPos(window, &window_x, &window_y);
  385. x += window_x;
  386. y += window_y;
  387. }
  388. io.AddMousePosEvent((float)x, (float)y);
  389. bd->LastValidMousePos = ImVec2((float)x, (float)y);
  390. }
  391. // Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position,
  392. // so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984)
  393. void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered)
  394. {
  395. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  396. if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  397. bd->PrevUserCallbackCursorEnter(window, entered);
  398. if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
  399. return;
  400. ImGuiIO& io = ImGui::GetIO();
  401. if (entered)
  402. {
  403. bd->MouseWindow = window;
  404. io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y);
  405. }
  406. else if (!entered && bd->MouseWindow == window)
  407. {
  408. bd->LastValidMousePos = io.MousePos;
  409. bd->MouseWindow = nullptr;
  410. io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
  411. }
  412. }
  413. void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
  414. {
  415. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  416. if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
  417. bd->PrevUserCallbackChar(window, c);
  418. ImGuiIO& io = ImGui::GetIO();
  419. io.AddInputCharacter(c);
  420. }
  421. void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int)
  422. {
  423. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  424. bd->WantUpdateMonitors = true;
  425. }
  426. #ifdef __EMSCRIPTEN__
  427. static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*)
  428. {
  429. // Mimic Emscripten_HandleWheel() in SDL.
  430. // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096
  431. float multiplier = 0.0f;
  432. if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step.
  433. else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step.
  434. else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps.
  435. float wheel_x = ev->deltaX * -multiplier;
  436. float wheel_y = ev->deltaY * -multiplier;
  437. ImGuiIO& io = ImGui::GetIO();
  438. io.AddMouseWheelEvent(wheel_x, wheel_y);
  439. //IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y);
  440. return EM_TRUE;
  441. }
  442. #endif
  443. void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
  444. {
  445. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  446. IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!");
  447. IM_ASSERT(bd->Window == window);
  448. bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback);
  449. bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback);
  450. bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback);
  451. bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
  452. bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
  453. bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
  454. bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
  455. bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
  456. bd->InstalledCallbacks = true;
  457. }
  458. void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window)
  459. {
  460. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  461. IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!");
  462. IM_ASSERT(bd->Window == window);
  463. glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus);
  464. glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter);
  465. glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos);
  466. glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton);
  467. glfwSetScrollCallback(window, bd->PrevUserCallbackScroll);
  468. glfwSetKeyCallback(window, bd->PrevUserCallbackKey);
  469. glfwSetCharCallback(window, bd->PrevUserCallbackChar);
  470. glfwSetMonitorCallback(bd->PrevUserCallbackMonitor);
  471. bd->InstalledCallbacks = false;
  472. bd->PrevUserCallbackWindowFocus = nullptr;
  473. bd->PrevUserCallbackCursorEnter = nullptr;
  474. bd->PrevUserCallbackCursorPos = nullptr;
  475. bd->PrevUserCallbackMousebutton = nullptr;
  476. bd->PrevUserCallbackScroll = nullptr;
  477. bd->PrevUserCallbackKey = nullptr;
  478. bd->PrevUserCallbackChar = nullptr;
  479. bd->PrevUserCallbackMonitor = nullptr;
  480. }
  481. // Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user.
  482. // This is 'false' by default meaning we only chain callbacks for the main viewport.
  483. // We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback.
  484. // If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter.
  485. void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows)
  486. {
  487. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  488. bd->CallbacksChainForAllWindows = chain_for_all_windows;
  489. }
  490. static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
  491. {
  492. ImGuiIO& io = ImGui::GetIO();
  493. IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
  494. //printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED);
  495. // Setup backend capabilities flags
  496. ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)();
  497. io.BackendPlatformUserData = (void*)bd;
  498. io.BackendPlatformName = "imgui_impl_glfw";
  499. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  500. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  501. #ifndef __EMSCRIPTEN__
  502. io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
  503. #endif
  504. #if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32))
  505. io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional)
  506. #endif
  507. bd->Window = window;
  508. bd->Time = 0.0;
  509. bd->WantUpdateMonitors = true;
  510. io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
  511. io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
  512. io.ClipboardUserData = bd->Window;
  513. // Create mouse cursors
  514. // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
  515. // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
  516. // Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
  517. GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
  518. bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  519. bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
  520. bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
  521. bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
  522. bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
  523. #if GLFW_HAS_NEW_CURSORS
  524. bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
  525. bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
  526. bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
  527. bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
  528. #else
  529. bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  530. bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  531. bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  532. bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  533. #endif
  534. glfwSetErrorCallback(prev_error_callback);
  535. #if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908)
  536. (void)glfwGetError(NULL);
  537. #endif
  538. // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
  539. if (install_callbacks)
  540. ImGui_ImplGlfw_InstallCallbacks(window);
  541. // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096)
  542. // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves.
  543. // FIXME: May break chaining in case user registered their own Emscripten callback?
  544. #ifdef __EMSCRIPTEN__
  545. emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, false, ImGui_ImplEmscripten_WheelCallback);
  546. #endif
  547. // Update monitors the first time (note: monitor callback are broken in GLFW 3.2 and earlier, see github.com/glfw/glfw/issues/784)
  548. ImGui_ImplGlfw_UpdateMonitors();
  549. glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
  550. // Set platform dependent data in viewport
  551. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  552. main_viewport->PlatformHandle = (void*)bd->Window;
  553. #ifdef _WIN32
  554. main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window);
  555. #elif defined(__APPLE__)
  556. main_viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(bd->Window);
  557. #else
  558. IM_UNUSED(main_viewport);
  559. #endif
  560. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  561. ImGui_ImplGlfw_InitPlatformInterface();
  562. bd->ClientApi = client_api;
  563. return true;
  564. }
  565. bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
  566. {
  567. return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
  568. }
  569. bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
  570. {
  571. return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
  572. }
  573. bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks)
  574. {
  575. return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
  576. }
  577. void ImGui_ImplGlfw_Shutdown()
  578. {
  579. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  580. IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
  581. ImGuiIO& io = ImGui::GetIO();
  582. ImGui_ImplGlfw_ShutdownPlatformInterface();
  583. if (bd->InstalledCallbacks)
  584. ImGui_ImplGlfw_RestoreCallbacks(bd->Window);
  585. for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
  586. glfwDestroyCursor(bd->MouseCursors[cursor_n]);
  587. io.BackendPlatformName = nullptr;
  588. io.BackendPlatformUserData = nullptr;
  589. IM_DELETE(bd);
  590. }
  591. static void ImGui_ImplGlfw_UpdateMouseData()
  592. {
  593. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  594. ImGuiIO& io = ImGui::GetIO();
  595. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  596. if (glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
  597. {
  598. io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
  599. return;
  600. }
  601. ImGuiID mouse_viewport_id = 0;
  602. const ImVec2 mouse_pos_prev = io.MousePos;
  603. for (int n = 0; n < platform_io.Viewports.Size; n++)
  604. {
  605. ImGuiViewport* viewport = platform_io.Viewports[n];
  606. GLFWwindow* window = (GLFWwindow*)viewport->PlatformHandle;
  607. #ifdef __EMSCRIPTEN__
  608. const bool is_window_focused = true;
  609. #else
  610. const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0;
  611. #endif
  612. if (is_window_focused)
  613. {
  614. // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  615. // When multi-viewports are enabled, all Dear ImGui positions are same as OS positions.
  616. if (io.WantSetMousePos)
  617. glfwSetCursorPos(window, (double)(mouse_pos_prev.x - viewport->Pos.x), (double)(mouse_pos_prev.y - viewport->Pos.y));
  618. // (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured)
  619. if (bd->MouseWindow == nullptr)
  620. {
  621. double mouse_x, mouse_y;
  622. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  623. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  624. {
  625. // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
  626. // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
  627. int window_x, window_y;
  628. glfwGetWindowPos(window, &window_x, &window_y);
  629. mouse_x += window_x;
  630. mouse_y += window_y;
  631. }
  632. bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y);
  633. io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
  634. }
  635. }
  636. // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering.
  637. // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic.
  638. // - [X] GLFW >= 3.3 backend ON WINDOWS ONLY does correctly ignore viewports with the _NoInputs flag.
  639. // - [!] GLFW <= 3.2 backend CANNOT correctly ignore viewports with the _NoInputs flag, and CANNOT reported Hovered Viewport because of mouse capture.
  640. // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window
  641. // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported
  642. // by the backend, and use its flawed heuristic to guess the viewport behind.
  643. // - [X] GLFW backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target).
  644. // FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems.
  645. // See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature.
  646. #if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32))
  647. const bool window_no_input = (viewport->Flags & ImGuiViewportFlags_NoInputs) != 0;
  648. #if GLFW_HAS_MOUSE_PASSTHROUGH
  649. glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, window_no_input);
  650. #endif
  651. if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !window_no_input)
  652. mouse_viewport_id = viewport->ID;
  653. #else
  654. // We cannot use bd->MouseWindow maintained from CursorEnter/Leave callbacks, because it is locked to the window capturing mouse.
  655. #endif
  656. }
  657. if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
  658. io.AddMouseViewportEvent(mouse_viewport_id);
  659. }
  660. static void ImGui_ImplGlfw_UpdateMouseCursor()
  661. {
  662. ImGuiIO& io = ImGui::GetIO();
  663. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  664. if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
  665. return;
  666. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  667. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  668. for (int n = 0; n < platform_io.Viewports.Size; n++)
  669. {
  670. GLFWwindow* window = (GLFWwindow*)platform_io.Viewports[n]->PlatformHandle;
  671. if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
  672. {
  673. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  674. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
  675. }
  676. else
  677. {
  678. // Show OS mouse cursor
  679. // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
  680. glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]);
  681. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  682. }
  683. }
  684. }
  685. // Update gamepad inputs
  686. static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
  687. static void ImGui_ImplGlfw_UpdateGamepads()
  688. {
  689. ImGuiIO& io = ImGui::GetIO();
  690. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
  691. return;
  692. io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
  693. #if GLFW_HAS_GAMEPAD_API && !defined(__EMSCRIPTEN__)
  694. GLFWgamepadstate gamepad;
  695. if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad))
  696. return;
  697. #define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0)
  698. #define MAP_ANALOG(KEY_NO, AXIS_NO, _UNUSED, V0, V1) do { float v = gamepad.axes[AXIS_NO]; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
  699. #else
  700. int axes_count = 0, buttons_count = 0;
  701. const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
  702. const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
  703. if (axes_count == 0 || buttons_count == 0)
  704. return;
  705. #define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0)
  706. #define MAP_ANALOG(KEY_NO, _UNUSED, AXIS_NO, V0, V1) do { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
  707. #endif
  708. io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
  709. MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7);
  710. MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6);
  711. MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square
  712. MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle
  713. MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle
  714. MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross
  715. MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13);
  716. MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11);
  717. MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10);
  718. MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12);
  719. MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4);
  720. MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5);
  721. MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f);
  722. MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f);
  723. MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8);
  724. MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9);
  725. MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f);
  726. MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f);
  727. MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f);
  728. MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f);
  729. MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f);
  730. MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f);
  731. MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f);
  732. MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f);
  733. #undef MAP_BUTTON
  734. #undef MAP_ANALOG
  735. }
  736. static void ImGui_ImplGlfw_UpdateMonitors()
  737. {
  738. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  739. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  740. int monitors_count = 0;
  741. GLFWmonitor** glfw_monitors = glfwGetMonitors(&monitors_count);
  742. platform_io.Monitors.resize(0);
  743. bd->WantUpdateMonitors = false;
  744. for (int n = 0; n < monitors_count; n++)
  745. {
  746. ImGuiPlatformMonitor monitor;
  747. int x, y;
  748. glfwGetMonitorPos(glfw_monitors[n], &x, &y);
  749. const GLFWvidmode* vid_mode = glfwGetVideoMode(glfw_monitors[n]);
  750. if (vid_mode == NULL)
  751. continue; // Failed to get Video mode (e.g. Emscripten does not support this function)
  752. monitor.MainPos = monitor.WorkPos = ImVec2((float)x, (float)y);
  753. monitor.MainSize = monitor.WorkSize = ImVec2((float)vid_mode->width, (float)vid_mode->height);
  754. #if GLFW_HAS_MONITOR_WORK_AREA
  755. int w, h;
  756. glfwGetMonitorWorkarea(glfw_monitors[n], &x, &y, &w, &h);
  757. if (w > 0 && h > 0) // Workaround a small GLFW issue reporting zero on monitor changes: https://github.com/glfw/glfw/pull/1761
  758. {
  759. monitor.WorkPos = ImVec2((float)x, (float)y);
  760. monitor.WorkSize = ImVec2((float)w, (float)h);
  761. }
  762. #endif
  763. #if GLFW_HAS_PER_MONITOR_DPI
  764. // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
  765. float x_scale, y_scale;
  766. glfwGetMonitorContentScale(glfw_monitors[n], &x_scale, &y_scale);
  767. monitor.DpiScale = x_scale;
  768. #endif
  769. platform_io.Monitors.push_back(monitor);
  770. }
  771. }
  772. void ImGui_ImplGlfw_NewFrame()
  773. {
  774. ImGuiIO& io = ImGui::GetIO();
  775. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  776. IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplGlfw_InitForXXX()?");
  777. // Setup display size (every frame to accommodate for window resizing)
  778. int w, h;
  779. int display_w, display_h;
  780. glfwGetWindowSize(bd->Window, &w, &h);
  781. glfwGetFramebufferSize(bd->Window, &display_w, &display_h);
  782. io.DisplaySize = ImVec2((float)w, (float)h);
  783. if (w > 0 && h > 0)
  784. io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h);
  785. if (bd->WantUpdateMonitors)
  786. ImGui_ImplGlfw_UpdateMonitors();
  787. // Setup time step
  788. double current_time = glfwGetTime();
  789. io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
  790. bd->Time = current_time;
  791. ImGui_ImplGlfw_UpdateMouseData();
  792. ImGui_ImplGlfw_UpdateMouseCursor();
  793. // Update game controllers (if enabled and available)
  794. ImGui_ImplGlfw_UpdateGamepads();
  795. }
  796. //--------------------------------------------------------------------------------------------------------
  797. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  798. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  799. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
  800. //--------------------------------------------------------------------------------------------------------
  801. // Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data.
  802. struct ImGui_ImplGlfw_ViewportData
  803. {
  804. GLFWwindow* Window;
  805. bool WindowOwned;
  806. int IgnoreWindowPosEventFrame;
  807. int IgnoreWindowSizeEventFrame;
  808. ImGui_ImplGlfw_ViewportData() { Window = nullptr; WindowOwned = false; IgnoreWindowSizeEventFrame = IgnoreWindowPosEventFrame = -1; }
  809. ~ImGui_ImplGlfw_ViewportData() { IM_ASSERT(Window == nullptr); }
  810. };
  811. static void ImGui_ImplGlfw_WindowCloseCallback(GLFWwindow* window)
  812. {
  813. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
  814. viewport->PlatformRequestClose = true;
  815. }
  816. // GLFW may dispatch window pos/size events after calling glfwSetWindowPos()/glfwSetWindowSize().
  817. // However: depending on the platform the callback may be invoked at different time:
  818. // - on Windows it appears to be called within the glfwSetWindowPos()/glfwSetWindowSize() call
  819. // - on Linux it is queued and invoked during glfwPollEvents()
  820. // Because the event doesn't always fire on glfwSetWindowXXX() we use a frame counter tag to only
  821. // ignore recent glfwSetWindowXXX() calls.
  822. static void ImGui_ImplGlfw_WindowPosCallback(GLFWwindow* window, int, int)
  823. {
  824. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
  825. {
  826. if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
  827. {
  828. bool ignore_event = (ImGui::GetFrameCount() <= vd->IgnoreWindowPosEventFrame + 1);
  829. //data->IgnoreWindowPosEventFrame = -1;
  830. if (ignore_event)
  831. return;
  832. }
  833. viewport->PlatformRequestMove = true;
  834. }
  835. }
  836. static void ImGui_ImplGlfw_WindowSizeCallback(GLFWwindow* window, int, int)
  837. {
  838. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
  839. {
  840. if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
  841. {
  842. bool ignore_event = (ImGui::GetFrameCount() <= vd->IgnoreWindowSizeEventFrame + 1);
  843. //data->IgnoreWindowSizeEventFrame = -1;
  844. if (ignore_event)
  845. return;
  846. }
  847. viewport->PlatformRequestResize = true;
  848. }
  849. }
  850. static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport)
  851. {
  852. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  853. ImGui_ImplGlfw_ViewportData* vd = IM_NEW(ImGui_ImplGlfw_ViewportData)();
  854. viewport->PlatformUserData = vd;
  855. // GLFW 3.2 unfortunately always set focus on glfwCreateWindow() if GLFW_VISIBLE is set, regardless of GLFW_FOCUSED
  856. // With GLFW 3.3, the hint GLFW_FOCUS_ON_SHOW fixes this problem
  857. glfwWindowHint(GLFW_VISIBLE, false);
  858. glfwWindowHint(GLFW_FOCUSED, false);
  859. #if GLFW_HAS_FOCUS_ON_SHOW
  860. glfwWindowHint(GLFW_FOCUS_ON_SHOW, false);
  861. #endif
  862. glfwWindowHint(GLFW_DECORATED, (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? false : true);
  863. #if GLFW_HAS_WINDOW_TOPMOST
  864. glfwWindowHint(GLFW_FLOATING, (viewport->Flags & ImGuiViewportFlags_TopMost) ? true : false);
  865. #endif
  866. GLFWwindow* share_window = (bd->ClientApi == GlfwClientApi_OpenGL) ? bd->Window : nullptr;
  867. vd->Window = glfwCreateWindow((int)viewport->Size.x, (int)viewport->Size.y, "No Title Yet", nullptr, share_window);
  868. vd->WindowOwned = true;
  869. viewport->PlatformHandle = (void*)vd->Window;
  870. #ifdef _WIN32
  871. viewport->PlatformHandleRaw = glfwGetWin32Window(vd->Window);
  872. #elif defined(__APPLE__)
  873. viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(vd->Window);
  874. #endif
  875. glfwSetWindowPos(vd->Window, (int)viewport->Pos.x, (int)viewport->Pos.y);
  876. // Install GLFW callbacks for secondary viewports
  877. glfwSetWindowFocusCallback(vd->Window, ImGui_ImplGlfw_WindowFocusCallback);
  878. glfwSetCursorEnterCallback(vd->Window, ImGui_ImplGlfw_CursorEnterCallback);
  879. glfwSetCursorPosCallback(vd->Window, ImGui_ImplGlfw_CursorPosCallback);
  880. glfwSetMouseButtonCallback(vd->Window, ImGui_ImplGlfw_MouseButtonCallback);
  881. glfwSetScrollCallback(vd->Window, ImGui_ImplGlfw_ScrollCallback);
  882. glfwSetKeyCallback(vd->Window, ImGui_ImplGlfw_KeyCallback);
  883. glfwSetCharCallback(vd->Window, ImGui_ImplGlfw_CharCallback);
  884. glfwSetWindowCloseCallback(vd->Window, ImGui_ImplGlfw_WindowCloseCallback);
  885. glfwSetWindowPosCallback(vd->Window, ImGui_ImplGlfw_WindowPosCallback);
  886. glfwSetWindowSizeCallback(vd->Window, ImGui_ImplGlfw_WindowSizeCallback);
  887. if (bd->ClientApi == GlfwClientApi_OpenGL)
  888. {
  889. glfwMakeContextCurrent(vd->Window);
  890. glfwSwapInterval(0);
  891. }
  892. }
  893. static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport)
  894. {
  895. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  896. if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
  897. {
  898. if (vd->WindowOwned)
  899. {
  900. #if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
  901. HWND hwnd = (HWND)viewport->PlatformHandleRaw;
  902. ::RemovePropA(hwnd, "IMGUI_VIEWPORT");
  903. #endif
  904. // Release any keys that were pressed in the window being destroyed and are still held down,
  905. // because we will not receive any release events after window is destroyed.
  906. for (int i = 0; i < IM_ARRAYSIZE(bd->KeyOwnerWindows); i++)
  907. if (bd->KeyOwnerWindows[i] == vd->Window)
  908. ImGui_ImplGlfw_KeyCallback(vd->Window, i, 0, GLFW_RELEASE, 0); // Later params are only used for main viewport, on which this function is never called.
  909. glfwDestroyWindow(vd->Window);
  910. }
  911. vd->Window = nullptr;
  912. IM_DELETE(vd);
  913. }
  914. viewport->PlatformUserData = viewport->PlatformHandle = nullptr;
  915. }
  916. // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs".
  917. // In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!)
  918. #if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
  919. static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  920. {
  921. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  922. if (msg == WM_NCHITTEST)
  923. {
  924. // Let mouse pass-through the window. This will allow the backend to call io.AddMouseViewportEvent() properly (which is OPTIONAL).
  925. // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
  926. // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
  927. // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
  928. ImGuiViewport* viewport = (ImGuiViewport*)::GetPropA(hWnd, "IMGUI_VIEWPORT");
  929. if (viewport->Flags & ImGuiViewportFlags_NoInputs)
  930. return HTTRANSPARENT;
  931. }
  932. return ::CallWindowProc(bd->GlfwWndProc, hWnd, msg, wParam, lParam);
  933. }
  934. #endif
  935. static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport)
  936. {
  937. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  938. #if defined(_WIN32)
  939. // GLFW hack: Hide icon from task bar
  940. HWND hwnd = (HWND)viewport->PlatformHandleRaw;
  941. if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)
  942. {
  943. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
  944. ex_style &= ~WS_EX_APPWINDOW;
  945. ex_style |= WS_EX_TOOLWINDOW;
  946. ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
  947. }
  948. // GLFW hack: install hook for WM_NCHITTEST message handler
  949. #if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
  950. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  951. ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport);
  952. if (bd->GlfwWndProc == nullptr)
  953. bd->GlfwWndProc = (WNDPROC)::GetWindowLongPtr(hwnd, GWLP_WNDPROC);
  954. ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)WndProcNoInputs);
  955. #endif
  956. #if !GLFW_HAS_FOCUS_ON_SHOW
  957. // GLFW hack: GLFW 3.2 has a bug where glfwShowWindow() also activates/focus the window.
  958. // The fix was pushed to GLFW repository on 2018/01/09 and should be included in GLFW 3.3 via a GLFW_FOCUS_ON_SHOW window attribute.
  959. // See https://github.com/glfw/glfw/issues/1189
  960. // FIXME-VIEWPORT: Implement same work-around for Linux/OSX in the meanwhile.
  961. if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
  962. {
  963. ::ShowWindow(hwnd, SW_SHOWNA);
  964. return;
  965. }
  966. #endif
  967. #endif
  968. glfwShowWindow(vd->Window);
  969. }
  970. static ImVec2 ImGui_ImplGlfw_GetWindowPos(ImGuiViewport* viewport)
  971. {
  972. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  973. int x = 0, y = 0;
  974. glfwGetWindowPos(vd->Window, &x, &y);
  975. return ImVec2((float)x, (float)y);
  976. }
  977. static void ImGui_ImplGlfw_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
  978. {
  979. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  980. vd->IgnoreWindowPosEventFrame = ImGui::GetFrameCount();
  981. glfwSetWindowPos(vd->Window, (int)pos.x, (int)pos.y);
  982. }
  983. static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport)
  984. {
  985. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  986. int w = 0, h = 0;
  987. glfwGetWindowSize(vd->Window, &w, &h);
  988. return ImVec2((float)w, (float)h);
  989. }
  990. static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  991. {
  992. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  993. #if __APPLE__ && !GLFW_HAS_OSX_WINDOW_POS_FIX
  994. // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are
  995. // positioned from the upper-left corner. GLFW makes an effort to convert macOS style coordinates, however it
  996. // doesn't handle it when changing size. We are manually moving the window in order for changes of size to be based
  997. // on the upper-left corner.
  998. int x, y, width, height;
  999. glfwGetWindowPos(vd->Window, &x, &y);
  1000. glfwGetWindowSize(vd->Window, &width, &height);
  1001. glfwSetWindowPos(vd->Window, x, y - height + size.y);
  1002. #endif
  1003. vd->IgnoreWindowSizeEventFrame = ImGui::GetFrameCount();
  1004. glfwSetWindowSize(vd->Window, (int)size.x, (int)size.y);
  1005. }
  1006. static void ImGui_ImplGlfw_SetWindowTitle(ImGuiViewport* viewport, const char* title)
  1007. {
  1008. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1009. glfwSetWindowTitle(vd->Window, title);
  1010. }
  1011. static void ImGui_ImplGlfw_SetWindowFocus(ImGuiViewport* viewport)
  1012. {
  1013. #if GLFW_HAS_FOCUS_WINDOW
  1014. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1015. glfwFocusWindow(vd->Window);
  1016. #else
  1017. // FIXME: What are the effect of not having this function? At the moment imgui doesn't actually call SetWindowFocus - we set that up ahead, will answer that question later.
  1018. (void)viewport;
  1019. #endif
  1020. }
  1021. static bool ImGui_ImplGlfw_GetWindowFocus(ImGuiViewport* viewport)
  1022. {
  1023. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1024. return glfwGetWindowAttrib(vd->Window, GLFW_FOCUSED) != 0;
  1025. }
  1026. static bool ImGui_ImplGlfw_GetWindowMinimized(ImGuiViewport* viewport)
  1027. {
  1028. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1029. return glfwGetWindowAttrib(vd->Window, GLFW_ICONIFIED) != 0;
  1030. }
  1031. #if GLFW_HAS_WINDOW_ALPHA
  1032. static void ImGui_ImplGlfw_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
  1033. {
  1034. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1035. glfwSetWindowOpacity(vd->Window, alpha);
  1036. }
  1037. #endif
  1038. static void ImGui_ImplGlfw_RenderWindow(ImGuiViewport* viewport, void*)
  1039. {
  1040. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  1041. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1042. if (bd->ClientApi == GlfwClientApi_OpenGL)
  1043. glfwMakeContextCurrent(vd->Window);
  1044. }
  1045. static void ImGui_ImplGlfw_SwapBuffers(ImGuiViewport* viewport, void*)
  1046. {
  1047. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  1048. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1049. if (bd->ClientApi == GlfwClientApi_OpenGL)
  1050. {
  1051. glfwMakeContextCurrent(vd->Window);
  1052. glfwSwapBuffers(vd->Window);
  1053. }
  1054. }
  1055. //--------------------------------------------------------------------------------------------------------
  1056. // Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
  1057. //--------------------------------------------------------------------------------------------------------
  1058. // Avoid including <vulkan.h> so we can build without it
  1059. #if GLFW_HAS_VULKAN
  1060. #ifndef VULKAN_H_
  1061. #define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
  1062. #if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  1063. #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
  1064. #else
  1065. #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;
  1066. #endif
  1067. VK_DEFINE_HANDLE(VkInstance)
  1068. VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR)
  1069. struct VkAllocationCallbacks;
  1070. enum VkResult { VK_RESULT_MAX_ENUM = 0x7FFFFFFF };
  1071. #endif // VULKAN_H_
  1072. extern "C" { extern GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); }
  1073. static int ImGui_ImplGlfw_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
  1074. {
  1075. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  1076. ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
  1077. IM_UNUSED(bd);
  1078. IM_ASSERT(bd->ClientApi == GlfwClientApi_Vulkan);
  1079. VkResult err = glfwCreateWindowSurface((VkInstance)vk_instance, vd->Window, (const VkAllocationCallbacks*)vk_allocator, (VkSurfaceKHR*)out_vk_surface);
  1080. return (int)err;
  1081. }
  1082. #endif // GLFW_HAS_VULKAN
  1083. static void ImGui_ImplGlfw_InitPlatformInterface()
  1084. {
  1085. // Register platform interface (will be coupled with a renderer interface)
  1086. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  1087. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1088. platform_io.Platform_CreateWindow = ImGui_ImplGlfw_CreateWindow;
  1089. platform_io.Platform_DestroyWindow = ImGui_ImplGlfw_DestroyWindow;
  1090. platform_io.Platform_ShowWindow = ImGui_ImplGlfw_ShowWindow;
  1091. platform_io.Platform_SetWindowPos = ImGui_ImplGlfw_SetWindowPos;
  1092. platform_io.Platform_GetWindowPos = ImGui_ImplGlfw_GetWindowPos;
  1093. platform_io.Platform_SetWindowSize = ImGui_ImplGlfw_SetWindowSize;
  1094. platform_io.Platform_GetWindowSize = ImGui_ImplGlfw_GetWindowSize;
  1095. platform_io.Platform_SetWindowFocus = ImGui_ImplGlfw_SetWindowFocus;
  1096. platform_io.Platform_GetWindowFocus = ImGui_ImplGlfw_GetWindowFocus;
  1097. platform_io.Platform_GetWindowMinimized = ImGui_ImplGlfw_GetWindowMinimized;
  1098. platform_io.Platform_SetWindowTitle = ImGui_ImplGlfw_SetWindowTitle;
  1099. platform_io.Platform_RenderWindow = ImGui_ImplGlfw_RenderWindow;
  1100. platform_io.Platform_SwapBuffers = ImGui_ImplGlfw_SwapBuffers;
  1101. #if GLFW_HAS_WINDOW_ALPHA
  1102. platform_io.Platform_SetWindowAlpha = ImGui_ImplGlfw_SetWindowAlpha;
  1103. #endif
  1104. #if GLFW_HAS_VULKAN
  1105. platform_io.Platform_CreateVkSurface = ImGui_ImplGlfw_CreateVkSurface;
  1106. #endif
  1107. // Register main window handle (which is owned by the main application, not by us)
  1108. // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
  1109. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  1110. ImGui_ImplGlfw_ViewportData* vd = IM_NEW(ImGui_ImplGlfw_ViewportData)();
  1111. vd->Window = bd->Window;
  1112. vd->WindowOwned = false;
  1113. main_viewport->PlatformUserData = vd;
  1114. main_viewport->PlatformHandle = (void*)bd->Window;
  1115. }
  1116. static void ImGui_ImplGlfw_ShutdownPlatformInterface()
  1117. {
  1118. ImGui::DestroyPlatformWindows();
  1119. }
  1120. #if defined(__clang__)
  1121. #pragma clang diagnostic pop
  1122. #endif