imgui_impl_glfw.cpp 68 KB

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