imgui_impl_glfw.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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.0+. Prefer GLFW 3.3+/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 are obsolete since 1.87 and not supported since 1.91.5]
  9. // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
  10. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors) with GLFW 3.1+. Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
  11. // [X] Multiple Dear ImGui contexts support.
  12. // Missing features or Issues:
  13. // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround.
  14. // [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors.
  15. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  16. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  17. // Learn about Dear ImGui:
  18. // - FAQ https://dearimgui.com/faq
  19. // - Getting Started https://dearimgui.com/getting-started
  20. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  21. // - Introduction, links and more at the top of imgui.cpp
  22. // About Emscripten support:
  23. // - Emscripten provides its own GLFW (3.2.1) implementation (syntax: "-sUSE_GLFW=3"), but Joystick is broken and several features are not supported (multiple windows, clipboard, timer, etc.)
  24. // - A third-party Emscripten GLFW (3.4.0) implementation (syntax: "--use-port=contrib.glfw3") fixes the Joystick issue and implements all relevant features for the browser.
  25. // See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Comparison.md for details.
  26. // CHANGELOG
  27. // (minor and older changes stripped away, please see git history for details)
  28. // 2025-11-06: Lower minimum requirement to GLFW 3.0. Though a recent version e.g GLFW 3.4 is highly recommended.
  29. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown.
  30. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921)
  31. // 2025-07-08: Made ImGui_ImplGlfw_GetContentScaleForWindow(), ImGui_ImplGlfw_GetContentScaleForMonitor() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733)
  32. // 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069)
  33. // 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps.
  34. // 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102.
  35. // 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled.
  36. // 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
  37. // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
  38. // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
  39. // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn
  40. // 2024-07-31: Added ImGui_ImplGlfw_Sleep() helper function for usage by our examples app, since GLFW doesn't provide one.
  41. // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter.
  42. // 2024-07-08: Emscripten: Added support for GLFW3 contrib port (GLFW 3.4.0 features + bug fixes): to enable, replace -sUSE_GLFW=3 with --use-port=contrib.glfw3 (requires emscripten 3.1.59+) (https://github.com/pongasoft/emscripten-glfw)
  43. // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions.
  44. // 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window.
  45. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys.
  46. // 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)
  47. // 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)
  48. // 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)
  49. // 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034)
  50. // 2023-03-14: Emscripten: Avoid using glfwGetError() and glfwGetGamepadState() which are not correctly implemented in Emscripten emulation. (#6240)
  51. // 2023-02-03: Emscripten: Registering custom low-level mouse wheel handler to get more accurate scrolling impulses on Emscripten. (#4019, #6096)
  52. // 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.
  53. // 2022-11-22: Perform a dummy glfwGetError() read to cancel missing names with glfwGetKeyName(). (#5908)
  54. // 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785)
  55. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  56. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
  57. // 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position *EDIT* Reverted 2023-07-18.
  58. // 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX.
  59. // 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11.
  60. // 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend.
  61. // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
  62. // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
  63. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
  64. // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
  65. // 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().
  66. // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
  67. // 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.
  68. // 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().
  69. // 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().
  70. // 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).
  71. // 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
  72. // 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
  73. // 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
  74. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
  75. // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
  76. // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
  77. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
  78. // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
  79. // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
  80. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
  81. // 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
  82. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  83. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
  84. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  85. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  86. // 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
  87. // 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
  88. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  89. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
  90. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
  91. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
  92. #include "imgui.h"
  93. #ifndef IMGUI_DISABLE
  94. #include "imgui_impl_glfw.h"
  95. // Clang warnings with -Weverything
  96. #if defined(__clang__)
  97. #pragma clang diagnostic push
  98. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
  99. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  100. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
  101. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
  102. #endif
  103. // GLFW
  104. #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  105. #define GLFW_HAS_X11_OR_WAYLAND 1
  106. #else
  107. #define GLFW_HAS_X11_OR_WAYLAND 0
  108. #endif
  109. #include <GLFW/glfw3.h>
  110. #ifdef _WIN32
  111. #undef APIENTRY
  112. #ifndef GLFW_EXPOSE_NATIVE_WIN32 // for glfwGetWin32Window()
  113. #define GLFW_EXPOSE_NATIVE_WIN32
  114. #endif
  115. #include <GLFW/glfw3native.h>
  116. #elif defined(__APPLE__)
  117. #ifndef GLFW_EXPOSE_NATIVE_COCOA // for glfwGetCocoaWindow()
  118. #define GLFW_EXPOSE_NATIVE_COCOA
  119. #endif
  120. #include <GLFW/glfw3native.h>
  121. #elif GLFW_HAS_X11_OR_WAYLAND
  122. #ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.)
  123. #define GLFW_EXPOSE_NATIVE_X11
  124. #endif
  125. #include <GLFW/glfw3native.h>
  126. #endif
  127. #undef Status // X11 headers are leaking this.
  128. #ifndef _WIN32
  129. #include <unistd.h> // for usleep()
  130. #endif
  131. #include <stdio.h> // for snprintf()
  132. #ifdef __EMSCRIPTEN__
  133. #include <emscripten.h>
  134. #include <emscripten/html5.h>
  135. #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3
  136. #include <GLFW/emscripten_glfw3.h>
  137. #else
  138. #define EMSCRIPTEN_USE_EMBEDDED_GLFW3
  139. #endif
  140. #endif
  141. // We gather version tests as define in order to easily see which features are version-dependent.
  142. #define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION)
  143. #define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorContentScale
  144. #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?
  145. #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
  146. #else
  147. #define GLFW_HAS_NEW_CURSORS (0)
  148. #endif
  149. #define GLFW_HAS_CREATECURSOR (GLFW_VERSION_COMBINED >= 3100) // 3.1+ glfwCreateCursor()
  150. #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api
  151. #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName()
  152. #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError()
  153. #define GLFW_HAS_GETPLATFORM (GLFW_VERSION_COMBINED >= 3400) // 3.4+ glfwGetPlatform()
  154. // Map GLFWWindow* to ImGuiContext*.
  155. // - Would be simpler if we could use glfwSetWindowUserPointer()/glfwGetWindowUserPointer(), but this is a single and shared resource.
  156. // - Would be simpler if we could use e.g. std::map<> as well. But we don't.
  157. // - This is not particularly optimized as we expect size to be small and queries to be rare.
  158. struct ImGui_ImplGlfw_WindowToContext { GLFWwindow* Window; ImGuiContext* Context; };
  159. static ImVector<ImGui_ImplGlfw_WindowToContext> g_ContextMap;
  160. static void ImGui_ImplGlfw_ContextMap_Add(GLFWwindow* window, ImGuiContext* ctx) { g_ContextMap.push_back(ImGui_ImplGlfw_WindowToContext{ window, ctx }); }
  161. static void ImGui_ImplGlfw_ContextMap_Remove(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) { g_ContextMap.erase_unsorted(&entry); if (g_ContextMap.empty()) g_ContextMap.clear(); return; } }
  162. static ImGuiContext* ImGui_ImplGlfw_ContextMap_Get(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) return entry.Context; return nullptr; }
  163. enum GlfwClientApi
  164. {
  165. GlfwClientApi_OpenGL,
  166. GlfwClientApi_Vulkan,
  167. GlfwClientApi_Unknown, // Anything else fits here.
  168. };
  169. // GLFW data
  170. struct ImGui_ImplGlfw_Data
  171. {
  172. ImGuiContext* Context;
  173. GLFWwindow* Window;
  174. GlfwClientApi ClientApi;
  175. double Time;
  176. GLFWwindow* MouseWindow;
  177. #if GLFW_HAS_CREATECURSOR
  178. GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT];
  179. #endif
  180. ImVec2 LastValidMousePos;
  181. bool IsWayland;
  182. bool InstalledCallbacks;
  183. bool CallbacksChainForAllWindows;
  184. char BackendPlatformName[32];
  185. #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
  186. const char* CanvasSelector;
  187. #endif
  188. // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
  189. GLFWwindowfocusfun PrevUserCallbackWindowFocus;
  190. GLFWcursorposfun PrevUserCallbackCursorPos;
  191. GLFWcursorenterfun PrevUserCallbackCursorEnter;
  192. GLFWmousebuttonfun PrevUserCallbackMousebutton;
  193. GLFWscrollfun PrevUserCallbackScroll;
  194. GLFWkeyfun PrevUserCallbackKey;
  195. GLFWcharfun PrevUserCallbackChar;
  196. GLFWmonitorfun PrevUserCallbackMonitor;
  197. #ifdef _WIN32
  198. WNDPROC PrevWndProc;
  199. #endif
  200. ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); }
  201. };
  202. // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
  203. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  204. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
  205. // - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks
  206. // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks.
  207. // - 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.
  208. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
  209. namespace ImGui { extern ImGuiIO& GetIO(ImGuiContext*); }
  210. static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
  211. {
  212. // Get data for current context
  213. return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
  214. }
  215. static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(GLFWwindow* window)
  216. {
  217. // Get data for a given GLFW window, regardless of current context (since GLFW events are sent together)
  218. ImGuiContext* ctx = ImGui_ImplGlfw_ContextMap_Get(window);
  219. return (ImGui_ImplGlfw_Data*)ImGui::GetIO(ctx).BackendPlatformUserData;
  220. }
  221. // Functions
  222. static bool ImGui_ImplGlfw_IsWayland()
  223. {
  224. #if !GLFW_HAS_X11_OR_WAYLAND
  225. return false;
  226. #elif GLFW_HAS_GETPLATFORM
  227. return glfwGetPlatform() == GLFW_PLATFORM_WAYLAND;
  228. #else
  229. const char* version = glfwGetVersionString();
  230. if (strstr(version, "Wayland") == NULL) // e.g. Ubuntu 22.04 ships with GLFW 3.3.6 compiled without Wayland
  231. return false;
  232. #ifdef GLFW_EXPOSE_NATIVE_X11
  233. if (glfwGetX11Display() != NULL)
  234. return false;
  235. #endif
  236. return true;
  237. #endif
  238. }
  239. // Not static to allow third-party code to use that if they want to (but undocumented)
  240. ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode);
  241. ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode)
  242. {
  243. IM_UNUSED(scancode);
  244. switch (keycode)
  245. {
  246. case GLFW_KEY_TAB: return ImGuiKey_Tab;
  247. case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow;
  248. case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow;
  249. case GLFW_KEY_UP: return ImGuiKey_UpArrow;
  250. case GLFW_KEY_DOWN: return ImGuiKey_DownArrow;
  251. case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp;
  252. case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
  253. case GLFW_KEY_HOME: return ImGuiKey_Home;
  254. case GLFW_KEY_END: return ImGuiKey_End;
  255. case GLFW_KEY_INSERT: return ImGuiKey_Insert;
  256. case GLFW_KEY_DELETE: return ImGuiKey_Delete;
  257. case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace;
  258. case GLFW_KEY_SPACE: return ImGuiKey_Space;
  259. case GLFW_KEY_ENTER: return ImGuiKey_Enter;
  260. case GLFW_KEY_ESCAPE: return ImGuiKey_Escape;
  261. case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe;
  262. case GLFW_KEY_COMMA: return ImGuiKey_Comma;
  263. case GLFW_KEY_MINUS: return ImGuiKey_Minus;
  264. case GLFW_KEY_PERIOD: return ImGuiKey_Period;
  265. case GLFW_KEY_SLASH: return ImGuiKey_Slash;
  266. case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon;
  267. case GLFW_KEY_EQUAL: return ImGuiKey_Equal;
  268. case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket;
  269. case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash;
  270. case GLFW_KEY_WORLD_1: return ImGuiKey_Oem102;
  271. case GLFW_KEY_WORLD_2: return ImGuiKey_Oem102;
  272. case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket;
  273. case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent;
  274. case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock;
  275. case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock;
  276. case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock;
  277. case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen;
  278. case GLFW_KEY_PAUSE: return ImGuiKey_Pause;
  279. case GLFW_KEY_KP_0: return ImGuiKey_Keypad0;
  280. case GLFW_KEY_KP_1: return ImGuiKey_Keypad1;
  281. case GLFW_KEY_KP_2: return ImGuiKey_Keypad2;
  282. case GLFW_KEY_KP_3: return ImGuiKey_Keypad3;
  283. case GLFW_KEY_KP_4: return ImGuiKey_Keypad4;
  284. case GLFW_KEY_KP_5: return ImGuiKey_Keypad5;
  285. case GLFW_KEY_KP_6: return ImGuiKey_Keypad6;
  286. case GLFW_KEY_KP_7: return ImGuiKey_Keypad7;
  287. case GLFW_KEY_KP_8: return ImGuiKey_Keypad8;
  288. case GLFW_KEY_KP_9: return ImGuiKey_Keypad9;
  289. case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal;
  290. case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide;
  291. case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
  292. case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract;
  293. case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd;
  294. case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter;
  295. case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual;
  296. case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift;
  297. case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl;
  298. case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt;
  299. case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper;
  300. case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift;
  301. case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl;
  302. case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt;
  303. case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper;
  304. case GLFW_KEY_MENU: return ImGuiKey_Menu;
  305. case GLFW_KEY_0: return ImGuiKey_0;
  306. case GLFW_KEY_1: return ImGuiKey_1;
  307. case GLFW_KEY_2: return ImGuiKey_2;
  308. case GLFW_KEY_3: return ImGuiKey_3;
  309. case GLFW_KEY_4: return ImGuiKey_4;
  310. case GLFW_KEY_5: return ImGuiKey_5;
  311. case GLFW_KEY_6: return ImGuiKey_6;
  312. case GLFW_KEY_7: return ImGuiKey_7;
  313. case GLFW_KEY_8: return ImGuiKey_8;
  314. case GLFW_KEY_9: return ImGuiKey_9;
  315. case GLFW_KEY_A: return ImGuiKey_A;
  316. case GLFW_KEY_B: return ImGuiKey_B;
  317. case GLFW_KEY_C: return ImGuiKey_C;
  318. case GLFW_KEY_D: return ImGuiKey_D;
  319. case GLFW_KEY_E: return ImGuiKey_E;
  320. case GLFW_KEY_F: return ImGuiKey_F;
  321. case GLFW_KEY_G: return ImGuiKey_G;
  322. case GLFW_KEY_H: return ImGuiKey_H;
  323. case GLFW_KEY_I: return ImGuiKey_I;
  324. case GLFW_KEY_J: return ImGuiKey_J;
  325. case GLFW_KEY_K: return ImGuiKey_K;
  326. case GLFW_KEY_L: return ImGuiKey_L;
  327. case GLFW_KEY_M: return ImGuiKey_M;
  328. case GLFW_KEY_N: return ImGuiKey_N;
  329. case GLFW_KEY_O: return ImGuiKey_O;
  330. case GLFW_KEY_P: return ImGuiKey_P;
  331. case GLFW_KEY_Q: return ImGuiKey_Q;
  332. case GLFW_KEY_R: return ImGuiKey_R;
  333. case GLFW_KEY_S: return ImGuiKey_S;
  334. case GLFW_KEY_T: return ImGuiKey_T;
  335. case GLFW_KEY_U: return ImGuiKey_U;
  336. case GLFW_KEY_V: return ImGuiKey_V;
  337. case GLFW_KEY_W: return ImGuiKey_W;
  338. case GLFW_KEY_X: return ImGuiKey_X;
  339. case GLFW_KEY_Y: return ImGuiKey_Y;
  340. case GLFW_KEY_Z: return ImGuiKey_Z;
  341. case GLFW_KEY_F1: return ImGuiKey_F1;
  342. case GLFW_KEY_F2: return ImGuiKey_F2;
  343. case GLFW_KEY_F3: return ImGuiKey_F3;
  344. case GLFW_KEY_F4: return ImGuiKey_F4;
  345. case GLFW_KEY_F5: return ImGuiKey_F5;
  346. case GLFW_KEY_F6: return ImGuiKey_F6;
  347. case GLFW_KEY_F7: return ImGuiKey_F7;
  348. case GLFW_KEY_F8: return ImGuiKey_F8;
  349. case GLFW_KEY_F9: return ImGuiKey_F9;
  350. case GLFW_KEY_F10: return ImGuiKey_F10;
  351. case GLFW_KEY_F11: return ImGuiKey_F11;
  352. case GLFW_KEY_F12: return ImGuiKey_F12;
  353. case GLFW_KEY_F13: return ImGuiKey_F13;
  354. case GLFW_KEY_F14: return ImGuiKey_F14;
  355. case GLFW_KEY_F15: return ImGuiKey_F15;
  356. case GLFW_KEY_F16: return ImGuiKey_F16;
  357. case GLFW_KEY_F17: return ImGuiKey_F17;
  358. case GLFW_KEY_F18: return ImGuiKey_F18;
  359. case GLFW_KEY_F19: return ImGuiKey_F19;
  360. case GLFW_KEY_F20: return ImGuiKey_F20;
  361. case GLFW_KEY_F21: return ImGuiKey_F21;
  362. case GLFW_KEY_F22: return ImGuiKey_F22;
  363. case GLFW_KEY_F23: return ImGuiKey_F23;
  364. case GLFW_KEY_F24: return ImGuiKey_F24;
  365. default: return ImGuiKey_None;
  366. }
  367. }
  368. // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW
  369. // See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630
  370. static void ImGui_ImplGlfw_UpdateKeyModifiers(ImGuiIO& io, GLFWwindow* window)
  371. {
  372. io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS));
  373. io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS));
  374. io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS));
  375. io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS));
  376. }
  377. static bool ImGui_ImplGlfw_ShouldChainCallback(ImGui_ImplGlfw_Data* bd, GLFWwindow* window)
  378. {
  379. return bd->CallbacksChainForAllWindows ? true : (window == bd->Window);
  380. }
  381. void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
  382. {
  383. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  384. if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  385. bd->PrevUserCallbackMousebutton(window, button, action, mods);
  386. ImGuiIO& io = ImGui::GetIO(bd->Context);
  387. ImGui_ImplGlfw_UpdateKeyModifiers(io, window);
  388. if (button >= 0 && button < ImGuiMouseButton_COUNT)
  389. io.AddMouseButtonEvent(button, action == GLFW_PRESS);
  390. }
  391. void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
  392. {
  393. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  394. if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  395. bd->PrevUserCallbackScroll(window, xoffset, yoffset);
  396. #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
  397. // Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback().
  398. return;
  399. #endif
  400. ImGuiIO& io = ImGui::GetIO(bd->Context);
  401. io.AddMouseWheelEvent((float)xoffset, (float)yoffset);
  402. }
  403. // FIXME: should this be baked into ImGui_ImplGlfw_KeyToImGuiKey()? then what about the values passed to io.SetKeyEventNativeData()?
  404. static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode)
  405. {
  406. #if GLFW_HAS_GETKEYNAME && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3)
  407. // GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult.
  408. // (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)
  409. // See https://github.com/glfw/glfw/issues/1502 for details.
  410. // Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process).
  411. // This won't cover edge cases but this is at least going to cover common cases.
  412. if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL)
  413. return key;
  414. GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
  415. const char* key_name = glfwGetKeyName(key, scancode);
  416. glfwSetErrorCallback(prev_error_callback);
  417. #if GLFW_HAS_GETERROR && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) // Eat errors (see #5908)
  418. (void)glfwGetError(nullptr);
  419. #endif
  420. if (key_name && key_name[0] != 0 && key_name[1] == 0)
  421. {
  422. const char char_names[] = "`-=[]\\,;\'./";
  423. 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 };
  424. IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys));
  425. if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); }
  426. else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); }
  427. else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); }
  428. else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; }
  429. }
  430. // if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name);
  431. #else
  432. IM_UNUSED(scancode);
  433. #endif
  434. return key;
  435. }
  436. void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods)
  437. {
  438. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  439. if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  440. bd->PrevUserCallbackKey(window, keycode, scancode, action, mods);
  441. if (action != GLFW_PRESS && action != GLFW_RELEASE)
  442. return;
  443. ImGuiIO& io = ImGui::GetIO(bd->Context);
  444. ImGui_ImplGlfw_UpdateKeyModifiers(io, window);
  445. keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode);
  446. ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode, scancode);
  447. io.AddKeyEvent(imgui_key, (action == GLFW_PRESS));
  448. io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code)
  449. }
  450. void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused)
  451. {
  452. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  453. if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  454. bd->PrevUserCallbackWindowFocus(window, focused);
  455. ImGuiIO& io = ImGui::GetIO(bd->Context);
  456. io.AddFocusEvent(focused != 0);
  457. }
  458. void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y)
  459. {
  460. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  461. if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  462. bd->PrevUserCallbackCursorPos(window, x, y);
  463. ImGuiIO& io = ImGui::GetIO(bd->Context);
  464. io.AddMousePosEvent((float)x, (float)y);
  465. bd->LastValidMousePos = ImVec2((float)x, (float)y);
  466. }
  467. // Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position,
  468. // so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984)
  469. void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered)
  470. {
  471. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  472. if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  473. bd->PrevUserCallbackCursorEnter(window, entered);
  474. ImGuiIO& io = ImGui::GetIO(bd->Context);
  475. if (entered)
  476. {
  477. bd->MouseWindow = window;
  478. io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y);
  479. }
  480. else if (!entered && bd->MouseWindow == window)
  481. {
  482. bd->LastValidMousePos = io.MousePos;
  483. bd->MouseWindow = nullptr;
  484. io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
  485. }
  486. }
  487. void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
  488. {
  489. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  490. if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window))
  491. bd->PrevUserCallbackChar(window, c);
  492. ImGuiIO& io = ImGui::GetIO(bd->Context);
  493. io.AddInputCharacter(c);
  494. }
  495. void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int)
  496. {
  497. // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too.
  498. }
  499. #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
  500. static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void* user_data)
  501. {
  502. // Mimic Emscripten_HandleWheel() in SDL.
  503. // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096
  504. ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
  505. float multiplier = 0.0f;
  506. if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step.
  507. else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step.
  508. else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps.
  509. float wheel_x = ev->deltaX * -multiplier;
  510. float wheel_y = ev->deltaY * -multiplier;
  511. ImGuiIO& io = ImGui::GetIO(bd->Context);
  512. io.AddMouseWheelEvent(wheel_x, wheel_y);
  513. //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);
  514. return EM_TRUE;
  515. }
  516. #endif
  517. #ifdef _WIN32
  518. // GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen.
  519. // Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently.
  520. static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
  521. {
  522. LPARAM extra_info = ::GetMessageExtraInfo();
  523. if ((extra_info & 0xFFFFFF80) == 0xFF515700)
  524. return ImGuiMouseSource_Pen;
  525. if ((extra_info & 0xFFFFFF80) == 0xFF515780)
  526. return ImGuiMouseSource_TouchScreen;
  527. return ImGuiMouseSource_Mouse;
  528. }
  529. static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  530. {
  531. ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)::GetPropA(hWnd, "IMGUI_BACKEND_DATA");
  532. ImGuiIO& io = ImGui::GetIO(bd->Context);
  533. switch (msg)
  534. {
  535. case WM_MOUSEMOVE: case WM_NCMOUSEMOVE:
  536. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_LBUTTONUP:
  537. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP:
  538. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP:
  539. case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP:
  540. io.AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo());
  541. break;
  542. default: break;
  543. }
  544. return ::CallWindowProcW(bd->PrevWndProc, hWnd, msg, wParam, lParam);
  545. }
  546. #endif
  547. void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
  548. {
  549. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  550. IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!");
  551. IM_ASSERT(bd->Window == window);
  552. bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback);
  553. bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback);
  554. bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback);
  555. bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
  556. bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
  557. bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
  558. bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
  559. bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
  560. bd->InstalledCallbacks = true;
  561. }
  562. void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window)
  563. {
  564. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  565. IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!");
  566. IM_ASSERT(bd->Window == window);
  567. glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus);
  568. glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter);
  569. glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos);
  570. glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton);
  571. glfwSetScrollCallback(window, bd->PrevUserCallbackScroll);
  572. glfwSetKeyCallback(window, bd->PrevUserCallbackKey);
  573. glfwSetCharCallback(window, bd->PrevUserCallbackChar);
  574. glfwSetMonitorCallback(bd->PrevUserCallbackMonitor);
  575. bd->InstalledCallbacks = false;
  576. bd->PrevUserCallbackWindowFocus = nullptr;
  577. bd->PrevUserCallbackCursorEnter = nullptr;
  578. bd->PrevUserCallbackCursorPos = nullptr;
  579. bd->PrevUserCallbackMousebutton = nullptr;
  580. bd->PrevUserCallbackScroll = nullptr;
  581. bd->PrevUserCallbackKey = nullptr;
  582. bd->PrevUserCallbackChar = nullptr;
  583. bd->PrevUserCallbackMonitor = nullptr;
  584. }
  585. // Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user).
  586. // This is 'false' by default meaning we only chain callbacks for the main viewport.
  587. // We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback.
  588. // If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter.
  589. void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows)
  590. {
  591. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  592. bd->CallbacksChainForAllWindows = chain_for_all_windows;
  593. }
  594. #ifdef __EMSCRIPTEN__
  595. #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817
  596. void ImGui_ImplGlfw_EmscriptenOpenURL(const char* url) { if (url) emscripten::glfw3::OpenURL(url); }
  597. #else
  598. EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); });
  599. #endif
  600. #endif
  601. static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
  602. {
  603. ImGuiIO& io = ImGui::GetIO();
  604. IMGUI_CHECKVERSION();
  605. IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
  606. //printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED);
  607. // Setup backend capabilities flags
  608. ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)();
  609. snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_glfw (%d)", GLFW_VERSION_COMBINED);
  610. io.BackendPlatformUserData = (void*)bd;
  611. io.BackendPlatformName = bd->BackendPlatformName;
  612. #if GLFW_HAS_CREATECURSOR
  613. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  614. #endif
  615. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  616. bd->Context = ImGui::GetCurrentContext();
  617. bd->Window = window;
  618. bd->Time = 0.0;
  619. bd->IsWayland = ImGui_ImplGlfw_IsWayland();
  620. ImGui_ImplGlfw_ContextMap_Add(window, bd->Context);
  621. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  622. #if GLFW_VERSION_COMBINED < 3300
  623. platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(ImGui_ImplGlfw_GetBackendData()->Window, text); };
  624. platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(ImGui_ImplGlfw_GetBackendData()->Window); };
  625. #else
  626. platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(nullptr, text); };
  627. platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(nullptr); };
  628. #endif
  629. #ifdef __EMSCRIPTEN__
  630. platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; };
  631. #endif
  632. // Create mouse cursors
  633. // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
  634. // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
  635. // Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
  636. #if GLFW_HAS_CREATECURSOR
  637. GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
  638. bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  639. bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
  640. bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
  641. bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
  642. bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
  643. #if GLFW_HAS_NEW_CURSORS
  644. bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
  645. bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
  646. bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
  647. bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
  648. #else
  649. bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  650. bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  651. bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  652. bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  653. #endif
  654. glfwSetErrorCallback(prev_error_callback);
  655. #endif
  656. #if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908)
  657. (void)glfwGetError(nullptr);
  658. #endif
  659. // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
  660. if (install_callbacks)
  661. ImGui_ImplGlfw_InstallCallbacks(window);
  662. // Set platform dependent data in viewport
  663. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  664. main_viewport->PlatformHandle = (void*)bd->Window;
  665. #ifdef _WIN32
  666. main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window);
  667. #elif defined(__APPLE__)
  668. main_viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(bd->Window);
  669. #else
  670. IM_UNUSED(main_viewport);
  671. #endif
  672. // Windows: register a WndProc hook so we can intercept some messages.
  673. #ifdef _WIN32
  674. HWND hwnd = (HWND)main_viewport->PlatformHandleRaw;
  675. ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd);
  676. bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC);
  677. IM_ASSERT(bd->PrevWndProc != nullptr);
  678. ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc);
  679. #endif
  680. // Emscripten: the same application can run on various platforms, so we detect the Apple platform at runtime
  681. // to override io.ConfigMacOSXBehaviors from its default (which is always false in Emscripten).
  682. #ifdef __EMSCRIPTEN__
  683. #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817
  684. if (emscripten::glfw3::IsRuntimePlatformApple())
  685. {
  686. io.ConfigMacOSXBehaviors = true;
  687. // Due to how the browser (poorly) handles the Meta Key, this line essentially disables repeats when used.
  688. // This means that Meta + V only registers a single key-press, even if the keys are held.
  689. // This is a compromise for dealing with this issue in ImGui since ImGui implements key repeat itself.
  690. // See https://github.com/pongasoft/emscripten-glfw/blob/v3.4.0.20240817/docs/Usage.md#the-problem-of-the-super-key
  691. emscripten::glfw3::SetSuperPlusKeyTimeouts(10, 10);
  692. }
  693. #endif
  694. #endif
  695. bd->ClientApi = client_api;
  696. return true;
  697. }
  698. bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
  699. {
  700. return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
  701. }
  702. bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
  703. {
  704. return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
  705. }
  706. bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks)
  707. {
  708. return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
  709. }
  710. void ImGui_ImplGlfw_Shutdown()
  711. {
  712. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  713. IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
  714. ImGuiIO& io = ImGui::GetIO();
  715. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  716. if (bd->InstalledCallbacks)
  717. ImGui_ImplGlfw_RestoreCallbacks(bd->Window);
  718. #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
  719. if (bd->CanvasSelector)
  720. emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, nullptr);
  721. #endif
  722. #if GLFW_HAS_CREATECURSOR
  723. for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
  724. glfwDestroyCursor(bd->MouseCursors[cursor_n]);
  725. #endif
  726. // Windows: restore our WndProc hook
  727. #ifdef _WIN32
  728. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  729. ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_BACKEND_DATA", nullptr);
  730. ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc);
  731. bd->PrevWndProc = nullptr;
  732. #endif
  733. io.BackendPlatformName = nullptr;
  734. io.BackendPlatformUserData = nullptr;
  735. io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
  736. platform_io.ClearPlatformHandlers();
  737. ImGui_ImplGlfw_ContextMap_Remove(bd->Window);
  738. IM_DELETE(bd);
  739. }
  740. static void ImGui_ImplGlfw_UpdateMouseData()
  741. {
  742. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  743. ImGuiIO& io = ImGui::GetIO();
  744. // (those braces are here to reduce diff with multi-viewports support in 'docking' branch)
  745. {
  746. GLFWwindow* window = bd->Window;
  747. #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
  748. const bool is_window_focused = true;
  749. #else
  750. const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0;
  751. #endif
  752. if (is_window_focused)
  753. {
  754. // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
  755. if (io.WantSetMousePos)
  756. glfwSetCursorPos(window, (double)io.MousePos.x, (double)io.MousePos.y);
  757. // (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured)
  758. if (bd->MouseWindow == nullptr)
  759. {
  760. double mouse_x, mouse_y;
  761. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  762. bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y);
  763. io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
  764. }
  765. }
  766. }
  767. }
  768. static void ImGui_ImplGlfw_UpdateMouseCursor()
  769. {
  770. ImGuiIO& io = ImGui::GetIO();
  771. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  772. if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
  773. return;
  774. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  775. // (those braces are here to reduce diff with multi-viewports support in 'docking' branch)
  776. {
  777. GLFWwindow* window = bd->Window;
  778. if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
  779. {
  780. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  781. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
  782. }
  783. else
  784. {
  785. // Show OS mouse cursor
  786. // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
  787. #if GLFW_HAS_CREATECURSOR
  788. glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]);
  789. #endif
  790. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  791. }
  792. }
  793. }
  794. // Update gamepad inputs
  795. static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
  796. static void ImGui_ImplGlfw_UpdateGamepads()
  797. {
  798. ImGuiIO& io = ImGui::GetIO();
  799. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs, but see #8075
  800. return;
  801. io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
  802. #if GLFW_HAS_GAMEPAD_API && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3)
  803. GLFWgamepadstate gamepad;
  804. if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad))
  805. return;
  806. #define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0)
  807. #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)
  808. #else
  809. int axes_count = 0, buttons_count = 0;
  810. const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
  811. const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
  812. if (axes_count == 0 || buttons_count == 0)
  813. return;
  814. #define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0)
  815. #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)
  816. #endif
  817. io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
  818. MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7);
  819. MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6);
  820. MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square
  821. MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle
  822. MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle
  823. MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross
  824. MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13);
  825. MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11);
  826. MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10);
  827. MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12);
  828. MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4);
  829. MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5);
  830. MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f);
  831. MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f);
  832. MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8);
  833. MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9);
  834. MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f);
  835. MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f);
  836. MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f);
  837. MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f);
  838. MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f);
  839. MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f);
  840. MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f);
  841. MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f);
  842. #undef MAP_BUTTON
  843. #undef MAP_ANALOG
  844. }
  845. // - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend.
  846. // - Apple platforms use FramebufferScale so we always return 1.0f.
  847. // - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle.
  848. float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window)
  849. {
  850. #if GLFW_HAS_X11_OR_WAYLAND
  851. if (ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window))
  852. if (bd->IsWayland)
  853. return 1.0f;
  854. #endif
  855. #if GLFW_HAS_PER_MONITOR_DPI && !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(__ANDROID__))
  856. float x_scale, y_scale;
  857. glfwGetWindowContentScale(window, &x_scale, &y_scale);
  858. return x_scale;
  859. #else
  860. IM_UNUSED(window);
  861. return 1.0f;
  862. #endif
  863. }
  864. float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor)
  865. {
  866. #if GLFW_HAS_X11_OR_WAYLAND
  867. if (ImGui_ImplGlfw_IsWayland()) // We can't access our bd->IsWayland cache for a monitor.
  868. return 1.0f;
  869. #endif
  870. #if GLFW_HAS_PER_MONITOR_DPI && !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(__ANDROID__))
  871. float x_scale, y_scale;
  872. glfwGetMonitorContentScale(monitor, &x_scale, &y_scale);
  873. return x_scale;
  874. #else
  875. IM_UNUSED(monitor);
  876. return 1.0f;
  877. #endif
  878. }
  879. static void ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(GLFWwindow* window, ImVec2* out_size, ImVec2* out_framebuffer_scale)
  880. {
  881. int w, h;
  882. int display_w, display_h;
  883. glfwGetWindowSize(window, &w, &h);
  884. glfwGetFramebufferSize(window, &display_w, &display_h);
  885. float fb_scale_x = (w > 0) ? (float)display_w / (float)w : 1.0f;
  886. float fb_scale_y = (h > 0) ? (float)display_h / (float)h : 1.0f;
  887. #if GLFW_HAS_X11_OR_WAYLAND
  888. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window);
  889. if (!bd->IsWayland)
  890. fb_scale_x = fb_scale_y = 1.0f;
  891. #endif
  892. if (out_size != nullptr)
  893. *out_size = ImVec2((float)w, (float)h);
  894. if (out_framebuffer_scale != nullptr)
  895. *out_framebuffer_scale = ImVec2(fb_scale_x, fb_scale_y);
  896. }
  897. void ImGui_ImplGlfw_NewFrame()
  898. {
  899. ImGuiIO& io = ImGui::GetIO();
  900. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  901. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?");
  902. // Setup main viewport size (every frame to accommodate for window resizing)
  903. ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(bd->Window, &io.DisplaySize, &io.DisplayFramebufferScale);
  904. // Setup time step
  905. // (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)
  906. double current_time = glfwGetTime();
  907. if (current_time <= bd->Time)
  908. current_time = bd->Time + 0.00001f;
  909. io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
  910. bd->Time = current_time;
  911. ImGui_ImplGlfw_UpdateMouseData();
  912. ImGui_ImplGlfw_UpdateMouseCursor();
  913. // Update game controllers (if enabled and available)
  914. ImGui_ImplGlfw_UpdateGamepads();
  915. }
  916. // GLFW doesn't provide a portable sleep function
  917. void ImGui_ImplGlfw_Sleep(int milliseconds)
  918. {
  919. #ifdef _WIN32
  920. ::Sleep(milliseconds);
  921. #else
  922. usleep(milliseconds * 1000);
  923. #endif
  924. }
  925. #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
  926. static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data)
  927. {
  928. ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
  929. double canvas_width, canvas_height;
  930. emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
  931. glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
  932. return true;
  933. }
  934. static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, const EmscriptenFullscreenChangeEvent* event, void* user_data)
  935. {
  936. ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
  937. double canvas_width, canvas_height;
  938. emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
  939. glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
  940. return true;
  941. }
  942. // 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query.
  943. // STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID.
  944. void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_selector)
  945. {
  946. IM_ASSERT(canvas_selector != nullptr);
  947. ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
  948. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?");
  949. bd->CanvasSelector = canvas_selector;
  950. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, bd, false, ImGui_ImplGlfw_OnCanvasSizeChange);
  951. emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, bd, false, ImGui_ImplEmscripten_FullscreenChangeCallback);
  952. // Change the size of the GLFW window according to the size of the canvas
  953. ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd);
  954. // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096)
  955. // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves.
  956. // FIXME: May break chaining in case user registered their own Emscripten callback?
  957. emscripten_set_wheel_callback(bd->CanvasSelector, bd, false, ImGui_ImplEmscripten_WheelCallback);
  958. }
  959. #elif defined(EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3)
  960. // When using --use-port=contrib.glfw3 for the GLFW implementation, you can override the behavior of this call
  961. // by invoking emscripten_glfw_make_canvas_resizable afterward.
  962. // See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Usage.md#how-to-make-the-canvas-resizable-by-the-user for an explanation
  963. void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector)
  964. {
  965. GLFWwindow* w = (GLFWwindow*)(EM_ASM_INT({ return Module.glfwGetWindow(UTF8ToString($0)); }, canvas_selector));
  966. IM_ASSERT(window == w); // Sanity check
  967. IM_UNUSED(w);
  968. emscripten_glfw_make_canvas_resizable(window, "window", nullptr);
  969. }
  970. #endif // #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3
  971. //-----------------------------------------------------------------------------
  972. #if defined(__clang__)
  973. #pragma clang diagnostic pop
  974. #endif
  975. #endif // #ifndef IMGUI_DISABLE