imgui_impl_glfw.cpp 77 KB

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