Debian Codegraph @

subprojects/imgui-1.91.6/backends/imgui_impl_glfw.cpp

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