imgui_impl_glfw.cpp 51 KB

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