1 // dear imgui: Platform Binding for GLFW
2 // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..)
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+)
5 
6 // Implemented features:
7 //  [X] Platform: Clipboard support.
8 //  [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
9 //  [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW.
10 //  [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE).
11 
12 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
13 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
14 // https://github.com/ocornut/imgui
15 
16 // CHANGELOG
17 // (minor and older changes stripped away, please see git history for details)
18 //  2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
19 //  2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
20 //  2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
21 //  2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
22 //  2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
23 //  2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
24 //  2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
25 //  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
26 //  2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
27 //  2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
28 //  2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
29 //  2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
30 //  2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
31 //  2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
32 //  2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
33 
34 #include "imgui/imgui.h"
35 #include "imgui_impl_glfw.h"
36 
37 // GLFW
38 #define GLFW_INCLUDE_NONE
39 #include "glad/gl.h"
40 #include "GLFW/glfw3.h"
41 #ifdef _WIN32
42 #undef APIENTRY
43 #define GLFW_EXPOSE_NATIVE_WIN32
44 #include "GLFW/glfw3native.h"   // for glfwGetWin32Window
45 #endif
46 #define GLFW_HAS_WINDOW_TOPMOST     (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING
47 #define GLFW_HAS_WINDOW_HOVERED     (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED
48 #define GLFW_HAS_WINDOW_ALPHA       (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity
49 #define GLFW_HAS_PER_MONITOR_DPI    (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale
50 #define GLFW_HAS_VULKAN             (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface
51 
52 // Data
53 enum GlfwClientApi
54 {
55     GlfwClientApi_Unknown,
56     GlfwClientApi_OpenGL,
57     GlfwClientApi_Vulkan
58 };
59 static GLFWwindow*          g_Window = NULL;
60 static GlfwClientApi        g_ClientApi = GlfwClientApi_Unknown;
61 static double               g_Time = 0.0;
62 static bool                 g_MouseJustPressed[5] = { false, false, false, false, false };
63 static GLFWcursor*          g_MouseCursors[ImGuiMouseCursor_COUNT] = { 0 };
64 
65 // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
66 static GLFWmousebuttonfun   g_PrevUserCallbackMousebutton = NULL;
67 static GLFWscrollfun        g_PrevUserCallbackScroll = NULL;
68 static GLFWkeyfun           g_PrevUserCallbackKey = NULL;
69 static GLFWcharfun          g_PrevUserCallbackChar = NULL;
70 
ImGui_ImplGlfw_GetClipboardText(void * user_data)71 static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
72 {
73     return glfwGetClipboardString((GLFWwindow*)user_data);
74 }
75 
ImGui_ImplGlfw_SetClipboardText(void * user_data,const char * text)76 static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
77 {
78     glfwSetClipboardString((GLFWwindow*)user_data, text);
79 }
80 
ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow * window,int button,int action,int mods)81 void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
82 {
83     if (g_PrevUserCallbackMousebutton != NULL)
84         g_PrevUserCallbackMousebutton(window, button, action, mods);
85 
86     if (action == GLFW_PRESS && button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed))
87         g_MouseJustPressed[button] = true;
88 }
89 
ImGui_ImplGlfw_ScrollCallback(GLFWwindow * window,double xoffset,double yoffset)90 void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
91 {
92     if (g_PrevUserCallbackScroll != NULL)
93         g_PrevUserCallbackScroll(window, xoffset, yoffset);
94 
95     ImGuiIO& io = ImGui::GetIO();
96     io.MouseWheelH += (float)xoffset;
97     io.MouseWheel += (float)yoffset;
98 }
99 
ImGui_ImplGlfw_KeyCallback(GLFWwindow * window,int key,int scancode,int action,int mods)100 void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
101 {
102     if (g_PrevUserCallbackKey != NULL)
103         g_PrevUserCallbackKey(window, key, scancode, action, mods);
104 
105     ImGuiIO& io = ImGui::GetIO();
106     if (action == GLFW_PRESS)
107         io.KeysDown[key] = true;
108     if (action == GLFW_RELEASE)
109         io.KeysDown[key] = false;
110 
111     // Modifiers are not reliable across systems
112     io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
113     io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
114     io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
115     io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
116 }
117 
ImGui_ImplGlfw_CharCallback(GLFWwindow * window,unsigned int c)118 void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
119 {
120     if (g_PrevUserCallbackChar != NULL)
121         g_PrevUserCallbackChar(window, c);
122 
123     ImGuiIO& io = ImGui::GetIO();
124     if (c > 0 && c < 0x10000)
125         io.AddInputCharacter((unsigned short)c);
126 }
127 
ImGui_ImplGlfw_Init(GLFWwindow * window,bool install_callbacks,GlfwClientApi client_api)128 static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
129 {
130     g_Window = window;
131     g_Time = 0.0;
132 
133     // Setup back-end capabilities flags
134     ImGuiIO& io = ImGui::GetIO();
135     io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;         // We can honor GetMouseCursor() values (optional)
136     io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;          // We can honor io.WantSetMousePos requests (optional, rarely used)
137     io.BackendPlatformName = "imgui_impl_glfw";
138 
139     // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
140     io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
141     io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
142     io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
143     io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
144     io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
145     io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
146     io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
147     io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
148     io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
149     io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
150     io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
151     io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
152     io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
153     io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
154     io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
155     io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
156     io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
157     io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
158     io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
159     io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
160     io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
161 
162     io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
163     io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
164     io.ClipboardUserData = g_Window;
165 #if defined(_WIN32)
166     io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);
167 #endif
168 
169     g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
170     g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
171     g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);   // FIXME: GLFW doesn't have this.
172     g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
173     g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
174     g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);  // FIXME: GLFW doesn't have this.
175     g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);  // FIXME: GLFW doesn't have this.
176     g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
177 
178     // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
179     g_PrevUserCallbackMousebutton = NULL;
180     g_PrevUserCallbackScroll = NULL;
181     g_PrevUserCallbackKey = NULL;
182     g_PrevUserCallbackChar = NULL;
183     if (install_callbacks)
184     {
185         g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
186         g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
187         g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
188         g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
189     }
190 
191     g_ClientApi = client_api;
192     return true;
193 }
194 
ImGui_ImplGlfw_InitForOpenGL(GLFWwindow * window,bool install_callbacks)195 bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
196 {
197     return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
198 }
199 
ImGui_ImplGlfw_InitForVulkan(GLFWwindow * window,bool install_callbacks)200 bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
201 {
202     return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
203 }
204 
ImGui_ImplGlfw_Shutdown()205 void ImGui_ImplGlfw_Shutdown()
206 {
207     for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
208     {
209         glfwDestroyCursor(g_MouseCursors[cursor_n]);
210         g_MouseCursors[cursor_n] = NULL;
211     }
212     g_ClientApi = GlfwClientApi_Unknown;
213 }
214 
ImGui_ImplGlfw_UpdateMousePosAndButtons()215 static void ImGui_ImplGlfw_UpdateMousePosAndButtons()
216 {
217     // Update buttons
218     ImGuiIO& io = ImGui::GetIO();
219     for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
220     {
221         // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
222         io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0;
223         g_MouseJustPressed[i] = false;
224     }
225 
226     // Update mouse position
227     const ImVec2 mouse_pos_backup = io.MousePos;
228     io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
229 #ifdef __EMSCRIPTEN__
230     const bool focused = true; // Emscripten
231 #else
232     const bool focused = glfwGetWindowAttrib(g_Window, GLFW_FOCUSED) != 0;
233 #endif
234     if (focused)
235     {
236         if (io.WantSetMousePos)
237         {
238             glfwSetCursorPos(g_Window, (double)mouse_pos_backup.x, (double)mouse_pos_backup.y);
239         }
240         else
241         {
242             double mouse_x, mouse_y;
243             glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
244             io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
245         }
246     }
247 }
248 
ImGui_ImplGlfw_UpdateMouseCursor()249 static void ImGui_ImplGlfw_UpdateMouseCursor()
250 {
251     ImGuiIO& io = ImGui::GetIO();
252     if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(g_Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
253         return;
254 
255     ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
256     if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
257     {
258         // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
259         glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
260     }
261     else
262     {
263         // Show OS mouse cursor
264         // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
265         glfwSetCursor(g_Window, g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
266         glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
267     }
268 }
269 
ImGui_ImplGlfw_NewFrame()270 void ImGui_ImplGlfw_NewFrame()
271 {
272     ImGuiIO& io = ImGui::GetIO();
273     IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
274 
275     // Setup display size (every frame to accommodate for window resizing)
276     int w, h;
277     int display_w, display_h;
278     glfwGetWindowSize(g_Window, &w, &h);
279     glfwGetFramebufferSize(g_Window, &display_w, &display_h);
280     io.DisplaySize = ImVec2((float)w, (float)h);
281     io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
282 
283     // Setup time step
284     double current_time = glfwGetTime();
285     io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
286     g_Time = current_time;
287 
288     ImGui_ImplGlfw_UpdateMousePosAndButtons();
289     ImGui_ImplGlfw_UpdateMouseCursor();
290 
291     // Gamepad navigation mapping [BETA]
292     memset(io.NavInputs, 0, sizeof(io.NavInputs));
293     if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad)
294     {
295         // Update gamepad inputs
296         #define MAP_BUTTON(NAV_NO, BUTTON_NO)       { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; }
297         #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; }
298         int axes_count = 0, buttons_count = 0;
299         const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
300         const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
301         MAP_BUTTON(ImGuiNavInput_Activate,   0);     // Cross / A
302         MAP_BUTTON(ImGuiNavInput_Cancel,     1);     // Circle / B
303         MAP_BUTTON(ImGuiNavInput_Menu,       2);     // Square / X
304         MAP_BUTTON(ImGuiNavInput_Input,      3);     // Triangle / Y
305         MAP_BUTTON(ImGuiNavInput_DpadLeft,   13);    // D-Pad Left
306         MAP_BUTTON(ImGuiNavInput_DpadRight,  11);    // D-Pad Right
307         MAP_BUTTON(ImGuiNavInput_DpadUp,     10);    // D-Pad Up
308         MAP_BUTTON(ImGuiNavInput_DpadDown,   12);    // D-Pad Down
309         MAP_BUTTON(ImGuiNavInput_FocusPrev,  4);     // L1 / LB
310         MAP_BUTTON(ImGuiNavInput_FocusNext,  5);     // R1 / RB
311         MAP_BUTTON(ImGuiNavInput_TweakSlow,  4);     // L1 / LB
312         MAP_BUTTON(ImGuiNavInput_TweakFast,  5);     // R1 / RB
313         MAP_ANALOG(ImGuiNavInput_LStickLeft, 0,  -0.3f,  -0.9f);
314         MAP_ANALOG(ImGuiNavInput_LStickRight,0,  +0.3f,  +0.9f);
315         MAP_ANALOG(ImGuiNavInput_LStickUp,   1,  +0.3f,  +0.9f);
316         MAP_ANALOG(ImGuiNavInput_LStickDown, 1,  -0.3f,  -0.9f);
317         #undef MAP_BUTTON
318         #undef MAP_ANALOG
319         if (axes_count > 0 && buttons_count > 0)
320             io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
321         else
322             io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
323     }
324 }
325