Debian Codegraph @

subprojects/imgui-1.91.6/imgui.cpp

raw
1 // dear imgui, v1.91.6
2 // (main code and documentation)
3
4 // Help:
5 // - See links below.
6 // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7 // - Read top of imgui.cpp for more details, links and comments.
8
9 // Resources:
10 // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11 // - Homepage ................... https://github.com/ocornut/imgui
12 // - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13 // - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!)
14 // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15 // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16 // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17 // - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18 // - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19 // - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20 // - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21 // - Issues & support ........... https://github.com/ocornut/imgui/issues
22 // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24 // For first-time users having issues compiling/linking/running/loading fonts:
25 // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26 // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28 // Copyright (c) 2014-2024 Omar Cornut
29 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30 // See LICENSE.txt for copyright and licensing details (standard MIT License).
31 // This library is free but needs your support to sustain development and maintenance.
32 // Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33 // PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34 // Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36 // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37 // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38 // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39 // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40 // to a better solution or official support for them.
41
42 /*
43
44 Index of this file:
45
46 DOCUMENTATION
47
48 - MISSION STATEMENT
49 - CONTROLS GUIDE
50 - PROGRAMMER GUIDE
51 - READ FIRST
52 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55 - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56 - API BREAKING CHANGES (read me when you update!)
57 - FREQUENTLY ASKED QUESTIONS (FAQ)
58 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60 CODE
61 (search for "[SECTION]" in the code to find them)
62
63 // [SECTION] INCLUDES
64 // [SECTION] FORWARD DECLARATIONS
65 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
66 // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
67 // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68 // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69 // [SECTION] MISC HELPERS/UTILITIES (File functions)
70 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71 // [SECTION] MISC HELPERS/UTILITIES (Color functions)
72 // [SECTION] ImGuiStorage
73 // [SECTION] ImGuiTextFilter
74 // [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75 // [SECTION] ImGuiListClipper
76 // [SECTION] STYLING
77 // [SECTION] RENDER HELPERS
78 // [SECTION] INITIALIZATION, SHUTDOWN
79 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80 // [SECTION] ID STACK
81 // [SECTION] INPUTS
82 // [SECTION] ERROR CHECKING, STATE RECOVERY
83 // [SECTION] ITEM SUBMISSION
84 // [SECTION] LAYOUT
85 // [SECTION] SCROLLING
86 // [SECTION] TOOLTIPS
87 // [SECTION] POPUPS
88 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89 // [SECTION] DRAG AND DROP
90 // [SECTION] LOGGING/CAPTURING
91 // [SECTION] SETTINGS
92 // [SECTION] LOCALIZATION
93 // [SECTION] VIEWPORTS, PLATFORM WINDOWS
94 // [SECTION] PLATFORM DEPENDENT HELPERS
95 // [SECTION] METRICS/DEBUGGER WINDOW
96 // [SECTION] DEBUG LOG WINDOW
97 // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
98
99 */
100
101 //-----------------------------------------------------------------------------
102 // DOCUMENTATION
103 //-----------------------------------------------------------------------------
104
105 /*
106
107 MISSION STATEMENT
108 =================
109
110 - Easy to use to create code-driven and data-driven tools.
111 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
112 - Easy to hack and improve.
113 - Minimize setup and maintenance.
114 - Minimize state storage on user side.
115 - Minimize state synchronization.
116 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
117 - Efficient runtime and memory consumption.
118
119 Designed primarily for developers and content-creators, not the typical end-user!
120 Some of the current weaknesses (which we aim to address in the future) includes:
121
122 - Doesn't look fancy.
123 - Limited layout features, intricate layouts are typically crafted in code.
124
125
126 CONTROLS GUIDE
127 ==============
128
129 - MOUSE CONTROLS
130 - Mouse wheel: Scroll vertically.
131 - SHIFT+Mouse wheel: Scroll horizontally.
132 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
133 - Click ^, Double-Click title: Collapse window.
134 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
135 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
136 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
137
138 - TEXT EDITOR
139 - Hold SHIFT or Drag Mouse: Select text.
140 - CTRL+Left/Right: Word jump.
141 - CTRL+Shift+Left/Right: Select words.
142 - CTRL+A or Double-Click: Select All.
143 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
144 - CTRL+Z, CTRL+Y: Undo, Redo.
145 - ESCAPE: Revert text to its original value.
146 - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
147
148 - KEYBOARD CONTROLS
149 - Basic:
150 - Tab, SHIFT+Tab Cycle through text editable fields.
151 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
152 - CTRL+Click Input text into a Slider or Drag widget.
153 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
154 - Tab, SHIFT+Tab: Cycle through every items.
155 - Arrow keys Move through items using directional navigation. Tweak value.
156 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
157 - Enter Activate item (prefer text input when possible).
158 - Space Activate item (prefer tweaking with arrows when possible).
159 - Escape Deactivate item, leave child window, close popup.
160 - Page Up, Page Down Previous page, next page.
161 - Home, End Scroll to top, scroll to bottom.
162 - Alt Toggle between scrolling layer and menu layer.
163 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
164 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
165 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
166 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
167 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
168
169 - GAMEPAD CONTROLS
170 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
171 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
172 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
173 - Backend support: backend needs to:
174 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
175 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
176 Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
177 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
178 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
179
180 - REMOTE INPUTS SHARING & MOUSE EMULATION
181 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
182 - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
183 in order to share your PC mouse/keyboard.
184 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
185 - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag.
186 Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
187 When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
188 When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
189 (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
190 (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
191 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
192
193
194 PROGRAMMER GUIDE
195 ================
196
197 READ FIRST
198 ----------
199 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
200 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
201 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
202 data retention on your side, less state duplication, less state synchronization, fewer bugs.
203 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
204 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
205 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
206 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
207 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
208 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
209 For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
210 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
211 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
212 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
213 If you get an assert, read the messages and comments around the assert.
214 - This codebase aims to be highly optimized:
215 - A typical idle frame should never call malloc/free.
216 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
217 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
218 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
219 - This codebase aims to be both highly opinionated and highly flexible:
220 - This code works because of the things it choose to solve or not solve.
221 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
222 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
223 This is to increase compatibility, increase maintainability and facilitate use from other languages.
224 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
225 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
226 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
227 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
228 (so don't use ImVector in your code or at our own risk!).
229 - Building: We don't use nor mandate a build system for the main library.
230 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
231 This is also because providing a build system for the main library would be of little-value.
232 The build problems are almost never coming from the main library but from specific backends.
233
234
235 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
236 ----------------------------------------------
237 - Update submodule or copy/overwrite every file.
238 - About imconfig.h:
239 - You may modify your copy of imconfig.h, in this case don't overwrite it.
240 - or you may locally branch to modify imconfig.h and merge/rebase latest.
241 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
242 specify a custom path for your imconfig.h file and instead not have to modify the default one.
243
244 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
245 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
246 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
247 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
248 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
249 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
250 likely be a comment about it. Please report any issue to the GitHub page!
251 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
252 - Try to keep your copy of Dear ImGui reasonably up to date!
253
254
255 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
256 ---------------------------------------------------------------
257 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
258 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
259 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
260 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
261 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
262 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
263 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
264 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
265 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
266 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
267 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
268 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
269
270
271 HOW A SIMPLE APPLICATION MAY LOOK LIKE
272 --------------------------------------
273 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
274 The sub-folders in examples/ contain examples applications following this structure.
275
276 // Application init: create a dear imgui context, setup some options, load fonts
277 ImGui::CreateContext();
278 ImGuiIO& io = ImGui::GetIO();
279 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
280 // TODO: Fill optional fields of the io structure later.
281 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
282
283 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
284 ImGui_ImplWin32_Init(hwnd);
285 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
286
287 // Application main loop
288 while (true)
289 {
290 // Feed inputs to dear imgui, start new frame
291 ImGui_ImplDX11_NewFrame();
292 ImGui_ImplWin32_NewFrame();
293 ImGui::NewFrame();
294
295 // Any application code here
296 ImGui::Text("Hello, world!");
297
298 // Render dear imgui into screen
299 ImGui::Render();
300 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
301 g_pSwapChain->Present(1, 0);
302 }
303
304 // Shutdown
305 ImGui_ImplDX11_Shutdown();
306 ImGui_ImplWin32_Shutdown();
307 ImGui::DestroyContext();
308
309 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
310
311 // Application init: create a dear imgui context, setup some options, load fonts
312 ImGui::CreateContext();
313 ImGuiIO& io = ImGui::GetIO();
314 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
315 // TODO: Fill optional fields of the io structure later.
316 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
317
318 // Build and load the texture atlas into a texture
319 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
320 int width, height;
321 unsigned char* pixels = nullptr;
322 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
323
324 // At this point you've got the texture data and you need to upload that to your graphic system:
325 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
326 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
327 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
328 io.Fonts->SetTexID((void*)texture);
329
330 // Application main loop
331 while (true)
332 {
333 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
334 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
335 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
336 io.DisplaySize.x = 1920.0f; // set the current display width
337 io.DisplaySize.y = 1280.0f; // set the current display height here
338 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
339 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
340 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
341
342 // Call NewFrame(), after this point you can use ImGui::* functions anytime
343 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
344 ImGui::NewFrame();
345
346 // Most of your application code here
347 ImGui::Text("Hello, world!");
348 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
349 MyGameRender(); // may use any Dear ImGui functions as well!
350
351 // Render dear imgui, swap buffers
352 // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
353 ImGui::EndFrame();
354 ImGui::Render();
355 ImDrawData* draw_data = ImGui::GetDrawData();
356 MyImGuiRenderFunction(draw_data);
357 SwapBuffers();
358 }
359
360 // Shutdown
361 ImGui::DestroyContext();
362
363 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
364 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
365 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
366
367
368 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
369 ---------------------------------------------
370 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
371
372 void MyImGuiRenderFunction(ImDrawData* draw_data)
373 {
374 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
375 // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
376 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
377 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
378 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
379 ImVec2 clip_off = draw_data->DisplayPos;
380 for (int n = 0; n < draw_data->CmdListsCount; n++)
381 {
382 const ImDrawList* cmd_list = draw_data->CmdLists[n];
383 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
384 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
385 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
386 {
387 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
388 if (pcmd->UserCallback)
389 {
390 pcmd->UserCallback(cmd_list, pcmd);
391 }
392 else
393 {
394 // Project scissor/clipping rectangles into framebuffer space
395 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
396 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
397 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
398 continue;
399
400 // We are using scissoring to clip some objects. All low-level graphics API should support it.
401 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
402 // (some elements visible outside their bounds) but you can fix that once everything else works!
403 // - Clipping coordinates are provided in imgui coordinates space:
404 // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
405 // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
406 // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
407 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
408 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
409 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
410
411 // The texture for the draw call is specified by pcmd->GetTexID().
412 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
413 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
414
415 // Render 'pcmd->ElemCount/3' indexed triangles.
416 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
417 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
418 }
419 }
420 }
421 }
422
423
424 API BREAKING CHANGES
425 ====================
426
427 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
428 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
429 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
430 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
431
432 - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions.
433 As a result, old .ini data may be partially lost (docking and tables information particularly).
434 Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data.
435 - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
436 - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
437 - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
438 - pre-1.87 backends are not supported:
439 - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
440 - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
441 - for more reference:
442 - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
443 - read https://github.com/ocornut/imgui/issues/4921
444 - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
445 - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
446 - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
447 - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
448 - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
449 moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
450 kept legacy names (will obsolete) + code that copies settings once the first time. Dynamically changing the old value won't work. Switch to using the new value!
451 - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
452 this removes the requirement to redefine it for backends which are e.g. storing descriptor sets or other 64-bits structures when building on 32-bits archs. It therefore simplify various building scripts/helpers.
453 you may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID' when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
454 in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
455 - May warn: ImGui::Image((void*)MyTextureData, ...);
456 - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
457 - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
458 - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
459 - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
460 - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
461 although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
462 - 2024/09/10 (1.91.2) - internals: using multiple overlayed ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
463 it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
464 - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
465 - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
466 - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
467 - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line.
468 - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660)
469 - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
470 - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278)
471 - access those via GetPlatformIO() instead of GetIO().
472 some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol.
473 - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder:
474 - old ImageButton() before 1.89 used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID)
475 - new ImageButton() since 1.89 requires an explicit 'const char* str_id'
476 - old ImageButton() before 1.89 had frame_padding' override argument.
477 - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar().
478 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
479 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
480 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
481 - you can use: GetContentRegionAvail().x
482 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
483 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
484 - instead of: GetContentRegionMax()
485 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
486 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
487 - you can use: GetContentRegionAvail() // when called from left edge of window
488 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
489 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
490 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
491 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
492 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
493 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
494 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
495 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
496 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
497 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
498 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
499 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
500 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
501 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
502 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
503 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
504 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
505 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
506 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
507 - old: CaptureKeyboardFromApp(bool)
508 - new: SetNextFrameWantCaptureKeyboard(bool)
509 - old: CaptureMouseFromApp(bool)
510 - new: SetNextFrameWantCaptureMouse(bool)
511 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
512 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
513 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
514 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
515 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
516 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
517 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
518 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
519 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
520 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
521 for various reasons those changes makes sense. They are being made because making some of those API public.
522 only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
523 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
524 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
525 - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
526 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
527 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
528 - old: TreeNode("##Hidden"); SameLine(); Text("Hello"); // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
529 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
530 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
531 You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
532 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
533 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
534 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
535 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
536 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
537 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
538 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
539 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
540 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
541 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
542 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
543 those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
544 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
545 - old: BeginChild("Name", size, true)
546 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
547 - old: BeginChild("Name", size, false)
548 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
549 **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'**
550 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
551 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
552 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
553 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
554 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
555 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
556 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
557 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
558 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
559 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
560 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
561 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
562 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
563 - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
564 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
565 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
566 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
567 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
568 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
569 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
570 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
571 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
572 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
573 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
574 - ListBoxFooter() -> use EndListBox()
575 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
576 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
577 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
578 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
579 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
580 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
581 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
582 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
583 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
584 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
585 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
586 it has been frequently requested by people to use our own. We had an opt-in define which was
587 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
588 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
589 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
590 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
591 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
592 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
593 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
594 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
595 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
596 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
597 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
598 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
599 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
600 exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
601 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
602 this will require uses of legacy backend-dependent indices to be casted, e.g.
603 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
604 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
605 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
606 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
607 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
608 - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
609 - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
610 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
611 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
612 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
613 - previously this would make the window content size ~200x200:
614 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
615 - instead, please submit an item:
616 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
617 - alternative:
618 Begin(...) + Dummy(ImVec2(200,200)) + End();
619 - content size is now only extended when submitting an item!
620 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
621 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
622 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
623 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
624 - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
625 - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
626 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
627 - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
628 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
629 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
630 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
631 - Official backends from 1.87+ -> no issue.
632 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
633 - Custom backends not writing to io.NavInputs[] -> no issue.
634 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
635 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
636 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
637 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
638 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
639 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
640 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
641 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
642 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
643 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
644 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
645 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
646 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
647 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
648 read https://github.com/ocornut/imgui/issues/4921 for details.
649 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
650 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
651 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
652 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
653 - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
654 - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
655 - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
656 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
657 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
658 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
659 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
660 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
661 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
662 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
663 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
664 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
665 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
666 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
667 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
668 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
669 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
670 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
671 - if you are using official backends from the source tree: you have nothing to do.
672 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
673 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
674 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
675 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
676 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
677 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
678 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
679 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
680 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
681 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
682 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
683 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
684 the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
685 legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
686 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
687 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
688 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
689 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
690 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
691 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
692 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
693 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
694 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
695 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
696 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
697 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
698 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
699 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
700 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
701 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
702 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
703 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
704 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
705 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
706 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
707 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
708 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
709 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
710 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
711 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
712 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
713 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
714 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
715 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
716 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
717 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
718 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
719 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
720 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
721 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
722 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
723 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
724 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
725 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
726 - if you omitted the 'power' parameter (likely!), you are not affected.
727 - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
728 - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
729 see https://github.com/ocornut/imgui/issues/3361 for all details.
730 kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
731 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
732 - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
733 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
734 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
735 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
736 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
737 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
738 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
739 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
740 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
741 - ShowTestWindow() -> use ShowDemoWindow()
742 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
743 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
744 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
745 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
746 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
747 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
748 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
749 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
750 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
751 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
752 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
753 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
754 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
755 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
756 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
757 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
758 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
759 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
760 - ImFont::Glyph -> use ImFontGlyph
761 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
762 if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
763 The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
764 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
765 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
766 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
767 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
768 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
769 overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
770 This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
771 Please reach out if you are affected.
772 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
773 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
774 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
775 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
776 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
777 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
778 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
779 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
780 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
781 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
782 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
783 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
784 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
785 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
786 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
787 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
788 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
789 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
790 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
791 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
792 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
793 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
794 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
795 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
796 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
797 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
798 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
799 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
800 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
801 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
802 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
803 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
804 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
805 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
806 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
807 To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
808 If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
809 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
810 consistent with other functions. Kept redirection functions (will obsolete).
811 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
812 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
813 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
814 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
815 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
816 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
817 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
818 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
819 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
820 - removed Shutdown() function, as DestroyContext() serve this purpose.
821 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
822 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
823 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
824 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
825 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
826 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
827 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
828 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
829 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
830 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
831 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
832 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
833 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
834 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
835 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
836 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
837 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
838 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
839 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
840 Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
841 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
842 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
843 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
844 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
845 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
846 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
847 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
848 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
849 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
850 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
851 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
852 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
853 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
854 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
855 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
856 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
857 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
858 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
859 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
860 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
861 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
862 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
863 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
864 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
865 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
866 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
867 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
868 - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
869 - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
870 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
871 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
872 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
873 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
874 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
875 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
876 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
877 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
878 If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
879 This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
880 ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
881 If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
882 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
883 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
884 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
885 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
886 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
887 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
888 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
889 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
890 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
891 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
892 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
893 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
894 GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
895 GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
896 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
897 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
898 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
899 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
900 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
901 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
902 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
903 - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
904 - the signature of the io.RenderDrawListsFn handler has changed!
905 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
906 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
907 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
908 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
909 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
910 - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
911 - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
912 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
913 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
914 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
915 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
916 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
917 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
918 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
919 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
920 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
921 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
922 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
923 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
924 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
925 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
926 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
927 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
928 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
929 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
930 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
931 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
932 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
933 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
934 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
935 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
936 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
937 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
938 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
939 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
940 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
941 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
942 you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
943 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
944 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
945 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
946 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
947 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
948 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
949 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
950 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
951 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
952 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
953 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
954 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
955 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
956 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
957
958
959 FREQUENTLY ASKED QUESTIONS (FAQ)
960 ================================
961
962 Read all answers online:
963 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
964 Read all answers locally (with a text editor or ideally a Markdown viewer):
965 docs/FAQ.md
966 Some answers are copied down here to facilitate searching in code.
967
968 Q&A: Basics
969 ===========
970
971 Q: Where is the documentation?
972 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
973 - Run the examples/ applications and explore them.
974 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
975 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
976 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
977 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
978 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
979 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
980 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
981 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
982 - Your programming IDE is your friend, find the type or function declaration to find comments
983 associated with it.
984
985 Q: What is this library called?
986 Q: Which version should I get?
987 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
988 >> See https://www.dearimgui.com/faq for details.
989
990 Q&A: Integration
991 ================
992
993 Q: How to get started?
994 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
995
996 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
997 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
998 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
999
1000 Q. How can I enable keyboard or gamepad controls?
1001 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
1002 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
1003 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
1004 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
1005 >> See https://www.dearimgui.com/faq
1006
1007 Q&A: Usage
1008 ----------
1009
1010 Q: About the ID Stack system..
1011 - Why is my widget not reacting when I click on it?
1012 - How can I have widgets with an empty label?
1013 - How can I have multiple widgets with the same label?
1014 - How can I have multiple windows with the same label?
1015 Q: How can I display an image? What is ImTextureID, how does it work?
1016 Q: How can I use my own math types instead of ImVec2?
1017 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
1018 Q: How can I display custom shapes? (using low-level ImDrawList API)
1019 >> See https://www.dearimgui.com/faq
1020
1021 Q&A: Fonts, Text
1022 ================
1023
1024 Q: How should I handle DPI in my application?
1025 Q: How can I load a different font than the default?
1026 Q: How can I easily use icons in my application?
1027 Q: How can I load multiple fonts?
1028 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
1029 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
1030
1031 Q&A: Concerns
1032 =============
1033
1034 Q: Who uses Dear ImGui?
1035 Q: Can you create elaborate/serious tools with Dear ImGui?
1036 Q: Can you reskin the look of Dear ImGui?
1037 Q: Why using C++ (as opposed to C)?
1038 >> See https://www.dearimgui.com/faq
1039
1040 Q&A: Community
1041 ==============
1042
1043 Q: How can I help?
1044 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1045 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1046 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1047 >>> See https://github.com/ocornut/imgui/wiki/Funding
1048 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1049 - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1050 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1051 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1052 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1053 - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1054
1055 */
1056
1057 //-------------------------------------------------------------------------
1058 // [SECTION] INCLUDES
1059 //-------------------------------------------------------------------------
1060
1061 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1062 #define _CRT_SECURE_NO_WARNINGS
1063 #endif
1064
1065 #ifndef IMGUI_DEFINE_MATH_OPERATORS
1066 #define IMGUI_DEFINE_MATH_OPERATORS
1067 #endif
1068
1069 #include "imgui.h"
1070 #ifndef IMGUI_DISABLE
1071 #include "imgui_internal.h"
1072
1073 // System includes
1074 #include <stdio.h> // vsnprintf, sscanf, printf
1075 #include <stdint.h> // intptr_t
1076
1077 // [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1078 #if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1079 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1080 #endif
1081
1082 // [Windows] OS specific includes (optional)
1083 #if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1084 #define IMGUI_DISABLE_WIN32_FUNCTIONS
1085 #endif
1086 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1087 #ifndef WIN32_LEAN_AND_MEAN
1088 #define WIN32_LEAN_AND_MEAN
1089 #endif
1090 #ifndef NOMINMAX
1091 #define NOMINMAX
1092 #endif
1093 #ifndef __MINGW32__
1094 #include <Windows.h> // _wfopen, OpenClipboard
1095 #else
1096 #include <windows.h>
1097 #endif
1098 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1099 // The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1100 #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1101 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1102 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1103 #endif
1104 #endif
1105
1106 // [Apple] OS specific includes
1107 #if defined(__APPLE__)
1108 #include <TargetConditionals.h>
1109 #endif
1110
1111 // Visual Studio warnings
1112 #ifdef _MSC_VER
1113 #pragma warning (disable: 4127) // condition expression is constant
1114 #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1115 #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1116 #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1117 #endif
1118 #pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1119 #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1120 #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1121 #endif
1122
1123 // Clang/GCC warnings with -Weverything
1124 #if defined(__clang__)
1125 #if __has_warning("-Wunknown-warning-option")
1126 #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1127 #endif
1128 #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1129 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1130 #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1131 #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1132 #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1133 #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1134 #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1135 #pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1136 #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1137 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1138 #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1139 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1140 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1141 #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
1142 #elif defined(__GNUC__)
1143 // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1144 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1145 #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1146 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1147 #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1148 #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1149 #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1150 #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1151 #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1152 #pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1153 #endif
1154
1155 // Debug options
1156 #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
1157 #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1158
1159 // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1160 static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1161 static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1162
1163 static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1164
1165 // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1166 static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1167 static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1168 static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1169
1170 // Tooltip offset
1171 static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1172 static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale
1173 static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale
1174
1175 //-------------------------------------------------------------------------
1176 // [SECTION] FORWARD DECLARATIONS
1177 //-------------------------------------------------------------------------
1178
1179 static void SetCurrentWindow(ImGuiWindow* window);
1180 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1181 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1182
1183 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1184
1185 // Settings
1186 static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1187 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1188 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1189 static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1190 static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1191
1192 // Platform Dependents default implementation for ImGuiPlatformIO functions
1193 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx);
1194 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text);
1195 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1196 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1197
1198 namespace ImGui
1199 {
1200 // Item
1201 static void ItemHandleShortcut(ImGuiID id);
1202
1203 // Navigation
1204 static void NavUpdate();
1205 static void NavUpdateWindowing();
1206 static void NavUpdateWindowingOverlay();
1207 static void NavUpdateCancelRequest();
1208 static void NavUpdateCreateMoveRequest();
1209 static void NavUpdateCreateTabbingRequest();
1210 static float NavUpdatePageUpPageDown();
1211 static inline void NavUpdateAnyRequestFlag();
1212 static void NavUpdateCreateWrappingRequest();
1213 static void NavEndFrame();
1214 static bool NavScoreItem(ImGuiNavItemData* result);
1215 static void NavApplyItemToResult(ImGuiNavItemData* result);
1216 static void NavProcessItem();
1217 static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1218 static ImGuiInputSource NavCalcPreferredRefPosSource();
1219 static ImVec2 NavCalcPreferredRefPos();
1220 static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1221 static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1222 static void NavRestoreLayer(ImGuiNavLayer layer);
1223 static int FindWindowFocusIndex(ImGuiWindow* window);
1224
1225 // Error Checking and Debug Tools
1226 static void ErrorCheckNewFrameSanityChecks();
1227 static void ErrorCheckEndFrameSanityChecks();
1228 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
1229 static void UpdateDebugToolItemPicker();
1230 static void UpdateDebugToolStackQueries();
1231 static void UpdateDebugToolFlashStyleColor();
1232 #endif
1233
1234 // Inputs
1235 static void UpdateKeyboardInputs();
1236 static void UpdateMouseInputs();
1237 static void UpdateMouseWheel();
1238 static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1239
1240 // Misc
1241 static void UpdateSettings();
1242 static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1243 static void RenderWindowOuterBorders(ImGuiWindow* window);
1244 static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1245 static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1246 static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1247 static void RenderDimmedBackgrounds();
1248 static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1249
1250 // Viewports
1251 const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1252 static void UpdateViewportsNewFrame();
1253
1254 }
1255
1256 //-----------------------------------------------------------------------------
1257 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
1258 //-----------------------------------------------------------------------------
1259
1260 // DLL users:
1261 // - Heaps and globals are not shared across DLL boundaries!
1262 // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1263 // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1264 // - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1265 // - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1266
1267 // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1268 // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1269 // Change to a different context by calling ImGui::SetCurrentContext().
1270 // - Important: Dear ImGui functions are not thread-safe because of this pointer.
1271 // If you want thread-safety to allow N threads to access N different contexts:
1272 // - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1273 // struct ImGuiContext;
1274 // extern thread_local ImGuiContext* MyImGuiTLS;
1275 // #define GImGui MyImGuiTLS
1276 // And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1277 // - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1278 // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1279 // - DLL users: read comments above.
1280 #ifndef GImGui
1281 ImGuiContext* GImGui = NULL;
1282 #endif
1283
1284 // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1285 // - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1286 // - DLL users: read comments above.
1287 #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1288 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1289 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1290 #else
1291 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1292 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1293 #endif
1294 static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1295 static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1296 static void* GImAllocatorUserData = NULL;
1297
1298 //-----------------------------------------------------------------------------
1299 // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
1300 //-----------------------------------------------------------------------------
1301
1302 ImGuiStyle::ImGuiStyle()
1303 {
1304 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1305 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1306 WindowPadding = ImVec2(8,8); // Padding within a window
1307 WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1308 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1309 WindowMinSize = ImVec2(32,32); // Minimum window size
1310 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1311 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1312 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1313 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1314 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1315 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1316 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1317 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1318 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1319 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1320 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1321 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1322 TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1323 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1324 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1325 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1326 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1327 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1328 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1329 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1330 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1331 TabBorderSize = 0.0f; // Thickness of border around tabs.
1332 TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1333 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1334 TabBarOverlineSize = 2.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1335 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1336 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1337 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1338 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1339 SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1340 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText()
1341 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1342 SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1343 DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1344 DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1345 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1346 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1347 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1348 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1349 CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1350 CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1351
1352 // Behaviors
1353 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1354 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1355 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1356 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1357 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1358
1359 // Default theme
1360 ImGui::StyleColorsDark(this);
1361 }
1362
1363 // To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1364 // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1365 void ImGuiStyle::ScaleAllSizes(float scale_factor)
1366 {
1367 WindowPadding = ImTrunc(WindowPadding * scale_factor);
1368 WindowRounding = ImTrunc(WindowRounding * scale_factor);
1369 WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1370 ChildRounding = ImTrunc(ChildRounding * scale_factor);
1371 PopupRounding = ImTrunc(PopupRounding * scale_factor);
1372 FramePadding = ImTrunc(FramePadding * scale_factor);
1373 FrameRounding = ImTrunc(FrameRounding * scale_factor);
1374 ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1375 ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1376 CellPadding = ImTrunc(CellPadding * scale_factor);
1377 TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1378 IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1379 ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1380 ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1381 ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1382 GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1383 GrabRounding = ImTrunc(GrabRounding * scale_factor);
1384 LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1385 TabRounding = ImTrunc(TabRounding * scale_factor);
1386 TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1387 TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
1388 SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1389 DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1390 DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1391 MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1392 }
1393
1394 ImGuiIO::ImGuiIO()
1395 {
1396 // Most fields are initialized with zero
1397 memset(this, 0, sizeof(*this));
1398 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1399
1400 // Settings
1401 ConfigFlags = ImGuiConfigFlags_None;
1402 BackendFlags = ImGuiBackendFlags_None;
1403 DisplaySize = ImVec2(-1.0f, -1.0f);
1404 DeltaTime = 1.0f / 60.0f;
1405 IniSavingRate = 5.0f;
1406 IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1407 LogFilename = "imgui_log.txt";
1408 UserData = NULL;
1409
1410 Fonts = NULL;
1411 FontGlobalScale = 1.0f;
1412 FontDefault = NULL;
1413 FontAllowUserScaling = false;
1414 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1415
1416 // Keyboard/Gamepad Navigation options
1417 ConfigNavSwapGamepadButtons = false;
1418 ConfigNavMoveSetMousePos = false;
1419 ConfigNavCaptureKeyboard = true;
1420 ConfigNavEscapeClearFocusItem = true;
1421 ConfigNavEscapeClearFocusWindow = false;
1422 ConfigNavCursorVisibleAuto = true;
1423 ConfigNavCursorVisibleAlways = false;
1424
1425 // Miscellaneous options
1426 MouseDrawCursor = false;
1427 #ifdef __APPLE__
1428 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1429 #else
1430 ConfigMacOSXBehaviors = false;
1431 #endif
1432 ConfigInputTrickleEventQueue = true;
1433 ConfigInputTextCursorBlink = true;
1434 ConfigInputTextEnterKeepActive = false;
1435 ConfigDragClickToInputText = false;
1436 ConfigWindowsResizeFromEdges = true;
1437 ConfigWindowsMoveFromTitleBarOnly = false;
1438 ConfigWindowsCopyContentsWithCtrlC = false;
1439 ConfigScrollbarScrollByPage = true;
1440 ConfigMemoryCompactTimer = 60.0f;
1441 ConfigDebugIsDebuggerPresent = false;
1442 ConfigDebugHighlightIdConflicts = true;
1443 ConfigDebugBeginReturnValueOnce = false;
1444 ConfigDebugBeginReturnValueLoop = false;
1445
1446 ConfigErrorRecovery = true;
1447 ConfigErrorRecoveryEnableAssert = true;
1448 ConfigErrorRecoveryEnableDebugLog = true;
1449 ConfigErrorRecoveryEnableTooltip = true;
1450
1451 // Inputs Behaviors
1452 MouseDoubleClickTime = 0.30f;
1453 MouseDoubleClickMaxDist = 6.0f;
1454 MouseDragThreshold = 6.0f;
1455 KeyRepeatDelay = 0.275f;
1456 KeyRepeatRate = 0.050f;
1457
1458 // Platform Functions
1459 // Note: Initialize() will setup default clipboard/ime handlers.
1460 BackendPlatformName = BackendRendererName = NULL;
1461 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1462
1463 // Input (NB: we already have memset zero the entire structure!)
1464 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1465 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1466 MouseSource = ImGuiMouseSource_Mouse;
1467 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1468 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1469 AppAcceptingEvents = true;
1470 }
1471
1472 // Pass in translated ASCII characters for text input.
1473 // - with glfw you can get those from the callback set in glfwSetCharCallback()
1474 // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1475 // FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1476 void ImGuiIO::AddInputCharacter(unsigned int c)
1477 {
1478 IM_ASSERT(Ctx != NULL);
1479 ImGuiContext& g = *Ctx;
1480 if (c == 0 || !AppAcceptingEvents)
1481 return;
1482
1483 ImGuiInputEvent e;
1484 e.Type = ImGuiInputEventType_Text;
1485 e.Source = ImGuiInputSource_Keyboard;
1486 e.EventId = g.InputEventsNextEventId++;
1487 e.Text.Char = c;
1488 g.InputEventsQueue.push_back(e);
1489 }
1490
1491 // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1492 // we should save the high surrogate.
1493 void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1494 {
1495 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1496 return;
1497
1498 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1499 {
1500 if (InputQueueSurrogate != 0)
1501 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1502 InputQueueSurrogate = c;
1503 return;
1504 }
1505
1506 ImWchar cp = c;
1507 if (InputQueueSurrogate != 0)
1508 {
1509 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1510 {
1511 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1512 }
1513 else
1514 {
1515 #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1516 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1517 #else
1518 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1519 #endif
1520 }
1521
1522 InputQueueSurrogate = 0;
1523 }
1524 AddInputCharacter((unsigned)cp);
1525 }
1526
1527 void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1528 {
1529 if (!AppAcceptingEvents)
1530 return;
1531 while (*utf8_chars != 0)
1532 {
1533 unsigned int c = 0;
1534 utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1535 AddInputCharacter(c);
1536 }
1537 }
1538
1539 // Clear all incoming events.
1540 void ImGuiIO::ClearEventsQueue()
1541 {
1542 IM_ASSERT(Ctx != NULL);
1543 ImGuiContext& g = *Ctx;
1544 g.InputEventsQueue.clear();
1545 }
1546
1547 // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1548 void ImGuiIO::ClearInputKeys()
1549 {
1550 ImGuiContext& g = *Ctx;
1551 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
1552 {
1553 if (ImGui::IsMouseKey((ImGuiKey)key))
1554 continue;
1555 ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
1556 key_data->Down = false;
1557 key_data->DownDuration = -1.0f;
1558 key_data->DownDurationPrev = -1.0f;
1559 }
1560 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1561 KeyMods = ImGuiMod_None;
1562 InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1563 }
1564
1565 void ImGuiIO::ClearInputMouse()
1566 {
1567 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1568 {
1569 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
1570 key_data->Down = false;
1571 key_data->DownDuration = -1.0f;
1572 key_data->DownDurationPrev = -1.0f;
1573 }
1574 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1575 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1576 {
1577 MouseDown[n] = false;
1578 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1579 }
1580 MouseWheel = MouseWheelH = 0.0f;
1581 }
1582
1583 // Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1584 // Current frame character buffer is now also cleared by ClearInputKeys().
1585 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1586 void ImGuiIO::ClearInputCharacters()
1587 {
1588 InputQueueCharacters.resize(0);
1589 }
1590 #endif
1591
1592 static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1593 {
1594 ImGuiContext& g = *ctx;
1595 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1596 {
1597 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1598 if (e->Type != type)
1599 continue;
1600 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1601 continue;
1602 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1603 continue;
1604 return e;
1605 }
1606 return NULL;
1607 }
1608
1609 // Queue a new key down/up event.
1610 // - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1611 // - bool down: Is the key down? use false to signify a key release.
1612 // - float analog_value: 0.0f..1.0f
1613 // IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1614 // WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1615 void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1616 {
1617 //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1618 IM_ASSERT(Ctx != NULL);
1619 if (key == ImGuiKey_None || !AppAcceptingEvents)
1620 return;
1621 ImGuiContext& g = *Ctx;
1622 IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1623 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1624
1625 // MacOS: swap Cmd(Super) and Ctrl
1626 if (g.IO.ConfigMacOSXBehaviors)
1627 {
1628 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1629 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1630 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1631 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1632 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1633 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1634 }
1635
1636 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1637 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1638 const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1639 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1640 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1641 if (latest_key_down == down && latest_key_analog == analog_value)
1642 return;
1643
1644 // Add event
1645 ImGuiInputEvent e;
1646 e.Type = ImGuiInputEventType_Key;
1647 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1648 e.EventId = g.InputEventsNextEventId++;
1649 e.Key.Key = key;
1650 e.Key.Down = down;
1651 e.Key.AnalogValue = analog_value;
1652 g.InputEventsQueue.push_back(e);
1653 }
1654
1655 void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1656 {
1657 if (!AppAcceptingEvents)
1658 return;
1659 AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1660 }
1661
1662 // [Optional] Call after AddKeyEvent().
1663 // Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1664 // If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1665 void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1666 {
1667 if (key == ImGuiKey_None)
1668 return;
1669 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1670 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1671 IM_UNUSED(key); // Yet unused
1672 IM_UNUSED(native_keycode); // Yet unused
1673 IM_UNUSED(native_scancode); // Yet unused
1674 IM_UNUSED(native_legacy_index); // Yet unused
1675 }
1676
1677 // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1678 void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1679 {
1680 AppAcceptingEvents = accepting_events;
1681 }
1682
1683 // Queue a mouse move event
1684 void ImGuiIO::AddMousePosEvent(float x, float y)
1685 {
1686 IM_ASSERT(Ctx != NULL);
1687 ImGuiContext& g = *Ctx;
1688 if (!AppAcceptingEvents)
1689 return;
1690
1691 // Apply same flooring as UpdateMouseInputs()
1692 ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1693
1694 // Filter duplicate
1695 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1696 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1697 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1698 return;
1699
1700 ImGuiInputEvent e;
1701 e.Type = ImGuiInputEventType_MousePos;
1702 e.Source = ImGuiInputSource_Mouse;
1703 e.EventId = g.InputEventsNextEventId++;
1704 e.MousePos.PosX = pos.x;
1705 e.MousePos.PosY = pos.y;
1706 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1707 g.InputEventsQueue.push_back(e);
1708 }
1709
1710 void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1711 {
1712 IM_ASSERT(Ctx != NULL);
1713 ImGuiContext& g = *Ctx;
1714 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1715 if (!AppAcceptingEvents)
1716 return;
1717
1718 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1719 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1720 {
1721 // Order of both statements matterns: this event will still release mouse button 1
1722 mouse_button = 1;
1723 if (!down)
1724 MouseCtrlLeftAsRightClick = false;
1725 }
1726
1727 // Filter duplicate
1728 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1729 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1730 if (latest_button_down == down)
1731 return;
1732
1733 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1734 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1735 // - At this point we want from !down to down, so this is handling the initial press.
1736 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1737 {
1738 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1739 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1740 {
1741 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1742 MouseCtrlLeftAsRightClick = true;
1743 AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1744 return;
1745 }
1746 }
1747
1748 ImGuiInputEvent e;
1749 e.Type = ImGuiInputEventType_MouseButton;
1750 e.Source = ImGuiInputSource_Mouse;
1751 e.EventId = g.InputEventsNextEventId++;
1752 e.MouseButton.Button = mouse_button;
1753 e.MouseButton.Down = down;
1754 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1755 g.InputEventsQueue.push_back(e);
1756 }
1757
1758 // Queue a mouse wheel event (some mouse/API may only have a Y component)
1759 void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1760 {
1761 IM_ASSERT(Ctx != NULL);
1762 ImGuiContext& g = *Ctx;
1763
1764 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1765 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1766 return;
1767
1768 ImGuiInputEvent e;
1769 e.Type = ImGuiInputEventType_MouseWheel;
1770 e.Source = ImGuiInputSource_Mouse;
1771 e.EventId = g.InputEventsNextEventId++;
1772 e.MouseWheel.WheelX = wheel_x;
1773 e.MouseWheel.WheelY = wheel_y;
1774 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1775 g.InputEventsQueue.push_back(e);
1776 }
1777
1778 // This is not a real event, the data is latched in order to be stored in actual Mouse events.
1779 // This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1780 void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1781 {
1782 IM_ASSERT(Ctx != NULL);
1783 ImGuiContext& g = *Ctx;
1784 g.InputEventsNextMouseSource = source;
1785 }
1786
1787 void ImGuiIO::AddFocusEvent(bool focused)
1788 {
1789 IM_ASSERT(Ctx != NULL);
1790 ImGuiContext& g = *Ctx;
1791
1792 // Filter duplicate
1793 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1794 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1795 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1796 return;
1797
1798 ImGuiInputEvent e;
1799 e.Type = ImGuiInputEventType_Focus;
1800 e.EventId = g.InputEventsNextEventId++;
1801 e.AppFocused.Focused = focused;
1802 g.InputEventsQueue.push_back(e);
1803 }
1804
1805 ImGuiPlatformIO::ImGuiPlatformIO()
1806 {
1807 // Most fields are initialized with zero
1808 memset(this, 0, sizeof(*this));
1809 Platform_LocaleDecimalPoint = '.';
1810 }
1811
1812 //-----------------------------------------------------------------------------
1813 // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1814 //-----------------------------------------------------------------------------
1815
1816 ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1817 {
1818 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1819 ImVec2 p_last = p1;
1820 ImVec2 p_closest;
1821 float p_closest_dist2 = FLT_MAX;
1822 float t_step = 1.0f / (float)num_segments;
1823 for (int i_step = 1; i_step <= num_segments; i_step++)
1824 {
1825 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1826 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1827 float dist2 = ImLengthSqr(p - p_line);
1828 if (dist2 < p_closest_dist2)
1829 {
1830 p_closest = p_line;
1831 p_closest_dist2 = dist2;
1832 }
1833 p_last = p_current;
1834 }
1835 return p_closest;
1836 }
1837
1838 // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1839 static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1840 {
1841 float dx = x4 - x1;
1842 float dy = y4 - y1;
1843 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1844 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1845 d2 = (d2 >= 0) ? d2 : -d2;
1846 d3 = (d3 >= 0) ? d3 : -d3;
1847 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1848 {
1849 ImVec2 p_current(x4, y4);
1850 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1851 float dist2 = ImLengthSqr(p - p_line);
1852 if (dist2 < p_closest_dist2)
1853 {
1854 p_closest = p_line;
1855 p_closest_dist2 = dist2;
1856 }
1857 p_last = p_current;
1858 }
1859 else if (level < 10)
1860 {
1861 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
1862 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
1863 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
1864 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
1865 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
1866 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1867 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1868 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1869 }
1870 }
1871
1872 // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1873 // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1874 ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1875 {
1876 IM_ASSERT(tess_tol > 0.0f);
1877 ImVec2 p_last = p1;
1878 ImVec2 p_closest;
1879 float p_closest_dist2 = FLT_MAX;
1880 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1881 return p_closest;
1882 }
1883
1884 ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1885 {
1886 ImVec2 ap = p - a;
1887 ImVec2 ab_dir = b - a;
1888 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1889 if (dot < 0.0f)
1890 return a;
1891 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1892 if (dot > ab_len_sqr)
1893 return b;
1894 return a + ab_dir * dot / ab_len_sqr;
1895 }
1896
1897 bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1898 {
1899 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1900 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1901 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1902 return ((b1 == b2) && (b2 == b3));
1903 }
1904
1905 void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1906 {
1907 ImVec2 v0 = b - a;
1908 ImVec2 v1 = c - a;
1909 ImVec2 v2 = p - a;
1910 const float denom = v0.x * v1.y - v1.x * v0.y;
1911 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1912 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1913 out_u = 1.0f - out_v - out_w;
1914 }
1915
1916 ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1917 {
1918 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1919 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1920 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1921 float dist2_ab = ImLengthSqr(p - proj_ab);
1922 float dist2_bc = ImLengthSqr(p - proj_bc);
1923 float dist2_ca = ImLengthSqr(p - proj_ca);
1924 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1925 if (m == dist2_ab)
1926 return proj_ab;
1927 if (m == dist2_bc)
1928 return proj_bc;
1929 return proj_ca;
1930 }
1931
1932 //-----------------------------------------------------------------------------
1933 // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1934 //-----------------------------------------------------------------------------
1935
1936 // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1937 int ImStricmp(const char* str1, const char* str2)
1938 {
1939 int d;
1940 while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1941 return d;
1942 }
1943
1944 int ImStrnicmp(const char* str1, const char* str2, size_t count)
1945 {
1946 int d = 0;
1947 while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1948 return d;
1949 }
1950
1951 void ImStrncpy(char* dst, const char* src, size_t count)
1952 {
1953 if (count < 1)
1954 return;
1955 if (count > 1)
1956 strncpy(dst, src, count - 1);
1957 dst[count - 1] = 0;
1958 }
1959
1960 char* ImStrdup(const char* str)
1961 {
1962 size_t len = strlen(str);
1963 void* buf = IM_ALLOC(len + 1);
1964 return (char*)memcpy(buf, (const void*)str, len + 1);
1965 }
1966
1967 char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1968 {
1969 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1970 size_t src_size = strlen(src) + 1;
1971 if (dst_buf_size < src_size)
1972 {
1973 IM_FREE(dst);
1974 dst = (char*)IM_ALLOC(src_size);
1975 if (p_dst_size)
1976 *p_dst_size = src_size;
1977 }
1978 return (char*)memcpy(dst, (const void*)src, src_size);
1979 }
1980
1981 const char* ImStrchrRange(const char* str, const char* str_end, char c)
1982 {
1983 const char* p = (const char*)memchr(str, (int)c, str_end - str);
1984 return p;
1985 }
1986
1987 int ImStrlenW(const ImWchar* str)
1988 {
1989 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
1990 int n = 0;
1991 while (*str++) n++;
1992 return n;
1993 }
1994
1995 // Find end-of-line. Return pointer will point to either first \n, either str_end.
1996 const char* ImStreolRange(const char* str, const char* str_end)
1997 {
1998 const char* p = (const char*)memchr(str, '\n', str_end - str);
1999 return p ? p : str_end;
2000 }
2001
2002 const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
2003 {
2004 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2005 buf_mid_line--;
2006 return buf_mid_line;
2007 }
2008
2009 const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2010 {
2011 if (!needle_end)
2012 needle_end = needle + strlen(needle);
2013
2014 const char un0 = (char)ImToUpper(*needle);
2015 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2016 {
2017 if (ImToUpper(*haystack) == un0)
2018 {
2019 const char* b = needle + 1;
2020 for (const char* a = haystack + 1; b < needle_end; a++, b++)
2021 if (ImToUpper(*a) != ImToUpper(*b))
2022 break;
2023 if (b == needle_end)
2024 return haystack;
2025 }
2026 haystack++;
2027 }
2028 return NULL;
2029 }
2030
2031 // Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2032 void ImStrTrimBlanks(char* buf)
2033 {
2034 char* p = buf;
2035 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
2036 p++;
2037 char* p_start = p;
2038 while (*p != 0) // Find end of string
2039 p++;
2040 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
2041 p--;
2042 if (p_start != buf) // Copy memory if we had leading blanks
2043 memmove(buf, p_start, p - p_start);
2044 buf[p - p_start] = 0; // Zero terminate
2045 }
2046
2047 const char* ImStrSkipBlank(const char* str)
2048 {
2049 while (str[0] == ' ' || str[0] == '\t')
2050 str++;
2051 return str;
2052 }
2053
2054 // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2055 // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2056 // B) When buf==NULL vsnprintf() will return the output size.
2057 #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2058
2059 // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2060 // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2061 // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2062 // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2063 #ifdef IMGUI_USE_STB_SPRINTF
2064 #ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2065 #define STB_SPRINTF_IMPLEMENTATION
2066 #endif
2067 #ifdef IMGUI_STB_SPRINTF_FILENAME
2068 #include IMGUI_STB_SPRINTF_FILENAME
2069 #else
2070 #include "stb_sprintf.h"
2071 #endif
2072 #endif // #ifdef IMGUI_USE_STB_SPRINTF
2073
2074 #if defined(_MSC_VER) && !defined(vsnprintf)
2075 #define vsnprintf _vsnprintf
2076 #endif
2077
2078 int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2079 {
2080 va_list args;
2081 va_start(args, fmt);
2082 #ifdef IMGUI_USE_STB_SPRINTF
2083 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2084 #else
2085 int w = vsnprintf(buf, buf_size, fmt, args);
2086 #endif
2087 va_end(args);
2088 if (buf == NULL)
2089 return w;
2090 if (w == -1 || w >= (int)buf_size)
2091 w = (int)buf_size - 1;
2092 buf[w] = 0;
2093 return w;
2094 }
2095
2096 int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2097 {
2098 #ifdef IMGUI_USE_STB_SPRINTF
2099 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2100 #else
2101 int w = vsnprintf(buf, buf_size, fmt, args);
2102 #endif
2103 if (buf == NULL)
2104 return w;
2105 if (w == -1 || w >= (int)buf_size)
2106 w = (int)buf_size - 1;
2107 buf[w] = 0;
2108 return w;
2109 }
2110 #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2111
2112 void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2113 {
2114 va_list args;
2115 va_start(args, fmt);
2116 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2117 va_end(args);
2118 }
2119
2120 // FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2121 // by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2122 // ImGuiTempBufferToken token;
2123 // ImFormatStringToTempBuffer(token, ...);
2124 void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2125 {
2126 ImGuiContext& g = *GImGui;
2127 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2128 {
2129 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2130 if (buf == NULL)
2131 buf = "(null)";
2132 *out_buf = buf;
2133 if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2134 }
2135 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2136 {
2137 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2138 const char* buf = va_arg(args, const char*);
2139 if (buf == NULL)
2140 {
2141 buf = "(null)";
2142 buf_len = ImMin(buf_len, 6);
2143 }
2144 *out_buf = buf;
2145 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2146 }
2147 else
2148 {
2149 int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2150 *out_buf = g.TempBuffer.Data;
2151 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2152 }
2153 }
2154
2155 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2156 // CRC32 needs a 1KB lookup table (not cache friendly)
2157 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2158 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2159 static const ImU32 GCrc32LookupTable[256] =
2160 {
2161 #ifdef IMGUI_USE_LEGACY_CRC32_ADLER
2162 // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
2163 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2164 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2165 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2166 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2167 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2168 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2169 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2170 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2171 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2172 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2173 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2174 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2175 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2176 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2177 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2178 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2179 #else
2180 // CRC32c table compatible with SSE 4.2 instructions
2181 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
2182 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
2183 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
2184 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
2185 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
2186 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
2187 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
2188 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
2189 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
2190 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
2191 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
2192 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
2193 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
2194 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
2195 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
2196 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
2197 #endif
2198 };
2199 #endif
2200
2201 // Known size hash
2202 // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2203 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2204 ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2205 {
2206 ImU32 crc = ~seed;
2207 const unsigned char* data = (const unsigned char*)data_p;
2208 const unsigned char *data_end = (const unsigned char*)data_p + data_size;
2209 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2210 const ImU32* crc32_lut = GCrc32LookupTable;
2211 while (data < data_end)
2212 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2213 return ~crc;
2214 #else
2215 while (data + 4 <= data_end)
2216 {
2217 crc = _mm_crc32_u32(crc, *(ImU32*)data);
2218 data += 4;
2219 }
2220 while (data < data_end)
2221 crc = _mm_crc32_u8(crc, *data++);
2222 return ~crc;
2223 #endif
2224 }
2225
2226 // Zero-terminated string hash, with support for ### to reset back to seed value
2227 // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2228 // Because this syntax is rarely used we are optimizing for the common case.
2229 // - If we reach ### in the string we discard the hash so far and reset to the seed.
2230 // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2231 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2232 ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2233 {
2234 seed = ~seed;
2235 ImU32 crc = seed;
2236 const unsigned char* data = (const unsigned char*)data_p;
2237 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2238 const ImU32* crc32_lut = GCrc32LookupTable;
2239 #endif
2240 if (data_size != 0)
2241 {
2242 while (data_size-- != 0)
2243 {
2244 unsigned char c = *data++;
2245 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2246 crc = seed;
2247 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2248 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2249 #else
2250 crc = _mm_crc32_u8(crc, c);
2251 #endif
2252 }
2253 }
2254 else
2255 {
2256 while (unsigned char c = *data++)
2257 {
2258 if (c == '#' && data[0] == '#' && data[1] == '#')
2259 crc = seed;
2260 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2261 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2262 #else
2263 crc = _mm_crc32_u8(crc, c);
2264 #endif
2265 }
2266 }
2267 return ~crc;
2268 }
2269
2270 //-----------------------------------------------------------------------------
2271 // [SECTION] MISC HELPERS/UTILITIES (File functions)
2272 //-----------------------------------------------------------------------------
2273
2274 // Default file functions
2275 #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2276
2277 ImFileHandle ImFileOpen(const char* filename, const char* mode)
2278 {
2279 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2280 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2281 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2282 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2283 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2284
2285 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2286 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2287 wchar_t local_temp_stack[FILENAME_MAX];
2288 ImVector<wchar_t> local_temp_heap;
2289 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2290 local_temp_heap.resize(filename_wsize + mode_wsize);
2291 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2292 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2293 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2294 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2295 return ::_wfopen(filename_wbuf, mode_wbuf);
2296 #else
2297 return fopen(filename, mode);
2298 #endif
2299 }
2300
2301 // We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2302 bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
2303 ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2304 ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
2305 ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
2306 #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2307
2308 // Helper: Load file content into memory
2309 // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2310 // This can't really be used with "rt" because fseek size won't match read size.
2311 void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2312 {
2313 IM_ASSERT(filename && mode);
2314 if (out_file_size)
2315 *out_file_size = 0;
2316
2317 ImFileHandle f;
2318 if ((f = ImFileOpen(filename, mode)) == NULL)
2319 return NULL;
2320
2321 size_t file_size = (size_t)ImFileGetSize(f);
2322 if (file_size == (size_t)-1)
2323 {
2324 ImFileClose(f);
2325 return NULL;
2326 }
2327
2328 void* file_data = IM_ALLOC(file_size + padding_bytes);
2329 if (file_data == NULL)
2330 {
2331 ImFileClose(f);
2332 return NULL;
2333 }
2334 if (ImFileRead(file_data, 1, file_size, f) != file_size)
2335 {
2336 ImFileClose(f);
2337 IM_FREE(file_data);
2338 return NULL;
2339 }
2340 if (padding_bytes > 0)
2341 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2342
2343 ImFileClose(f);
2344 if (out_file_size)
2345 *out_file_size = file_size;
2346
2347 return file_data;
2348 }
2349
2350 //-----------------------------------------------------------------------------
2351 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2352 //-----------------------------------------------------------------------------
2353
2354 IM_MSVC_RUNTIME_CHECKS_OFF
2355
2356 // Convert UTF-8 to 32-bit character, process single character input.
2357 // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2358 // We handle UTF-8 decoding error by skipping forward.
2359 int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2360 {
2361 static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2362 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2363 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2364 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2365 static const int shifte[] = { 0, 6, 4, 2, 0 };
2366 int len = lengths[*(const unsigned char*)in_text >> 3];
2367 int wanted = len + (len ? 0 : 1);
2368
2369 if (in_text_end == NULL)
2370 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2371
2372 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2373 // so it is fast even with excessive branching.
2374 unsigned char s[4];
2375 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2376 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2377 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2378 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2379
2380 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2381 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2382 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2383 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2384 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2385 *out_char >>= shiftc[len];
2386
2387 // Accumulate the various error conditions.
2388 int e = 0;
2389 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2390 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2391 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
2392 e |= (s[1] & 0xc0) >> 2;
2393 e |= (s[2] & 0xc0) >> 4;
2394 e |= (s[3] ) >> 6;
2395 e ^= 0x2a; // top two bits of each tail byte correct?
2396 e >>= shifte[len];
2397
2398 if (e)
2399 {
2400 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2401 // One byte is consumed in case of invalid first byte of in_text.
2402 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2403 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2404 wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2405 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2406 }
2407
2408 return wanted;
2409 }
2410
2411 int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2412 {
2413 ImWchar* buf_out = buf;
2414 ImWchar* buf_end = buf + buf_size;
2415 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2416 {
2417 unsigned int c;
2418 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2419 *buf_out++ = (ImWchar)c;
2420 }
2421 *buf_out = 0;
2422 if (in_text_remaining)
2423 *in_text_remaining = in_text;
2424 return (int)(buf_out - buf);
2425 }
2426
2427 int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2428 {
2429 int char_count = 0;
2430 while ((!in_text_end || in_text < in_text_end) && *in_text)
2431 {
2432 unsigned int c;
2433 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2434 char_count++;
2435 }
2436 return char_count;
2437 }
2438
2439 // Based on stb_to_utf8() from github.com/nothings/stb/
2440 static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2441 {
2442 if (c < 0x80)
2443 {
2444 buf[0] = (char)c;
2445 return 1;
2446 }
2447 if (c < 0x800)
2448 {
2449 if (buf_size < 2) return 0;
2450 buf[0] = (char)(0xc0 + (c >> 6));
2451 buf[1] = (char)(0x80 + (c & 0x3f));
2452 return 2;
2453 }
2454 if (c < 0x10000)
2455 {
2456 if (buf_size < 3) return 0;
2457 buf[0] = (char)(0xe0 + (c >> 12));
2458 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2459 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2460 return 3;
2461 }
2462 if (c <= 0x10FFFF)
2463 {
2464 if (buf_size < 4) return 0;
2465 buf[0] = (char)(0xf0 + (c >> 18));
2466 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2467 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2468 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2469 return 4;
2470 }
2471 // Invalid code point, the max unicode is 0x10FFFF
2472 return 0;
2473 }
2474
2475 const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2476 {
2477 int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2478 out_buf[count] = 0;
2479 return out_buf;
2480 }
2481
2482 // Not optimal but we very rarely use this function.
2483 int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2484 {
2485 unsigned int unused = 0;
2486 return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2487 }
2488
2489 static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2490 {
2491 if (c < 0x80) return 1;
2492 if (c < 0x800) return 2;
2493 if (c < 0x10000) return 3;
2494 if (c <= 0x10FFFF) return 4;
2495 return 3;
2496 }
2497
2498 int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2499 {
2500 char* buf_p = out_buf;
2501 const char* buf_end = out_buf + out_buf_size;
2502 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2503 {
2504 unsigned int c = (unsigned int)(*in_text++);
2505 if (c < 0x80)
2506 *buf_p++ = (char)c;
2507 else
2508 buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2509 }
2510 *buf_p = 0;
2511 return (int)(buf_p - out_buf);
2512 }
2513
2514 int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2515 {
2516 int bytes_count = 0;
2517 while ((!in_text_end || in_text < in_text_end) && *in_text)
2518 {
2519 unsigned int c = (unsigned int)(*in_text++);
2520 if (c < 0x80)
2521 bytes_count++;
2522 else
2523 bytes_count += ImTextCountUtf8BytesFromChar(c);
2524 }
2525 return bytes_count;
2526 }
2527
2528 const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2529 {
2530 while (in_text_curr > in_text_start)
2531 {
2532 in_text_curr--;
2533 if ((*in_text_curr & 0xC0) != 0x80)
2534 return in_text_curr;
2535 }
2536 return in_text_start;
2537 }
2538
2539 int ImTextCountLines(const char* in_text, const char* in_text_end)
2540 {
2541 if (in_text_end == NULL)
2542 in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2543 int count = 0;
2544 while (in_text < in_text_end)
2545 {
2546 const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
2547 in_text = line_end ? line_end + 1 : in_text_end;
2548 count++;
2549 }
2550 return count;
2551 }
2552
2553 IM_MSVC_RUNTIME_CHECKS_RESTORE
2554
2555 //-----------------------------------------------------------------------------
2556 // [SECTION] MISC HELPERS/UTILITIES (Color functions)
2557 // Note: The Convert functions are early design which are not consistent with other API.
2558 //-----------------------------------------------------------------------------
2559
2560 IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2561 {
2562 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2563 int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2564 int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2565 int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2566 return IM_COL32(r, g, b, 0xFF);
2567 }
2568
2569 ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2570 {
2571 float s = 1.0f / 255.0f;
2572 return ImVec4(
2573 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2574 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2575 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2576 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2577 }
2578
2579 ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2580 {
2581 ImU32 out;
2582 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2583 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2584 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2585 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2586 return out;
2587 }
2588
2589 // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2590 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2591 void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2592 {
2593 float K = 0.f;
2594 if (g < b)
2595 {
2596 ImSwap(g, b);
2597 K = -1.f;
2598 }
2599 if (r < g)
2600 {
2601 ImSwap(r, g);
2602 K = -2.f / 6.f - K;
2603 }
2604
2605 const float chroma = r - (g < b ? g : b);
2606 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2607 out_s = chroma / (r + 1e-20f);
2608 out_v = r;
2609 }
2610
2611 // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2612 // also http://en.wikipedia.org/wiki/HSL_and_HSV
2613 void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2614 {
2615 if (s == 0.0f)
2616 {
2617 // gray
2618 out_r = out_g = out_b = v;
2619 return;
2620 }
2621
2622 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2623 int i = (int)h;
2624 float f = h - (float)i;
2625 float p = v * (1.0f - s);
2626 float q = v * (1.0f - s * f);
2627 float t = v * (1.0f - s * (1.0f - f));
2628
2629 switch (i)
2630 {
2631 case 0: out_r = v; out_g = t; out_b = p; break;
2632 case 1: out_r = q; out_g = v; out_b = p; break;
2633 case 2: out_r = p; out_g = v; out_b = t; break;
2634 case 3: out_r = p; out_g = q; out_b = v; break;
2635 case 4: out_r = t; out_g = p; out_b = v; break;
2636 case 5: default: out_r = v; out_g = p; out_b = q; break;
2637 }
2638 }
2639
2640 //-----------------------------------------------------------------------------
2641 // [SECTION] ImGuiStorage
2642 // Helper: Key->value storage
2643 //-----------------------------------------------------------------------------
2644
2645 // std::lower_bound but without the bullshit
2646 ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2647 {
2648 ImGuiStoragePair* in_p = in_begin;
2649 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2650 {
2651 size_t count2 = count >> 1;
2652 ImGuiStoragePair* mid = in_p + count2;
2653 if (mid->key < key)
2654 {
2655 in_p = ++mid;
2656 count -= count2 + 1;
2657 }
2658 else
2659 {
2660 count = count2;
2661 }
2662 }
2663 return in_p;
2664 }
2665
2666 IM_MSVC_RUNTIME_CHECKS_OFF
2667 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2668 {
2669 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2670 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2671 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2672 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2673 }
2674
2675 // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2676 void ImGuiStorage::BuildSortByKey()
2677 {
2678 ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2679 }
2680
2681 int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2682 {
2683 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2684 if (it == Data.Data + Data.Size || it->key != key)
2685 return default_val;
2686 return it->val_i;
2687 }
2688
2689 bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2690 {
2691 return GetInt(key, default_val ? 1 : 0) != 0;
2692 }
2693
2694 float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2695 {
2696 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2697 if (it == Data.Data + Data.Size || it->key != key)
2698 return default_val;
2699 return it->val_f;
2700 }
2701
2702 void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2703 {
2704 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2705 if (it == Data.Data + Data.Size || it->key != key)
2706 return NULL;
2707 return it->val_p;
2708 }
2709
2710 // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2711 int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2712 {
2713 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2714 if (it == Data.Data + Data.Size || it->key != key)
2715 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2716 return &it->val_i;
2717 }
2718
2719 bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2720 {
2721 return (bool*)GetIntRef(key, default_val ? 1 : 0);
2722 }
2723
2724 float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2725 {
2726 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2727 if (it == Data.Data + Data.Size || it->key != key)
2728 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2729 return &it->val_f;
2730 }
2731
2732 void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2733 {
2734 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2735 if (it == Data.Data + Data.Size || it->key != key)
2736 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2737 return &it->val_p;
2738 }
2739
2740 // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2741 void ImGuiStorage::SetInt(ImGuiID key, int val)
2742 {
2743 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2744 if (it == Data.Data + Data.Size || it->key != key)
2745 Data.insert(it, ImGuiStoragePair(key, val));
2746 else
2747 it->val_i = val;
2748 }
2749
2750 void ImGuiStorage::SetBool(ImGuiID key, bool val)
2751 {
2752 SetInt(key, val ? 1 : 0);
2753 }
2754
2755 void ImGuiStorage::SetFloat(ImGuiID key, float val)
2756 {
2757 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2758 if (it == Data.Data + Data.Size || it->key != key)
2759 Data.insert(it, ImGuiStoragePair(key, val));
2760 else
2761 it->val_f = val;
2762 }
2763
2764 void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2765 {
2766 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2767 if (it == Data.Data + Data.Size || it->key != key)
2768 Data.insert(it, ImGuiStoragePair(key, val));
2769 else
2770 it->val_p = val;
2771 }
2772
2773 void ImGuiStorage::SetAllInt(int v)
2774 {
2775 for (int i = 0; i < Data.Size; i++)
2776 Data[i].val_i = v;
2777 }
2778 IM_MSVC_RUNTIME_CHECKS_RESTORE
2779
2780 //-----------------------------------------------------------------------------
2781 // [SECTION] ImGuiTextFilter
2782 //-----------------------------------------------------------------------------
2783
2784 // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2785 ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2786 {
2787 InputBuf[0] = 0;
2788 CountGrep = 0;
2789 if (default_filter)
2790 {
2791 ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2792 Build();
2793 }
2794 }
2795
2796 bool ImGuiTextFilter::Draw(const char* label, float width)
2797 {
2798 if (width != 0.0f)
2799 ImGui::SetNextItemWidth(width);
2800 bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2801 if (value_changed)
2802 Build();
2803 return value_changed;
2804 }
2805
2806 void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2807 {
2808 out->resize(0);
2809 const char* wb = b;
2810 const char* we = wb;
2811 while (we < e)
2812 {
2813 if (*we == separator)
2814 {
2815 out->push_back(ImGuiTextRange(wb, we));
2816 wb = we + 1;
2817 }
2818 we++;
2819 }
2820 if (wb != we)
2821 out->push_back(ImGuiTextRange(wb, we));
2822 }
2823
2824 void ImGuiTextFilter::Build()
2825 {
2826 Filters.resize(0);
2827 ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2828 input_range.split(',', &Filters);
2829
2830 CountGrep = 0;
2831 for (ImGuiTextRange& f : Filters)
2832 {
2833 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2834 f.b++;
2835 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2836 f.e--;
2837 if (f.empty())
2838 continue;
2839 if (f.b[0] != '-')
2840 CountGrep += 1;
2841 }
2842 }
2843
2844 bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2845 {
2846 if (Filters.Size == 0)
2847 return true;
2848
2849 if (text == NULL)
2850 text = text_end = "";
2851
2852 for (const ImGuiTextRange& f : Filters)
2853 {
2854 if (f.b == f.e)
2855 continue;
2856 if (f.b[0] == '-')
2857 {
2858 // Subtract
2859 if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2860 return false;
2861 }
2862 else
2863 {
2864 // Grep
2865 if (ImStristr(text, text_end, f.b, f.e) != NULL)
2866 return true;
2867 }
2868 }
2869
2870 // Implicit * grep
2871 if (CountGrep == 0)
2872 return true;
2873
2874 return false;
2875 }
2876
2877 //-----------------------------------------------------------------------------
2878 // [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2879 //-----------------------------------------------------------------------------
2880
2881 // On some platform vsnprintf() takes va_list by reference and modifies it.
2882 // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2883 #ifndef va_copy
2884 #if defined(__GNUC__) || defined(__clang__)
2885 #define va_copy(dest, src) __builtin_va_copy(dest, src)
2886 #else
2887 #define va_copy(dest, src) (dest = src)
2888 #endif
2889 #endif
2890
2891 char ImGuiTextBuffer::EmptyString[1] = { 0 };
2892
2893 void ImGuiTextBuffer::append(const char* str, const char* str_end)
2894 {
2895 int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2896
2897 // Add zero-terminator the first time
2898 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2899 const int needed_sz = write_off + len;
2900 if (write_off + len >= Buf.Capacity)
2901 {
2902 int new_capacity = Buf.Capacity * 2;
2903 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2904 }
2905
2906 Buf.resize(needed_sz);
2907 memcpy(&Buf[write_off - 1], str, (size_t)len);
2908 Buf[write_off - 1 + len] = 0;
2909 }
2910
2911 void ImGuiTextBuffer::appendf(const char* fmt, ...)
2912 {
2913 va_list args;
2914 va_start(args, fmt);
2915 appendfv(fmt, args);
2916 va_end(args);
2917 }
2918
2919 // Helper: Text buffer for logging/accumulating text
2920 void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2921 {
2922 va_list args_copy;
2923 va_copy(args_copy, args);
2924
2925 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2926 if (len <= 0)
2927 {
2928 va_end(args_copy);
2929 return;
2930 }
2931
2932 // Add zero-terminator the first time
2933 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2934 const int needed_sz = write_off + len;
2935 if (write_off + len >= Buf.Capacity)
2936 {
2937 int new_capacity = Buf.Capacity * 2;
2938 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2939 }
2940
2941 Buf.resize(needed_sz);
2942 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2943 va_end(args_copy);
2944 }
2945
2946 void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2947 {
2948 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2949 if (old_size == new_size)
2950 return;
2951 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2952 LineOffsets.push_back(EndOffset);
2953 const char* base_end = base + new_size;
2954 for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2955 if (++p < base_end) // Don't push a trailing offset on last \n
2956 LineOffsets.push_back((int)(intptr_t)(p - base));
2957 EndOffset = ImMax(EndOffset, new_size);
2958 }
2959
2960 //-----------------------------------------------------------------------------
2961 // [SECTION] ImGuiListClipper
2962 //-----------------------------------------------------------------------------
2963
2964 // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2965 // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2966 static bool GetSkipItemForListClipping()
2967 {
2968 ImGuiContext& g = *GImGui;
2969 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2970 }
2971
2972 static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2973 {
2974 if (ranges.Size - offset <= 1)
2975 return;
2976
2977 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2978 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2979 for (int i = offset; i < sort_end + offset; ++i)
2980 if (ranges[i].Min > ranges[i + 1].Min)
2981 ImSwap(ranges[i], ranges[i + 1]);
2982
2983 // Now fuse ranges together as much as possible.
2984 for (int i = 1 + offset; i < ranges.Size; i++)
2985 {
2986 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2987 if (ranges[i - 1].Max < ranges[i].Min)
2988 continue;
2989 ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2990 ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2991 ranges.erase(ranges.Data + i);
2992 i--;
2993 }
2994 }
2995
2996 static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2997 {
2998 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2999 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
3000 // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
3001 ImGuiContext& g = *GImGui;
3002 ImGuiWindow* window = g.CurrentWindow;
3003 float off_y = pos_y - window->DC.CursorPos.y;
3004 window->DC.CursorPos.y = pos_y;
3005 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
3006 window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
3007 window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
3008 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
3009 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
3010 if (ImGuiTable* table = g.CurrentTable)
3011 {
3012 if (table->IsInsideRow)
3013 ImGui::TableEndRow(table);
3014 table->RowPosY2 = window->DC.CursorPos.y;
3015 const int row_increase = (int)((off_y / line_height) + 0.5f);
3016 //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
3017 table->RowBgColorCounter += row_increase;
3018 }
3019 }
3020
3021 ImGuiListClipper::ImGuiListClipper()
3022 {
3023 memset(this, 0, sizeof(*this));
3024 }
3025
3026 ImGuiListClipper::~ImGuiListClipper()
3027 {
3028 End();
3029 }
3030
3031 void ImGuiListClipper::Begin(int items_count, float items_height)
3032 {
3033 if (Ctx == NULL)
3034 Ctx = ImGui::GetCurrentContext();
3035
3036 ImGuiContext& g = *Ctx;
3037 ImGuiWindow* window = g.CurrentWindow;
3038 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3039
3040 if (ImGuiTable* table = g.CurrentTable)
3041 if (table->IsInsideRow)
3042 ImGui::TableEndRow(table);
3043
3044 StartPosY = window->DC.CursorPos.y;
3045 ItemsHeight = items_height;
3046 ItemsCount = items_count;
3047 DisplayStart = -1;
3048 DisplayEnd = 0;
3049
3050 // Acquire temporary buffer
3051 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3052 g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3053 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3054 data->Reset(this);
3055 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3056 TempData = data;
3057 StartSeekOffsetY = data->LossynessOffset;
3058 }
3059
3060 void ImGuiListClipper::End()
3061 {
3062 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3063 {
3064 // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3065 ImGuiContext& g = *Ctx;
3066 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3067 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3068 SeekCursorForItem(ItemsCount);
3069
3070 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3071 IM_ASSERT(data->ListClipper == this);
3072 data->StepNo = data->Ranges.Size;
3073 if (--g.ClipperTempDataStacked > 0)
3074 {
3075 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3076 data->ListClipper->TempData = data;
3077 }
3078 TempData = NULL;
3079 }
3080 ItemsCount = -1;
3081 }
3082
3083 void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3084 {
3085 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3086 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3087 IM_ASSERT(item_begin <= item_end);
3088 if (item_begin < item_end)
3089 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3090 }
3091
3092 // This is already called while stepping.
3093 // The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand.
3094 void ImGuiListClipper::SeekCursorForItem(int item_n)
3095 {
3096 // - Perform the add and multiply with double to allow seeking through larger ranges.
3097 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3098 // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
3099 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3100 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight);
3101 }
3102
3103 static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3104 {
3105 ImGuiContext& g = *clipper->Ctx;
3106 ImGuiWindow* window = g.CurrentWindow;
3107 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3108 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3109
3110 ImGuiTable* table = g.CurrentTable;
3111 if (table && table->IsInsideRow)
3112 ImGui::TableEndRow(table);
3113
3114 // No items
3115 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3116 return false;
3117
3118 // While we are in frozen row state, keep displaying items one by one, unclipped
3119 // FIXME: Could be stored as a table-agnostic state.
3120 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3121 {
3122 clipper->DisplayStart = data->ItemsFrozen;
3123 clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3124 if (clipper->DisplayStart < clipper->DisplayEnd)
3125 data->ItemsFrozen++;
3126 return true;
3127 }
3128
3129 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3130 bool calc_clipping = false;
3131 if (data->StepNo == 0)
3132 {
3133 clipper->StartPosY = window->DC.CursorPos.y;
3134 if (clipper->ItemsHeight <= 0.0f)
3135 {
3136 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3137 data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3138 clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3139 clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3140 data->StepNo = 1;
3141 return true;
3142 }
3143 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3144 }
3145
3146 // Step 1: Let the clipper infer height from first range
3147 if (clipper->ItemsHeight <= 0.0f)
3148 {
3149 IM_ASSERT(data->StepNo == 1);
3150 if (table)
3151 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3152
3153 clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3154 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3155 if (affected_by_floating_point_precision)
3156 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3157 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3158 return false;
3159 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3160 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3161 }
3162
3163 // Step 0 or 1: Calculate the actual ranges of visible elements.
3164 const int already_submitted = clipper->DisplayEnd;
3165 if (calc_clipping)
3166 {
3167 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3168 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3169
3170 if (g.LogEnabled)
3171 {
3172 // If logging is active, do not perform any clipping
3173 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3174 }
3175 else
3176 {
3177 // Add range selected to be included for navigation
3178 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3179 if (is_nav_request)
3180 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3181 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3182 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3183
3184 // Add focused/active item
3185 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3186 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3187 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3188
3189 // Add visible range
3190 float min_y = window->ClipRect.Min.y;
3191 float max_y = window->ClipRect.Max.y;
3192
3193 // Add box selection range
3194 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3195 if (bs->IsActive && bs->Window == window)
3196 {
3197 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3198 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3199 // As a workaround we currently half ItemSpacing worth on each side.
3200 min_y -= g.Style.ItemSpacing.y;
3201 max_y += g.Style.ItemSpacing.y;
3202
3203 // Box-select on 2D area requires different clipping.
3204 if (bs->UnclipMode)
3205 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
3206 }
3207
3208 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3209 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3210 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
3211 }
3212
3213 // Convert position ranges to item index ranges
3214 // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3215 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3216 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3217 for (ImGuiListClipperRange& range : data->Ranges)
3218 if (range.PosToIndexConvert)
3219 {
3220 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3221 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3222 range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3223 range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3224 range.PosToIndexConvert = false;
3225 }
3226 ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3227 }
3228
3229 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3230 while (data->StepNo < data->Ranges.Size)
3231 {
3232 clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3233 clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3234 if (clipper->DisplayStart > already_submitted) //-V1051
3235 clipper->SeekCursorForItem(clipper->DisplayStart);
3236 data->StepNo++;
3237 if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3238 continue;
3239 return true;
3240 }
3241
3242 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3243 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3244 if (clipper->ItemsCount < INT_MAX)
3245 clipper->SeekCursorForItem(clipper->ItemsCount);
3246
3247 return false;
3248 }
3249
3250 bool ImGuiListClipper::Step()
3251 {
3252 ImGuiContext& g = *Ctx;
3253 bool need_items_height = (ItemsHeight <= 0.0f);
3254 bool ret = ImGuiListClipper_StepInternal(this);
3255 if (ret && (DisplayStart == DisplayEnd))
3256 ret = false;
3257 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3258 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3259 if (need_items_height && ItemsHeight > 0.0f)
3260 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3261 if (ret)
3262 {
3263 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3264 }
3265 else
3266 {
3267 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3268 End();
3269 }
3270 return ret;
3271 }
3272
3273 //-----------------------------------------------------------------------------
3274 // [SECTION] STYLING
3275 //-----------------------------------------------------------------------------
3276
3277 ImGuiStyle& ImGui::GetStyle()
3278 {
3279 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3280 return GImGui->Style;
3281 }
3282
3283 ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3284 {
3285 ImGuiStyle& style = GImGui->Style;
3286 ImVec4 c = style.Colors[idx];
3287 c.w *= style.Alpha * alpha_mul;
3288 return ColorConvertFloat4ToU32(c);
3289 }
3290
3291 ImU32 ImGui::GetColorU32(const ImVec4& col)
3292 {
3293 ImGuiStyle& style = GImGui->Style;
3294 ImVec4 c = col;
3295 c.w *= style.Alpha;
3296 return ColorConvertFloat4ToU32(c);
3297 }
3298
3299 const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3300 {
3301 ImGuiStyle& style = GImGui->Style;
3302 return style.Colors[idx];
3303 }
3304
3305 ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3306 {
3307 ImGuiStyle& style = GImGui->Style;
3308 alpha_mul *= style.Alpha;
3309 if (alpha_mul >= 1.0f)
3310 return col;
3311 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3312 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3313 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3314 }
3315
3316 // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3317 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3318 {
3319 ImGuiContext& g = *GImGui;
3320 ImGuiColorMod backup;
3321 backup.Col = idx;
3322 backup.BackupValue = g.Style.Colors[idx];
3323 g.ColorStack.push_back(backup);
3324 if (g.DebugFlashStyleColorIdx != idx)
3325 g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3326 }
3327
3328 void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3329 {
3330 ImGuiContext& g = *GImGui;
3331 ImGuiColorMod backup;
3332 backup.Col = idx;
3333 backup.BackupValue = g.Style.Colors[idx];
3334 g.ColorStack.push_back(backup);
3335 if (g.DebugFlashStyleColorIdx != idx)
3336 g.Style.Colors[idx] = col;
3337 }
3338
3339 void ImGui::PopStyleColor(int count)
3340 {
3341 ImGuiContext& g = *GImGui;
3342 if (g.ColorStack.Size < count)
3343 {
3344 IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
3345 count = g.ColorStack.Size;
3346 }
3347 while (count > 0)
3348 {
3349 ImGuiColorMod& backup = g.ColorStack.back();
3350 g.Style.Colors[backup.Col] = backup.BackupValue;
3351 g.ColorStack.pop_back();
3352 count--;
3353 }
3354 }
3355
3356 static const ImGuiDataVarInfo GStyleVarInfo[] =
3357 {
3358 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3359 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3360 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3361 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3362 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3363 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3364 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3365 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3366 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3367 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3368 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3369 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3370 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3371 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3372 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3373 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3374 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3375 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3376 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3377 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3378 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3379 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3380 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3381 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3382 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3383 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3384 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3385 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3386 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3387 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3388 { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3389 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3390 { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3391 };
3392
3393 const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3394 {
3395 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3396 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3397 return &GStyleVarInfo[idx];
3398 }
3399
3400 void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3401 {
3402 ImGuiContext& g = *GImGui;
3403 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3404 if (var_info->Type != ImGuiDataType_Float || var_info->Count != 1)
3405 {
3406 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3407 return;
3408 }
3409 float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3410 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3411 *pvar = val;
3412 }
3413
3414 void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
3415 {
3416 ImGuiContext& g = *GImGui;
3417 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3418 if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2)
3419 {
3420 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3421 return;
3422 }
3423 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3424 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3425 pvar->x = val_x;
3426 }
3427
3428 void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
3429 {
3430 ImGuiContext& g = *GImGui;
3431 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3432 if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2)
3433 {
3434 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3435 return;
3436 }
3437 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3438 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3439 pvar->y = val_y;
3440 }
3441
3442 void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3443 {
3444 ImGuiContext& g = *GImGui;
3445 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3446 if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2)
3447 {
3448 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3449 return;
3450 }
3451 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3452 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3453 *pvar = val;
3454 }
3455
3456 void ImGui::PopStyleVar(int count)
3457 {
3458 ImGuiContext& g = *GImGui;
3459 if (g.StyleVarStack.Size < count)
3460 {
3461 IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
3462 count = g.StyleVarStack.Size;
3463 }
3464 while (count > 0)
3465 {
3466 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3467 ImGuiStyleMod& backup = g.StyleVarStack.back();
3468 const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3469 void* data = info->GetVarPtr(&g.Style);
3470 if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3471 else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3472 g.StyleVarStack.pop_back();
3473 count--;
3474 }
3475 }
3476
3477 const char* ImGui::GetStyleColorName(ImGuiCol idx)
3478 {
3479 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3480 switch (idx)
3481 {
3482 case ImGuiCol_Text: return "Text";
3483 case ImGuiCol_TextDisabled: return "TextDisabled";
3484 case ImGuiCol_WindowBg: return "WindowBg";
3485 case ImGuiCol_ChildBg: return "ChildBg";
3486 case ImGuiCol_PopupBg: return "PopupBg";
3487 case ImGuiCol_Border: return "Border";
3488 case ImGuiCol_BorderShadow: return "BorderShadow";
3489 case ImGuiCol_FrameBg: return "FrameBg";
3490 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3491 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3492 case ImGuiCol_TitleBg: return "TitleBg";
3493 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3494 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3495 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3496 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3497 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3498 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3499 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3500 case ImGuiCol_CheckMark: return "CheckMark";
3501 case ImGuiCol_SliderGrab: return "SliderGrab";
3502 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3503 case ImGuiCol_Button: return "Button";
3504 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3505 case ImGuiCol_ButtonActive: return "ButtonActive";
3506 case ImGuiCol_Header: return "Header";
3507 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3508 case ImGuiCol_HeaderActive: return "HeaderActive";
3509 case ImGuiCol_Separator: return "Separator";
3510 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3511 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3512 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3513 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3514 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3515 case ImGuiCol_TabHovered: return "TabHovered";
3516 case ImGuiCol_Tab: return "Tab";
3517 case ImGuiCol_TabSelected: return "TabSelected";
3518 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3519 case ImGuiCol_TabDimmed: return "TabDimmed";
3520 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3521 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3522 case ImGuiCol_PlotLines: return "PlotLines";
3523 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3524 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3525 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3526 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3527 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3528 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3529 case ImGuiCol_TableRowBg: return "TableRowBg";
3530 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3531 case ImGuiCol_TextLink: return "TextLink";
3532 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3533 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3534 case ImGuiCol_NavCursor: return "NavCursor";
3535 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3536 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3537 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3538 }
3539 IM_ASSERT(0);
3540 return "Unknown";
3541 }
3542
3543
3544 //-----------------------------------------------------------------------------
3545 // [SECTION] RENDER HELPERS
3546 // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3547 // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3548 // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3549 //-----------------------------------------------------------------------------
3550
3551 const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3552 {
3553 const char* text_display_end = text;
3554 if (!text_end)
3555 text_end = (const char*)-1;
3556
3557 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3558 text_display_end++;
3559 return text_display_end;
3560 }
3561
3562 // Internal ImGui functions to render text
3563 // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3564 void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3565 {
3566 ImGuiContext& g = *GImGui;
3567 ImGuiWindow* window = g.CurrentWindow;
3568
3569 // Hide anything after a '##' string
3570 const char* text_display_end;
3571 if (hide_text_after_hash)
3572 {
3573 text_display_end = FindRenderedTextEnd(text, text_end);
3574 }
3575 else
3576 {
3577 if (!text_end)
3578 text_end = text + strlen(text); // FIXME-OPT
3579 text_display_end = text_end;
3580 }
3581
3582 if (text != text_display_end)
3583 {
3584 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3585 if (g.LogEnabled)
3586 LogRenderedText(&pos, text, text_display_end);
3587 }
3588 }
3589
3590 void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3591 {
3592 ImGuiContext& g = *GImGui;
3593 ImGuiWindow* window = g.CurrentWindow;
3594
3595 if (!text_end)
3596 text_end = text + strlen(text); // FIXME-OPT
3597
3598 if (text != text_end)
3599 {
3600 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3601 if (g.LogEnabled)
3602 LogRenderedText(&pos, text, text_end);
3603 }
3604 }
3605
3606 // Default clip_rect uses (pos_min,pos_max)
3607 // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3608 // FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3609 // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3610 // better advantage of the render function taking size into account for coarse clipping.
3611 void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3612 {
3613 // Perform CPU side clipping for single clipped element to avoid using scissor state
3614 ImVec2 pos = pos_min;
3615 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3616
3617 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3618 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3619 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3620 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3621 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3622
3623 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3624 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3625 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3626
3627 // Render
3628 if (need_clipping)
3629 {
3630 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3631 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3632 }
3633 else
3634 {
3635 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3636 }
3637 }
3638
3639 void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3640 {
3641 // Hide anything after a '##' string
3642 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3643 const int text_len = (int)(text_display_end - text);
3644 if (text_len == 0)
3645 return;
3646
3647 ImGuiContext& g = *GImGui;
3648 ImGuiWindow* window = g.CurrentWindow;
3649 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3650 if (g.LogEnabled)
3651 LogRenderedText(&pos_min, text, text_display_end);
3652 }
3653
3654 // Another overly complex function until we reorganize everything into a nice all-in-one helper.
3655 // This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3656 // This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3657 void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3658 {
3659 ImGuiContext& g = *GImGui;
3660 if (text_end_full == NULL)
3661 text_end_full = FindRenderedTextEnd(text);
3662 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3663
3664 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3665 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3666 //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3667 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3668 if (text_size.x > pos_max.x - pos_min.x)
3669 {
3670 // Hello wo...
3671 // | | |
3672 // min max ellipsis_max
3673 // <-> this is generally some padding value
3674
3675 ImFont* font = draw_list->_Data->Font;
3676 const float font_size = draw_list->_Data->FontSize;
3677 const float font_scale = draw_list->_Data->FontScale;
3678 const char* text_end_ellipsis = NULL;
3679 const float ellipsis_width = font->EllipsisWidth * font_scale;
3680
3681 // We can now claim the space between pos_max.x and ellipsis_max.x
3682 const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3683 float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3684 if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3685 {
3686 // Always display at least 1 character if there's no room for character + ellipsis
3687 text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3688 text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3689 }
3690 while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3691 {
3692 // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3693 text_end_ellipsis--;
3694 text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3695 }
3696
3697 // Render text, render ellipsis
3698 RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3699 ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3700 if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3701 for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3702 font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3703 }
3704 else
3705 {
3706 RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3707 }
3708
3709 if (g.LogEnabled)
3710 LogRenderedText(&pos_min, text, text_end_full);
3711 }
3712
3713 // Render a rectangle shaped with optional rounding and borders
3714 void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding)
3715 {
3716 ImGuiContext& g = *GImGui;
3717 ImGuiWindow* window = g.CurrentWindow;
3718 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3719 const float border_size = g.Style.FrameBorderSize;
3720 if (borders && border_size > 0.0f)
3721 {
3722 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3723 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3724 }
3725 }
3726
3727 void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3728 {
3729 ImGuiContext& g = *GImGui;
3730 ImGuiWindow* window = g.CurrentWindow;
3731 const float border_size = g.Style.FrameBorderSize;
3732 if (border_size > 0.0f)
3733 {
3734 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3735 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3736 }
3737 }
3738
3739 void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags)
3740 {
3741 ImGuiContext& g = *GImGui;
3742 if (id != g.NavId)
3743 return;
3744 if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
3745 return;
3746 if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
3747 return;
3748 ImGuiWindow* window = g.CurrentWindow;
3749 if (window->DC.NavHideHighlightOneFrame)
3750 return;
3751
3752 float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3753 ImRect display_rect = bb;
3754 display_rect.ClipWith(window->ClipRect);
3755 const float thickness = 2.0f;
3756 if (flags & ImGuiNavRenderCursorFlags_Compact)
3757 {
3758 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
3759 }
3760 else
3761 {
3762 const float distance = 3.0f + thickness * 0.5f;
3763 display_rect.Expand(ImVec2(distance, distance));
3764 bool fully_visible = window->ClipRect.Contains(display_rect);
3765 if (!fully_visible)
3766 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3767 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
3768 if (!fully_visible)
3769 window->DrawList->PopClipRect();
3770 }
3771 }
3772
3773 void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3774 {
3775 ImGuiContext& g = *GImGui;
3776 if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
3777 mouse_cursor = ImGuiMouseCursor_Arrow;
3778 ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3779 for (ImGuiViewportP* viewport : g.Viewports)
3780 {
3781 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3782 ImVec2 offset, size, uv[4];
3783 if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3784 continue;
3785 const ImVec2 pos = base_pos - offset;
3786 const float scale = base_scale;
3787 if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3788 continue;
3789 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3790 ImTextureID tex_id = font_atlas->TexID;
3791 draw_list->PushTextureID(tex_id);
3792 draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3793 draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3794 draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border);
3795 draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill);
3796 draw_list->PopTextureID();
3797 }
3798 }
3799
3800 //-----------------------------------------------------------------------------
3801 // [SECTION] INITIALIZATION, SHUTDOWN
3802 //-----------------------------------------------------------------------------
3803
3804 // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3805 // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3806 ImGuiContext* ImGui::GetCurrentContext()
3807 {
3808 return GImGui;
3809 }
3810
3811 void ImGui::SetCurrentContext(ImGuiContext* ctx)
3812 {
3813 #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3814 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3815 #else
3816 GImGui = ctx;
3817 #endif
3818 }
3819
3820 void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3821 {
3822 GImAllocatorAllocFunc = alloc_func;
3823 GImAllocatorFreeFunc = free_func;
3824 GImAllocatorUserData = user_data;
3825 }
3826
3827 // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3828 void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3829 {
3830 *p_alloc_func = GImAllocatorAllocFunc;
3831 *p_free_func = GImAllocatorFreeFunc;
3832 *p_user_data = GImAllocatorUserData;
3833 }
3834
3835 ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3836 {
3837 ImGuiContext* prev_ctx = GetCurrentContext();
3838 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3839 SetCurrentContext(ctx);
3840 Initialize();
3841 if (prev_ctx != NULL)
3842 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3843 return ctx;
3844 }
3845
3846 void ImGui::DestroyContext(ImGuiContext* ctx)
3847 {
3848 ImGuiContext* prev_ctx = GetCurrentContext();
3849 if (ctx == NULL) //-V1051
3850 ctx = prev_ctx;
3851 SetCurrentContext(ctx);
3852 Shutdown();
3853 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3854 IM_DELETE(ctx);
3855 }
3856
3857 // IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation.
3858 static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3859 {
3860 { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3861 { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" },
3862 { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" },
3863 { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" },
3864 { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" },
3865 { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" },
3866 { ImGuiLocKey_WindowingPopup, "(Popup)" },
3867 { ImGuiLocKey_WindowingUntitled, "(Untitled)" },
3868 { ImGuiLocKey_OpenLink_s, "Open '%s'" },
3869 { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" },
3870 };
3871
3872 ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
3873 {
3874 IO.Ctx = this;
3875 InputTextState.Ctx = this;
3876
3877 Initialized = false;
3878 FontAtlasOwnedByContext = shared_font_atlas ? false : true;
3879 Font = NULL;
3880 FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f;
3881 IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
3882 Time = 0.0f;
3883 FrameCount = 0;
3884 FrameCountEnded = FrameCountRendered = -1;
3885 WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;
3886 GcCompactAll = false;
3887 TestEngineHookItems = false;
3888 TestEngine = NULL;
3889 memset(ContextName, 0, sizeof(ContextName));
3890
3891 InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
3892 InputEventsNextEventId = 1;
3893
3894 WindowsActiveCount = 0;
3895 CurrentWindow = NULL;
3896 HoveredWindow = NULL;
3897 HoveredWindowUnderMovingWindow = NULL;
3898 HoveredWindowBeforeClear = NULL;
3899 MovingWindow = NULL;
3900 WheelingWindow = NULL;
3901 WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
3902 WheelingWindowReleaseTimer = 0.0f;
3903
3904 DebugDrawIdConflicts = 0;
3905 DebugHookIdInfo = 0;
3906 HoveredId = HoveredIdPreviousFrame = 0;
3907 HoveredIdPreviousFrameItemCount = 0;
3908 HoveredIdAllowOverlap = false;
3909 HoveredIdIsDisabled = false;
3910 HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
3911 ItemUnclipByLog = false;
3912 ActiveId = 0;
3913 ActiveIdIsAlive = 0;
3914 ActiveIdTimer = 0.0f;
3915 ActiveIdIsJustActivated = false;
3916 ActiveIdAllowOverlap = false;
3917 ActiveIdNoClearOnFocusLoss = false;
3918 ActiveIdHasBeenPressedBefore = false;
3919 ActiveIdHasBeenEditedBefore = false;
3920 ActiveIdHasBeenEditedThisFrame = false;
3921 ActiveIdFromShortcut = false;
3922 ActiveIdClickOffset = ImVec2(-1, -1);
3923 ActiveIdWindow = NULL;
3924 ActiveIdSource = ImGuiInputSource_None;
3925 ActiveIdMouseButton = -1;
3926 ActiveIdPreviousFrame = 0;
3927 ActiveIdPreviousFrameIsAlive = false;
3928 ActiveIdPreviousFrameHasBeenEditedBefore = false;
3929 ActiveIdPreviousFrameWindow = NULL;
3930 LastActiveId = 0;
3931 LastActiveIdTimer = 0.0f;
3932
3933 LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
3934
3935 ActiveIdUsingNavDirMask = 0x00;
3936 ActiveIdUsingAllKeyboardKeys = false;
3937
3938 CurrentFocusScopeId = 0;
3939 CurrentItemFlags = ImGuiItemFlags_None;
3940 DebugShowGroupRects = false;
3941
3942 NavCursorVisible = false;
3943 NavHighlightItemUnderNav = false;
3944 NavMousePosDirty = false;
3945 NavIdIsAlive = false;
3946 NavId = 0;
3947 NavWindow = NULL;
3948 NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
3949 NavLayer = ImGuiNavLayer_Main;
3950 NavNextActivateId = 0;
3951 NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
3952 NavHighlightActivatedId = 0;
3953 NavHighlightActivatedTimer = 0.0f;
3954 NavInputSource = ImGuiInputSource_Keyboard;
3955 NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
3956 NavCursorHideFrames = 0;
3957
3958 NavAnyRequest = false;
3959 NavInitRequest = false;
3960 NavInitRequestFromMove = false;
3961 NavMoveSubmitted = false;
3962 NavMoveScoringItems = false;
3963 NavMoveForwardToNextFrame = false;
3964 NavMoveFlags = ImGuiNavMoveFlags_None;
3965 NavMoveScrollFlags = ImGuiScrollFlags_None;
3966 NavMoveKeyMods = ImGuiMod_None;
3967 NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
3968 NavScoringDebugCount = 0;
3969 NavTabbingDir = 0;
3970 NavTabbingCounter = 0;
3971
3972 NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
3973 NavJustMovedToKeyMods = ImGuiMod_None;
3974 NavJustMovedToIsTabbing = false;
3975 NavJustMovedToHasSelectionData = false;
3976
3977 // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
3978 // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
3979 ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
3980 ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
3981 NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
3982 NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
3983 NavWindowingToggleLayer = false;
3984 NavWindowingToggleKey = ImGuiKey_None;
3985
3986 DimBgRatio = 0.0f;
3987
3988 DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
3989 DragDropSourceFlags = ImGuiDragDropFlags_None;
3990 DragDropSourceFrameCount = -1;
3991 DragDropMouseButton = -1;
3992 DragDropTargetId = 0;
3993 DragDropAcceptFlags = ImGuiDragDropFlags_None;
3994 DragDropAcceptIdCurrRectSurface = 0.0f;
3995 DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
3996 DragDropAcceptFrameCount = -1;
3997 DragDropHoldJustPressedId = 0;
3998 memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
3999
4000 ClipperTempDataStacked = 0;
4001
4002 CurrentTable = NULL;
4003 TablesTempDataStacked = 0;
4004 CurrentTabBar = NULL;
4005 CurrentMultiSelect = NULL;
4006 MultiSelectTempDataStacked = 0;
4007
4008 HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
4009 HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
4010
4011 MouseCursor = ImGuiMouseCursor_Arrow;
4012 MouseStationaryTimer = 0.0f;
4013
4014 TempInputId = 0;
4015 memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
4016 BeginMenuDepth = BeginComboDepth = 0;
4017 ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
4018 ColorEditCurrentID = ColorEditSavedID = 0;
4019 ColorEditSavedHue = ColorEditSavedSat = 0.0f;
4020 ColorEditSavedColor = 0;
4021 WindowResizeRelativeMode = false;
4022 ScrollbarSeekMode = 0;
4023 ScrollbarClickDeltaToGrabCenter = 0.0f;
4024 SliderGrabClickOffset = 0.0f;
4025 SliderCurrentAccum = 0.0f;
4026 SliderCurrentAccumDirty = false;
4027 DragCurrentAccumDirty = false;
4028 DragCurrentAccum = 0.0f;
4029 DragSpeedDefaultRatio = 1.0f / 100.0f;
4030 DisabledAlphaBackup = 0.0f;
4031 DisabledStackSize = 0;
4032 TooltipOverrideCount = 0;
4033 TooltipPreviousWindow = NULL;
4034
4035 PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
4036 PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
4037
4038 SettingsLoaded = false;
4039 SettingsDirtyTimer = 0.0f;
4040 HookIdNext = 0;
4041
4042 memset(LocalizationTable, 0, sizeof(LocalizationTable));
4043
4044 LogEnabled = false;
4045 LogFlags = ImGuiLogFlags_None;
4046 LogWindow = NULL;
4047 LogNextPrefix = LogNextSuffix = NULL;
4048 LogFile = NULL;
4049 LogLinePosY = FLT_MAX;
4050 LogLineFirstItem = false;
4051 LogDepthRef = 0;
4052 LogDepthToExpand = LogDepthToExpandDefault = 2;
4053
4054 ErrorCallback = NULL;
4055 ErrorCallbackUserData = NULL;
4056 ErrorFirst = true;
4057 ErrorCountCurrentFrame = 0;
4058 StackSizesInBeginForCurrentWindow = NULL;
4059
4060 DebugDrawIdConflictsCount = 0;
4061 DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY | ImGuiDebugLogFlags_EventFont;
4062 DebugLocateId = 0;
4063 DebugLogSkippedErrors = 0;
4064 DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4065 DebugLogAutoDisableFrames = 0;
4066 DebugLocateFrames = 0;
4067 DebugBeginReturnValueCullDepth = -1;
4068 DebugItemPickerActive = false;
4069 DebugItemPickerMouseButton = ImGuiMouseButton_Left;
4070 DebugItemPickerBreakId = 0;
4071 DebugFlashStyleColorTime = 0.0f;
4072 DebugFlashStyleColorIdx = ImGuiCol_COUNT;
4073
4074 // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
4075 DebugBreakInWindow = 0;
4076 DebugBreakInTable = 0;
4077 DebugBreakInLocateId = false;
4078 DebugBreakKeyChord = ImGuiKey_Pause;
4079 DebugBreakInShortcutRouting = ImGuiKey_None;
4080
4081 memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
4082 FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
4083 FramerateSecPerFrameAccum = 0.0f;
4084 WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
4085 memset(TempKeychordName, 0, sizeof(TempKeychordName));
4086 }
4087
4088 void ImGui::Initialize()
4089 {
4090 ImGuiContext& g = *GImGui;
4091 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4092
4093 // Add .ini handle for ImGuiWindow and ImGuiTable types
4094 {
4095 ImGuiSettingsHandler ini_handler;
4096 ini_handler.TypeName = "Window";
4097 ini_handler.TypeHash = ImHashStr("Window");
4098 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4099 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4100 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4101 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4102 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4103 AddSettingsHandler(&ini_handler);
4104 }
4105 TableSettingsAddSettingsHandler();
4106
4107 // Setup default localization table
4108 LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
4109
4110 // Setup default ImGuiPlatformIO clipboard/IME handlers.
4111 g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
4112 g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl;
4113 g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl;
4114 g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl;
4115
4116 // Create default viewport
4117 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4118 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4119 g.Viewports.push_back(viewport);
4120 g.TempBuffer.resize(1024 * 3 + 1, 0);
4121
4122 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
4123 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4124 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
4125 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
4126 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
4127 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
4128 g.KeysMayBeCharInput.SetBit(key);
4129
4130 #ifdef IMGUI_HAS_DOCK
4131 #endif
4132
4133 g.Initialized = true;
4134 }
4135
4136 // This function is merely here to free heap allocations.
4137 void ImGui::Shutdown()
4138 {
4139 ImGuiContext& g = *GImGui;
4140 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
4141 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
4142
4143 // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
4144 if (g.IO.Fonts && g.FontAtlasOwnedByContext)
4145 {
4146 g.IO.Fonts->Locked = false;
4147 IM_DELETE(g.IO.Fonts);
4148 }
4149 g.IO.Fonts = NULL;
4150 g.DrawListSharedData.TempBuffer.clear();
4151
4152 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4153 if (!g.Initialized)
4154 return;
4155
4156 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4157 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4158 SaveIniSettingsToDisk(g.IO.IniFilename);
4159
4160 CallContextHooks(&g, ImGuiContextHookType_Shutdown);
4161
4162 // Clear everything else
4163 g.Windows.clear_delete();
4164 g.WindowsFocusOrder.clear();
4165 g.WindowsTempSortBuffer.clear();
4166 g.CurrentWindow = NULL;
4167 g.CurrentWindowStack.clear();
4168 g.WindowsById.Clear();
4169 g.NavWindow = NULL;
4170 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4171 g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
4172 g.MovingWindow = NULL;
4173
4174 g.KeysRoutingTable.Clear();
4175
4176 g.ColorStack.clear();
4177 g.StyleVarStack.clear();
4178 g.FontStack.clear();
4179 g.OpenPopupStack.clear();
4180 g.BeginPopupStack.clear();
4181 g.TreeNodeStack.clear();
4182
4183 g.Viewports.clear_delete();
4184
4185 g.TabBars.Clear();
4186 g.CurrentTabBarStack.clear();
4187 g.ShrinkWidthBuffer.clear();
4188
4189 g.ClipperTempData.clear_destruct();
4190
4191 g.Tables.Clear();
4192 g.TablesTempData.clear_destruct();
4193 g.DrawChannelsTempMergeBuffer.clear();
4194
4195 g.MultiSelectStorage.Clear();
4196 g.MultiSelectTempData.clear_destruct();
4197
4198 g.ClipboardHandlerData.clear();
4199 g.MenusIdSubmittedThisFrame.clear();
4200 g.InputTextState.ClearFreeMemory();
4201 g.InputTextDeactivatedState.ClearFreeMemory();
4202
4203 g.SettingsWindows.clear();
4204 g.SettingsHandlers.clear();
4205
4206 if (g.LogFile)
4207 {
4208 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4209 if (g.LogFile != stdout)
4210 #endif
4211 ImFileClose(g.LogFile);
4212 g.LogFile = NULL;
4213 }
4214 g.LogBuffer.clear();
4215 g.DebugLogBuf.clear();
4216 g.DebugLogIndex.clear();
4217
4218 g.Initialized = false;
4219 }
4220
4221 // No specific ordering/dependency support, will see as needed
4222 ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
4223 {
4224 ImGuiContext& g = *ctx;
4225 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
4226 g.Hooks.push_back(*hook);
4227 g.Hooks.back().HookId = ++g.HookIdNext;
4228 return g.HookIdNext;
4229 }
4230
4231 // Deferred removal, avoiding issue with changing vector while iterating it
4232 void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
4233 {
4234 ImGuiContext& g = *ctx;
4235 IM_ASSERT(hook_id != 0);
4236 for (ImGuiContextHook& hook : g.Hooks)
4237 if (hook.HookId == hook_id)
4238 hook.Type = ImGuiContextHookType_PendingRemoval_;
4239 }
4240
4241 // Call context hooks (used by e.g. test engine)
4242 // We assume a small number of hooks so all stored in same array
4243 void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
4244 {
4245 ImGuiContext& g = *ctx;
4246 for (ImGuiContextHook& hook : g.Hooks)
4247 if (hook.Type == hook_type)
4248 hook.Callback(&g, &hook);
4249 }
4250
4251
4252 //-----------------------------------------------------------------------------
4253 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4254 //-----------------------------------------------------------------------------
4255
4256 // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4257 ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4258 {
4259 memset(this, 0, sizeof(*this));
4260 Ctx = ctx;
4261 Name = ImStrdup(name);
4262 NameBufLen = (int)strlen(name) + 1;
4263 ID = ImHashStr(name);
4264 IDStack.push_back(ID);
4265 MoveId = GetID("#MOVE");
4266 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4267 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4268 AutoFitFramesX = AutoFitFramesY = -1;
4269 AutoPosLastDirection = ImGuiDir_None;
4270 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = 0;
4271 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4272 LastFrameActive = -1;
4273 LastTimeActive = -1.0f;
4274 FontWindowScale = 1.0f;
4275 SettingsOffset = -1;
4276 DrawList = &DrawListInst;
4277 DrawList->_OwnerName = Name;
4278 DrawList->_Data = &Ctx->DrawListSharedData;
4279 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4280 }
4281
4282 ImGuiWindow::~ImGuiWindow()
4283 {
4284 IM_ASSERT(DrawList == &DrawListInst);
4285 IM_DELETE(Name);
4286 ColumnsStorage.clear_destruct();
4287 }
4288
4289 static void SetCurrentWindow(ImGuiWindow* window)
4290 {
4291 ImGuiContext& g = *GImGui;
4292 g.CurrentWindow = window;
4293 g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
4294 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4295 g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking
4296 if (window)
4297 {
4298 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
4299 g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
4300 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4301 }
4302 }
4303
4304 void ImGui::GcCompactTransientMiscBuffers()
4305 {
4306 ImGuiContext& g = *GImGui;
4307 g.ItemFlagsStack.clear();
4308 g.GroupStack.clear();
4309 g.MultiSelectTempDataStacked = 0;
4310 g.MultiSelectTempData.clear_destruct();
4311 TableGcCompactSettings();
4312 }
4313
4314 // Free up/compact internal window buffers, we can use this when a window becomes unused.
4315 // Not freed:
4316 // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4317 // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4318 void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4319 {
4320 window->MemoryCompacted = true;
4321 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4322 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4323 window->IDStack.clear();
4324 window->DrawList->_ClearFreeMemory();
4325 window->DC.ChildWindows.clear();
4326 window->DC.ItemWidthStack.clear();
4327 window->DC.TextWrapPosStack.clear();
4328 }
4329
4330 void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4331 {
4332 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4333 // The other buffers tends to amortize much faster.
4334 window->MemoryCompacted = false;
4335 window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4336 window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4337 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4338 }
4339
4340 void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4341 {
4342 ImGuiContext& g = *GImGui;
4343
4344 // Clear previous active id
4345 if (g.ActiveId != 0)
4346 {
4347 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4348 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4349 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4350 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4351 {
4352 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4353 g.MovingWindow = NULL;
4354 }
4355
4356 // This could be written in a more general way (e.g associate a hook to ActiveId),
4357 // but since this is currently quite an exception we'll leave it as is.
4358 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4359 if (g.InputTextState.ID == g.ActiveId)
4360 InputTextDeactivateHook(g.ActiveId);
4361 }
4362
4363 // Set active id
4364 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4365 if (g.ActiveIdIsJustActivated)
4366 {
4367 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4368 g.ActiveIdTimer = 0.0f;
4369 g.ActiveIdHasBeenPressedBefore = false;
4370 g.ActiveIdHasBeenEditedBefore = false;
4371 g.ActiveIdMouseButton = -1;
4372 if (id != 0)
4373 {
4374 g.LastActiveId = id;
4375 g.LastActiveIdTimer = 0.0f;
4376 }
4377 }
4378 g.ActiveId = id;
4379 g.ActiveIdAllowOverlap = false;
4380 g.ActiveIdNoClearOnFocusLoss = false;
4381 g.ActiveIdWindow = window;
4382 g.ActiveIdHasBeenEditedThisFrame = false;
4383 g.ActiveIdFromShortcut = false;
4384 if (id)
4385 {
4386 g.ActiveIdIsAlive = id;
4387 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4388 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4389 }
4390
4391 // Clear declaration of inputs claimed by the widget
4392 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4393 g.ActiveIdUsingNavDirMask = 0x00;
4394 g.ActiveIdUsingAllKeyboardKeys = false;
4395 }
4396
4397 void ImGui::ClearActiveID()
4398 {
4399 SetActiveID(0, NULL); // g.ActiveId = 0;
4400 }
4401
4402 void ImGui::SetHoveredID(ImGuiID id)
4403 {
4404 ImGuiContext& g = *GImGui;
4405 g.HoveredId = id;
4406 g.HoveredIdAllowOverlap = false;
4407 if (id != 0 && g.HoveredIdPreviousFrame != id)
4408 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4409 }
4410
4411 ImGuiID ImGui::GetHoveredID()
4412 {
4413 ImGuiContext& g = *GImGui;
4414 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4415 }
4416
4417 void ImGui::MarkItemEdited(ImGuiID id)
4418 {
4419 // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
4420 // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4421 ImGuiContext& g = *GImGui;
4422 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
4423 return;
4424 if (g.ActiveId == id || g.ActiveId == 0)
4425 {
4426 g.ActiveIdHasBeenEditedThisFrame = true;
4427 g.ActiveIdHasBeenEditedBefore = true;
4428 }
4429
4430 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4431 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4432 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4433
4434 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4435 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4436 }
4437
4438 bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4439 {
4440 // An active popup disable hovering on other windows (apart from its own children)
4441 // FIXME-OPT: This could be cached/stored within the window.
4442 ImGuiContext& g = *GImGui;
4443 if (g.NavWindow)
4444 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
4445 if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
4446 {
4447 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4448 // NB: The 'else' is important because Modal windows are also Popups.
4449 bool want_inhibit = false;
4450 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4451 want_inhibit = true;
4452 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4453 want_inhibit = true;
4454
4455 // Inhibit hover unless the window is within the stack of our modal/popup
4456 if (want_inhibit)
4457 if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4458 return false;
4459 }
4460 return true;
4461 }
4462
4463 static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4464 {
4465 ImGuiContext& g = *GImGui;
4466 if (flags & ImGuiHoveredFlags_DelayNormal)
4467 return g.Style.HoverDelayNormal;
4468 if (flags & ImGuiHoveredFlags_DelayShort)
4469 return g.Style.HoverDelayShort;
4470 return 0.0f;
4471 }
4472
4473 static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4474 {
4475 // Allow instance flags to override shared flags
4476 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4477 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4478 return user_flags | shared_flags;
4479 }
4480
4481 // This is roughly matching the behavior of internal-facing ItemHoverable()
4482 // - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4483 // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4484 bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4485 {
4486 ImGuiContext& g = *GImGui;
4487 ImGuiWindow* window = g.CurrentWindow;
4488 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
4489
4490 if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
4491 {
4492 if (!IsItemFocused())
4493 return false;
4494 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4495 return false;
4496
4497 if (flags & ImGuiHoveredFlags_ForTooltip)
4498 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4499 }
4500 else
4501 {
4502 // Test for bounding box overlap, as updated as ItemAdd()
4503 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4504 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4505 return false;
4506
4507 if (flags & ImGuiHoveredFlags_ForTooltip)
4508 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4509
4510 // Done with rectangle culling so we can perform heavier checks now
4511 // Test if we are hovering the right window (our window could be behind another window)
4512 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4513 // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4514 // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4515 // the test that has been running for a long while.
4516 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4517 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4518 return false;
4519
4520 // Test if another item is active (e.g. being dragged)
4521 const ImGuiID id = g.LastItemData.ID;
4522 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4523 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4524 if (g.ActiveId != window->MoveId)
4525 return false;
4526
4527 // Test if interactions on this window are blocked by an active popup or modal.
4528 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4529 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4530 return false;
4531
4532 // Test if the item is disabled
4533 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4534 return false;
4535
4536 // Special handling for calling after Begin() which represent the title bar or tab.
4537 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4538 // will never be overwritten so we need to detect the case.
4539 if (id == window->MoveId && window->WriteAccessed)
4540 return false;
4541
4542 // Test if using AllowOverlap and overlapped
4543 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4544 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4545 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4546 return false;
4547 }
4548
4549 // Handle hover delay
4550 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4551 const float delay = CalcDelayFromHoveredFlags(flags);
4552 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4553 {
4554 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(g.LastItemData.Rect.Min);
4555 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4556 g.HoverItemDelayTimer = 0.0f;
4557 g.HoverItemDelayId = hover_delay_id;
4558
4559 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4560 // but once unlocked on a given item we also moving.
4561 //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4562 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4563 return false;
4564
4565 if (g.HoverItemDelayTimer < delay)
4566 return false;
4567 }
4568
4569 return true;
4570 }
4571
4572 // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4573 // (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4574 // FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4575 // If you used this in your legacy/custom widgets code:
4576 // - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
4577 // - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4578 bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4579 {
4580 ImGuiContext& g = *GImGui;
4581 ImGuiWindow* window = g.CurrentWindow;
4582
4583 // Detect ID conflicts
4584 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4585 if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
4586 {
4587 g.HoveredIdPreviousFrameItemCount++;
4588 if (g.DebugDrawIdConflicts == id)
4589 window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f);
4590 }
4591 #endif
4592
4593 if (g.HoveredWindow != window)
4594 return false;
4595 if (!IsMouseHoveringRect(bb.Min, bb.Max))
4596 return false;
4597
4598 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4599 return false;
4600 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4601 if (!g.ActiveIdFromShortcut)
4602 return false;
4603
4604 // Done with rectangle culling so we can perform heavier checks now.
4605 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4606 {
4607 g.HoveredIdIsDisabled = true;
4608 return false;
4609 }
4610
4611 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4612 // hover test in widgets code. We could also decide to split this function is two.
4613 if (id != 0)
4614 {
4615 // Drag source doesn't report as hovered
4616 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4617 return false;
4618
4619 SetHoveredID(id);
4620
4621 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4622 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4623 if (item_flags & ImGuiItemFlags_AllowOverlap)
4624 {
4625 g.HoveredIdAllowOverlap = true;
4626 if (g.HoveredIdPreviousFrame != id)
4627 return false;
4628 }
4629
4630 // Display shortcut (only works with mouse)
4631 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4632 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
4633 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4634 SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4635 }
4636
4637 // When disabled we'll return false but still set HoveredId
4638 if (item_flags & ImGuiItemFlags_Disabled)
4639 {
4640 // Release active id if turning disabled
4641 if (g.ActiveId == id && id != 0)
4642 ClearActiveID();
4643 g.HoveredIdIsDisabled = true;
4644 return false;
4645 }
4646
4647 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4648 if (id != 0)
4649 {
4650 // [DEBUG] Item Picker tool!
4651 // We perform the check here because reaching is path is rare (1~ time a frame),
4652 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4653 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4654 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4655 GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4656 if (g.DebugItemPickerBreakId == id)
4657 IM_DEBUG_BREAK();
4658 }
4659 #endif
4660
4661 if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
4662 return false;
4663
4664 return true;
4665 }
4666
4667 // FIXME: This is inlined/duplicated in ItemAdd()
4668 // FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4669 bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4670 {
4671 ImGuiContext& g = *GImGui;
4672 ImGuiWindow* window = g.CurrentWindow;
4673 if (!bb.Overlaps(window->ClipRect))
4674 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4675 if (!g.ItemUnclipByLog)
4676 return true;
4677 return false;
4678 }
4679
4680 // This is also inlined in ItemAdd()
4681 // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4682 void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4683 {
4684 ImGuiContext& g = *GImGui;
4685 g.LastItemData.ID = item_id;
4686 g.LastItemData.ItemFlags = in_flags;
4687 g.LastItemData.StatusFlags = item_flags;
4688 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4689 }
4690
4691 float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4692 {
4693 if (wrap_pos_x < 0.0f)
4694 return 0.0f;
4695
4696 ImGuiContext& g = *GImGui;
4697 ImGuiWindow* window = g.CurrentWindow;
4698 if (wrap_pos_x == 0.0f)
4699 {
4700 // We could decide to setup a default wrapping max point for auto-resizing windows,
4701 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4702 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4703 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4704 //else
4705 wrap_pos_x = window->WorkRect.Max.x;
4706 }
4707 else if (wrap_pos_x > 0.0f)
4708 {
4709 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4710 }
4711
4712 return ImMax(wrap_pos_x - pos.x, 1.0f);
4713 }
4714
4715 // IM_ALLOC() == ImGui::MemAlloc()
4716 void* ImGui::MemAlloc(size_t size)
4717 {
4718 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4719 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4720 if (ImGuiContext* ctx = GImGui)
4721 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4722 #endif
4723 return ptr;
4724 }
4725
4726 // IM_FREE() == ImGui::MemFree()
4727 void ImGui::MemFree(void* ptr)
4728 {
4729 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4730 if (ptr != NULL)
4731 if (ImGuiContext* ctx = GImGui)
4732 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4733 #endif
4734 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4735 }
4736
4737 // We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4738 void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4739 {
4740 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4741 IM_UNUSED(ptr);
4742 if (entry->FrameCount != frame_count)
4743 {
4744 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4745 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4746 entry->FrameCount = frame_count;
4747 entry->AllocCount = entry->FreeCount = 0;
4748 }
4749 if (size != (size_t)-1)
4750 {
4751 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
4752 entry->AllocCount++;
4753 info->TotalAllocCount++;
4754 }
4755 else
4756 {
4757 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4758 entry->FreeCount++;
4759 info->TotalFreeCount++;
4760 }
4761 }
4762
4763 const char* ImGui::GetClipboardText()
4764 {
4765 ImGuiContext& g = *GImGui;
4766 return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : "";
4767 }
4768
4769 void ImGui::SetClipboardText(const char* text)
4770 {
4771 ImGuiContext& g = *GImGui;
4772 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
4773 g.PlatformIO.Platform_SetClipboardTextFn(&g, text);
4774 }
4775
4776 const char* ImGui::GetVersion()
4777 {
4778 return IMGUI_VERSION;
4779 }
4780
4781 ImGuiIO& ImGui::GetIO()
4782 {
4783 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4784 return GImGui->IO;
4785 }
4786
4787 // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
4788 ImGuiIO& ImGui::GetIOEx(ImGuiContext* ctx)
4789 {
4790 IM_ASSERT(ctx != NULL);
4791 return ctx->IO;
4792 }
4793
4794 ImGuiPlatformIO& ImGui::GetPlatformIO()
4795 {
4796 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
4797 return GImGui->PlatformIO;
4798 }
4799
4800 // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4801 ImDrawData* ImGui::GetDrawData()
4802 {
4803 ImGuiContext& g = *GImGui;
4804 ImGuiViewportP* viewport = g.Viewports[0];
4805 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4806 }
4807
4808 double ImGui::GetTime()
4809 {
4810 return GImGui->Time;
4811 }
4812
4813 int ImGui::GetFrameCount()
4814 {
4815 return GImGui->FrameCount;
4816 }
4817
4818 static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4819 {
4820 // Create the draw list on demand, because they are not frequently used for all viewports
4821 ImGuiContext& g = *GImGui;
4822 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4823 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4824 if (draw_list == NULL)
4825 {
4826 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4827 draw_list->_OwnerName = drawlist_name;
4828 viewport->BgFgDrawLists[drawlist_no] = draw_list;
4829 }
4830
4831 // Our ImDrawList system requires that there is always a command
4832 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4833 {
4834 draw_list->_ResetForNewFrame();
4835 draw_list->PushTextureID(g.IO.Fonts->TexID);
4836 draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4837 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4838 }
4839 return draw_list;
4840 }
4841
4842 ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4843 {
4844 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4845 }
4846
4847 ImDrawList* ImGui::GetBackgroundDrawList()
4848 {
4849 ImGuiContext& g = *GImGui;
4850 return GetBackgroundDrawList(g.Viewports[0]);
4851 }
4852
4853 ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4854 {
4855 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4856 }
4857
4858 ImDrawList* ImGui::GetForegroundDrawList()
4859 {
4860 ImGuiContext& g = *GImGui;
4861 return GetForegroundDrawList(g.Viewports[0]);
4862 }
4863
4864 ImDrawListSharedData* ImGui::GetDrawListSharedData()
4865 {
4866 return &GImGui->DrawListSharedData;
4867 }
4868
4869 void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4870 {
4871 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4872 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4873 // This is because we want ActiveId to be set even when the window is not permitted to move.
4874 ImGuiContext& g = *GImGui;
4875 FocusWindow(window);
4876 SetActiveID(window->MoveId, window);
4877 if (g.IO.ConfigNavCursorVisibleAuto)
4878 g.NavCursorVisible = false;
4879 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
4880 g.ActiveIdNoClearOnFocusLoss = true;
4881 SetActiveIdUsingAllKeyboardKeys();
4882
4883 bool can_move_window = true;
4884 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
4885 can_move_window = false;
4886 if (can_move_window)
4887 g.MovingWindow = window;
4888 }
4889
4890 // Handle mouse moving window
4891 // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4892 // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4893 // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4894 // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4895 void ImGui::UpdateMouseMovingWindowNewFrame()
4896 {
4897 ImGuiContext& g = *GImGui;
4898 if (g.MovingWindow != NULL)
4899 {
4900 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4901 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4902 KeepAliveID(g.ActiveId);
4903 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
4904 ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
4905 if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
4906 {
4907 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4908 SetWindowPos(moving_window, pos, ImGuiCond_Always);
4909 FocusWindow(g.MovingWindow);
4910 }
4911 else
4912 {
4913 g.MovingWindow = NULL;
4914 ClearActiveID();
4915 }
4916 }
4917 else
4918 {
4919 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4920 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4921 {
4922 KeepAliveID(g.ActiveId);
4923 if (!g.IO.MouseDown[0])
4924 ClearActiveID();
4925 }
4926 }
4927 }
4928
4929 // Initiate focusing and moving window when clicking on empty space or title bar.
4930 // Initiate focusing window when clicking on a disabled item.
4931 // Handle left-click and right-click focus.
4932 void ImGui::UpdateMouseMovingWindowEndFrame()
4933 {
4934 ImGuiContext& g = *GImGui;
4935 if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
4936 return;
4937
4938 // Unless we just made a window/popup appear
4939 if (g.NavWindow && g.NavWindow->Appearing)
4940 return;
4941
4942 // Click on empty space to focus window and start moving
4943 // (after we're done with all our widgets)
4944 if (g.IO.MouseClicked[0])
4945 {
4946 // Handle the edge case of a popup being closed while clicking in its empty space.
4947 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4948 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4949 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4950
4951 if (root_window != NULL && !is_closed_popup)
4952 {
4953 StartMouseMovingWindow(g.HoveredWindow); //-V595
4954
4955 // Cancel moving if clicked outside of title bar
4956 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4957 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
4958 if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4959 g.MovingWindow = NULL;
4960
4961 // Cancel moving if clicked over an item which was disabled or inhibited by popups
4962 // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)0 already)
4963 if (g.HoveredIdIsDisabled)
4964 g.MovingWindow = NULL;
4965 }
4966 else if (root_window == NULL && g.NavWindow != NULL)
4967 {
4968 // Clicking on void disable focus
4969 FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4970 }
4971 }
4972
4973 // With right mouse button we close popups without changing focus based on where the mouse is aimed
4974 // Instead, focus will be restored to the window under the bottom-most closed popup.
4975 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4976 if (g.IO.MouseClicked[1] && g.HoveredId == 0)
4977 {
4978 // Find the top-most window between HoveredWindow and the top-most Modal Window.
4979 // This is where we can trim the popup stack.
4980 ImGuiWindow* modal = GetTopMostPopupModal();
4981 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4982 ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4983 }
4984 }
4985
4986 static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4987 {
4988 return (window->Active) && (!window->Hidden);
4989 }
4990
4991 // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4992 void ImGui::UpdateHoveredWindowAndCaptureFlags()
4993 {
4994 ImGuiContext& g = *GImGui;
4995 ImGuiIO& io = g.IO;
4996
4997 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4998 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4999 g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
5000
5001 // Find the window hovered by mouse:
5002 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
5003 // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
5004 // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
5005 bool clear_hovered_windows = false;
5006 FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
5007 g.HoveredWindowBeforeClear = g.HoveredWindow;
5008
5009 // Modal windows prevents mouse from hovering behind them.
5010 ImGuiWindow* modal_window = GetTopMostPopupModal();
5011 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window))
5012 clear_hovered_windows = true;
5013
5014 // Disabled mouse hovering (we don't currently clear MousePos, we could)
5015 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
5016 clear_hovered_windows = true;
5017
5018 // We track click ownership. When clicked outside of a window the click is owned by the application and
5019 // won't report hovering nor request capture even while dragging over our windows afterward.
5020 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
5021 const bool has_open_modal = (modal_window != NULL);
5022 int mouse_earliest_down = -1;
5023 bool mouse_any_down = false;
5024 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
5025 {
5026 if (io.MouseClicked[i])
5027 {
5028 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
5029 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
5030 }
5031 mouse_any_down |= io.MouseDown[i];
5032 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
5033 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
5034 mouse_earliest_down = i;
5035 }
5036 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
5037 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
5038
5039 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
5040 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
5041 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
5042 if (!mouse_avail && !mouse_dragging_extern_payload)
5043 clear_hovered_windows = true;
5044
5045 if (clear_hovered_windows)
5046 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5047
5048 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
5049 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
5050 if (g.WantCaptureMouseNextFrame != -1)
5051 {
5052 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
5053 }
5054 else
5055 {
5056 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
5057 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
5058 }
5059
5060 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
5061 io.WantCaptureKeyboard = false;
5062 if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
5063 {
5064 if ((g.ActiveId != 0) || (modal_window != NULL))
5065 io.WantCaptureKeyboard = true;
5066 else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
5067 io.WantCaptureKeyboard = true;
5068 }
5069 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
5070 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
5071
5072 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
5073 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
5074 }
5075
5076 // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
5077 static void SetupDrawListSharedData()
5078 {
5079 ImGuiContext& g = *GImGui;
5080 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
5081 for (ImGuiViewportP* viewport : g.Viewports)
5082 virtual_space.Add(viewport->GetMainRect());
5083 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
5084 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
5085 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
5086 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
5087 if (g.Style.AntiAliasedLines)
5088 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
5089 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
5090 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
5091 if (g.Style.AntiAliasedFill)
5092 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
5093 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
5094 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
5095 }
5096
5097 void ImGui::NewFrame()
5098 {
5099 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5100 ImGuiContext& g = *GImGui;
5101
5102 // Remove pending delete hooks before frame start.
5103 // This deferred removal avoid issues of removal while iterating the hook vector
5104 for (int n = g.Hooks.Size - 1; n >= 0; n--)
5105 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
5106 g.Hooks.erase(&g.Hooks[n]);
5107
5108 CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
5109
5110 // Check and assert for various common IO and Configuration mistakes
5111 ErrorCheckNewFrameSanityChecks();
5112
5113 // Load settings on first frame, save settings when modified (after a delay)
5114 UpdateSettings();
5115
5116 g.Time += g.IO.DeltaTime;
5117 g.WithinFrameScope = true;
5118 g.FrameCount += 1;
5119 g.TooltipOverrideCount = 0;
5120 g.WindowsActiveCount = 0;
5121 g.MenusIdSubmittedThisFrame.resize(0);
5122
5123 // Calculate frame-rate for the user, as a purely luxurious feature
5124 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
5125 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
5126 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
5127 g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
5128 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
5129
5130 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
5131 g.InputEventsTrail.resize(0);
5132 UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
5133
5134 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
5135 UpdateViewportsNewFrame();
5136
5137 // Setup current font and draw list shared data
5138 g.IO.Fonts->Locked = true;
5139 SetupDrawListSharedData();
5140 SetCurrentFont(GetDefaultFont());
5141 IM_ASSERT(g.Font->IsLoaded());
5142
5143 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
5144 for (ImGuiViewportP* viewport : g.Viewports)
5145 viewport->DrawDataP.Valid = false;
5146
5147 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
5148 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
5149 KeepAliveID(g.DragDropPayload.SourceId);
5150
5151 // [DEBUG]
5152 if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
5153 g.DebugDrawIdConflicts = 0;
5154 if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
5155 g.DebugDrawIdConflicts = g.HoveredIdPreviousFrame;
5156
5157 // Update HoveredId data
5158 if (!g.HoveredIdPreviousFrame)
5159 g.HoveredIdTimer = 0.0f;
5160 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
5161 g.HoveredIdNotActiveTimer = 0.0f;
5162 if (g.HoveredId)
5163 g.HoveredIdTimer += g.IO.DeltaTime;
5164 if (g.HoveredId && g.ActiveId != g.HoveredId)
5165 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
5166 g.HoveredIdPreviousFrame = g.HoveredId;
5167 g.HoveredIdPreviousFrameItemCount = 0;
5168 g.HoveredId = 0;
5169 g.HoveredIdAllowOverlap = false;
5170 g.HoveredIdIsDisabled = false;
5171
5172 // Clear ActiveID if the item is not alive anymore.
5173 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
5174 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
5175 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
5176 {
5177 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
5178 ClearActiveID();
5179 }
5180
5181 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
5182 if (g.ActiveId)
5183 g.ActiveIdTimer += g.IO.DeltaTime;
5184 g.LastActiveIdTimer += g.IO.DeltaTime;
5185 g.ActiveIdPreviousFrame = g.ActiveId;
5186 g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
5187 g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
5188 g.ActiveIdIsAlive = 0;
5189 g.ActiveIdHasBeenEditedThisFrame = false;
5190 g.ActiveIdPreviousFrameIsAlive = false;
5191 g.ActiveIdIsJustActivated = false;
5192 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
5193 g.TempInputId = 0;
5194 if (g.ActiveId == 0)
5195 {
5196 g.ActiveIdUsingNavDirMask = 0x00;
5197 g.ActiveIdUsingAllKeyboardKeys = false;
5198 }
5199
5200 // Record when we have been stationary as this state is preserved while over same item.
5201 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5202 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5203 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5204 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5205 else if (g.HoverItemDelayId == 0)
5206 g.HoverItemUnlockedStationaryId = 0;
5207 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5208 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5209 else if (g.HoveredWindow == NULL)
5210 g.HoverWindowUnlockedStationaryId = 0;
5211
5212 // Update hover delay for IsItemHovered() with delays and tooltips
5213 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5214 if (g.HoverItemDelayId != 0)
5215 {
5216 g.HoverItemDelayTimer += g.IO.DeltaTime;
5217 g.HoverItemDelayClearTimer = 0.0f;
5218 g.HoverItemDelayId = 0;
5219 }
5220 else if (g.HoverItemDelayTimer > 0.0f)
5221 {
5222 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5223 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5224 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5225 if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5226 g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
5227 }
5228
5229 // Drag and drop
5230 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5231 g.DragDropAcceptIdCurr = 0;
5232 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5233 g.DragDropWithinSource = false;
5234 g.DragDropWithinTarget = false;
5235 g.DragDropHoldJustPressedId = 0;
5236 g.TooltipPreviousWindow = NULL;
5237
5238 // Close popups on focus lost (currently wip/opt-in)
5239 //if (g.IO.AppFocusLost)
5240 // ClosePopupsExceptModals();
5241
5242 // Update keyboard input state
5243 UpdateKeyboardInputs();
5244
5245 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5246 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5247 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5248 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5249
5250 // Update keyboard/gamepad navigation
5251 NavUpdate();
5252
5253 // Update mouse input state
5254 UpdateMouseInputs();
5255
5256 // Mark all windows as not visible and compact unused memory.
5257 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5258 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5259 for (ImGuiWindow* window : g.Windows)
5260 {
5261 window->WasActive = window->Active;
5262 window->Active = false;
5263 window->WriteAccessed = false;
5264 window->BeginCountPreviousFrame = window->BeginCount;
5265 window->BeginCount = 0;
5266
5267 // Garbage collect transient buffers of recently unused windows
5268 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5269 GcCompactTransientWindowBuffers(window);
5270 }
5271
5272 // Find hovered window
5273 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5274 // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
5275 UpdateHoveredWindowAndCaptureFlags();
5276
5277 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5278 UpdateMouseMovingWindowNewFrame();
5279
5280 // Background darkening/whitening
5281 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5282 g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5283 else
5284 g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5285
5286 g.MouseCursor = ImGuiMouseCursor_Arrow;
5287 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5288
5289 // Platform IME data: reset for the frame
5290 g.PlatformImeDataPrev = g.PlatformImeData;
5291 g.PlatformImeData.WantVisible = false;
5292
5293 // Mouse wheel scrolling, scale
5294 UpdateMouseWheel();
5295
5296 // Garbage collect transient buffers of recently unused tables
5297 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5298 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5299 TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5300 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5301 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5302 TableGcCompactTransientBuffers(&table_temp_data);
5303 if (g.GcCompactAll)
5304 GcCompactTransientMiscBuffers();
5305 g.GcCompactAll = false;
5306
5307 // Closing the focused window restore focus to the first active root window in descending z-order
5308 if (g.NavWindow && !g.NavWindow->WasActive)
5309 FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5310
5311 // No window should be open at the beginning of the frame.
5312 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5313 g.CurrentWindowStack.resize(0);
5314 g.BeginPopupStack.resize(0);
5315 g.ItemFlagsStack.resize(0);
5316 g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags
5317 g.CurrentItemFlags = g.ItemFlagsStack.back();
5318 g.GroupStack.resize(0);
5319
5320 // [DEBUG] Update debug features
5321 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5322 UpdateDebugToolItemPicker();
5323 UpdateDebugToolStackQueries();
5324 UpdateDebugToolFlashStyleColor();
5325 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5326 {
5327 g.DebugLocateId = 0;
5328 g.DebugBreakInLocateId = false;
5329 }
5330 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5331 {
5332 DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5333 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5334 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5335 }
5336 #endif
5337
5338 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5339 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5340 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5341 g.WithinFrameScopeWithImplicitWindow = true;
5342 SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5343 Begin("Debug##Default");
5344 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5345
5346 // Store stack sizes
5347 g.ErrorCountCurrentFrame = 0;
5348 ErrorRecoveryStoreState(&g.StackSizesInNewFrame);
5349
5350 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5351 // allowing to validate correct Begin/End behavior in user code.
5352 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5353 if (g.IO.ConfigDebugBeginReturnValueLoop)
5354 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5355 else
5356 g.DebugBeginReturnValueCullDepth = -1;
5357 #endif
5358
5359 CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5360 }
5361
5362 // FIXME: Add a more explicit sort order in the window structure.
5363 static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5364 {
5365 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5366 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5367 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5368 return d;
5369 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5370 return d;
5371 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5372 }
5373
5374 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5375 {
5376 out_sorted_windows->push_back(window);
5377 if (window->Active)
5378 {
5379 int count = window->DC.ChildWindows.Size;
5380 ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5381 for (int i = 0; i < count; i++)
5382 {
5383 ImGuiWindow* child = window->DC.ChildWindows[i];
5384 if (child->Active)
5385 AddWindowToSortBuffer(out_sorted_windows, child);
5386 }
5387 }
5388 }
5389
5390 static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5391 {
5392 ImGuiContext& g = *GImGui;
5393 ImGuiViewportP* viewport = g.Viewports[0];
5394 g.IO.MetricsRenderWindows++;
5395 if (window->DrawList->_Splitter._Count > 1)
5396 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5397 ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5398 for (ImGuiWindow* child : window->DC.ChildWindows)
5399 if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5400 AddWindowToDrawData(child, layer);
5401 }
5402
5403 static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5404 {
5405 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5406 }
5407
5408 // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5409 static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5410 {
5411 AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5412 }
5413
5414 static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5415 {
5416 int n = builder->Layers[0]->Size;
5417 int full_size = n;
5418 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5419 full_size += builder->Layers[i]->Size;
5420 builder->Layers[0]->resize(full_size);
5421 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5422 {
5423 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5424 if (layer->empty())
5425 continue;
5426 memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5427 n += layer->Size;
5428 layer->resize(0);
5429 }
5430 }
5431
5432 static void InitViewportDrawData(ImGuiViewportP* viewport)
5433 {
5434 ImGuiIO& io = ImGui::GetIO();
5435 ImDrawData* draw_data = &viewport->DrawDataP;
5436
5437 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5438 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5439 viewport->DrawDataBuilder.Layers[0]->resize(0);
5440 viewport->DrawDataBuilder.Layers[1]->resize(0);
5441
5442 draw_data->Valid = true;
5443 draw_data->CmdListsCount = 0;
5444 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5445 draw_data->DisplayPos = viewport->Pos;
5446 draw_data->DisplaySize = viewport->Size;
5447 draw_data->FramebufferScale = io.DisplayFramebufferScale;
5448 draw_data->OwnerViewport = viewport;
5449 }
5450
5451 // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5452 // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5453 // so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5454 // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5455 // some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5456 // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5457 // - This is analoguous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
5458 // which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
5459 void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5460 {
5461 ImGuiWindow* window = GetCurrentWindow();
5462 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5463 window->ClipRect = window->DrawList->_ClipRectStack.back();
5464 }
5465
5466 void ImGui::PopClipRect()
5467 {
5468 ImGuiWindow* window = GetCurrentWindow();
5469 window->DrawList->PopClipRect();
5470 window->ClipRect = window->DrawList->_ClipRectStack.back();
5471 }
5472
5473 static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5474 {
5475 if ((col & IM_COL32_A_MASK) == 0)
5476 return;
5477
5478 ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport();
5479 ImRect viewport_rect = viewport->GetMainRect();
5480
5481 // Draw behind window by moving the draw command at the FRONT of the draw list
5482 {
5483 // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5484 // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5485 // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5486 ImDrawList* draw_list = window->RootWindow->DrawList;
5487 if (draw_list->CmdBuffer.Size == 0)
5488 draw_list->AddDrawCmd();
5489 draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5490 draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5491 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5492 IM_ASSERT(cmd.ElemCount == 6);
5493 draw_list->CmdBuffer.pop_back();
5494 draw_list->CmdBuffer.push_front(cmd);
5495 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5496 draw_list->PopClipRect();
5497 }
5498 }
5499
5500 ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5501 {
5502 ImGuiContext& g = *GImGui;
5503 ImGuiWindow* bottom_most_visible_window = parent_window;
5504 for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5505 {
5506 ImGuiWindow* window = g.Windows[i];
5507 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5508 continue;
5509 if (!IsWindowWithinBeginStackOf(window, parent_window))
5510 break;
5511 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5512 bottom_most_visible_window = window;
5513 }
5514 return bottom_most_visible_window;
5515 }
5516
5517 static void ImGui::RenderDimmedBackgrounds()
5518 {
5519 ImGuiContext& g = *GImGui;
5520 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5521 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5522 return;
5523 const bool dim_bg_for_modal = (modal_window != NULL);
5524 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5525 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5526 return;
5527
5528 if (dim_bg_for_modal)
5529 {
5530 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5531 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5532 RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5533 }
5534 else if (dim_bg_for_window_list)
5535 {
5536 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5537 RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5538
5539 // Draw border around CTRL+Tab target window
5540 ImGuiWindow* window = g.NavWindowingTargetAnim;
5541 ImGuiViewport* viewport = GetMainViewport();
5542 float distance = g.FontSize;
5543 ImRect bb = window->Rect();
5544 bb.Expand(distance);
5545 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5546 bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5547 if (window->DrawList->CmdBuffer.Size == 0)
5548 window->DrawList->AddDrawCmd();
5549 window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5550 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5551 window->DrawList->PopClipRect();
5552 }
5553 }
5554
5555 // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5556 void ImGui::EndFrame()
5557 {
5558 ImGuiContext& g = *GImGui;
5559 IM_ASSERT(g.Initialized);
5560
5561 // Don't process EndFrame() multiple times.
5562 if (g.FrameCountEnded == g.FrameCount)
5563 return;
5564 IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5565
5566 CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5567
5568 // [EXPERIMENTAL] Recover from errors
5569 if (g.IO.ConfigErrorRecovery)
5570 ErrorRecoveryTryToRecoverState(&g.StackSizesInNewFrame);
5571 ErrorCheckEndFrameSanityChecks();
5572 ErrorCheckEndFrameFinalizeErrorTooltip();
5573
5574 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5575 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5576 if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5577 {
5578 IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5579 ImGuiViewport* viewport = GetMainViewport();
5580 g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
5581 }
5582
5583 // Hide implicit/fallback "Debug" window if it hasn't been used
5584 g.WithinFrameScopeWithImplicitWindow = false;
5585 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5586 g.CurrentWindow->Active = false;
5587 End();
5588
5589 // Update navigation: CTRL+Tab, wrap-around requests
5590 NavEndFrame();
5591
5592 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5593 if (g.DragDropActive)
5594 {
5595 bool is_delivered = g.DragDropPayload.Delivery;
5596 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
5597 if (is_delivered || is_elapsed)
5598 ClearDragDrop();
5599 }
5600
5601 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5602 // If you want to handle source item disappearing: instead of submitting your description tooltip
5603 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5604 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5605 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5606 if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5607 {
5608 g.DragDropWithinSource = true;
5609 SetTooltip("...");
5610 g.DragDropWithinSource = false;
5611 }
5612
5613 // End frame
5614 g.WithinFrameScope = false;
5615 g.FrameCountEnded = g.FrameCount;
5616
5617 // Initiate moving window + handle left-click and right-click focus
5618 UpdateMouseMovingWindowEndFrame();
5619
5620 // Sort the window list so that all child windows are after their parent
5621 // We cannot do that on FocusWindow() because children may not exist yet
5622 g.WindowsTempSortBuffer.resize(0);
5623 g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5624 for (ImGuiWindow* window : g.Windows)
5625 {
5626 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
5627 continue;
5628 AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5629 }
5630
5631 // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5632 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5633 g.Windows.swap(g.WindowsTempSortBuffer);
5634 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5635
5636 // Unlock font atlas
5637 g.IO.Fonts->Locked = false;
5638
5639 // Clear Input data for next frame
5640 g.IO.MousePosPrev = g.IO.MousePos;
5641 g.IO.AppFocusLost = false;
5642 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5643 g.IO.InputQueueCharacters.resize(0);
5644
5645 CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5646 }
5647
5648 // Prepare the data for rendering so you can call GetDrawData()
5649 // (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5650 // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5651 void ImGui::Render()
5652 {
5653 ImGuiContext& g = *GImGui;
5654 IM_ASSERT(g.Initialized);
5655
5656 if (g.FrameCountEnded != g.FrameCount)
5657 EndFrame();
5658 if (g.FrameCountRendered == g.FrameCount)
5659 return;
5660 g.FrameCountRendered = g.FrameCount;
5661
5662 g.IO.MetricsRenderWindows = 0;
5663 CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5664
5665 // Add background ImDrawList (for each active viewport)
5666 for (ImGuiViewportP* viewport : g.Viewports)
5667 {
5668 InitViewportDrawData(viewport);
5669 if (viewport->BgFgDrawLists[0] != NULL)
5670 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5671 }
5672
5673 // Draw modal/window whitening backgrounds
5674 RenderDimmedBackgrounds();
5675
5676 // Add ImDrawList to render
5677 ImGuiWindow* windows_to_render_top_most[2];
5678 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
5679 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5680 for (ImGuiWindow* window : g.Windows)
5681 {
5682 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5683 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5684 AddRootWindowToDrawData(window);
5685 }
5686 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5687 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5688 AddRootWindowToDrawData(windows_to_render_top_most[n]);
5689
5690 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5691 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5692 RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5693
5694 // Setup ImDrawData structures for end-user
5695 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5696 for (ImGuiViewportP* viewport : g.Viewports)
5697 {
5698 FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5699
5700 // Add foreground ImDrawList (for each active viewport)
5701 if (viewport->BgFgDrawLists[1] != NULL)
5702 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5703
5704 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5705 ImDrawData* draw_data = &viewport->DrawDataP;
5706 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5707 for (ImDrawList* draw_list : draw_data->CmdLists)
5708 draw_list->_PopUnusedDrawCmd();
5709
5710 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5711 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5712 }
5713
5714 CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5715 }
5716
5717 // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5718 // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5719 ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5720 {
5721 ImGuiContext& g = *GImGui;
5722
5723 const char* text_display_end;
5724 if (hide_text_after_double_hash)
5725 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
5726 else
5727 text_display_end = text_end;
5728
5729 ImFont* font = g.Font;
5730 const float font_size = g.FontSize;
5731 if (text == text_display_end)
5732 return ImVec2(0.0f, font_size);
5733 ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5734
5735 // Round
5736 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5737 // FIXME: Investigate using ceilf or e.g.
5738 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5739 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5740 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5741
5742 return text_size;
5743 }
5744
5745 // Find window given position, search front-to-back
5746 // - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5747 // - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5748 // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5749 // called, aka before the next Begin(). Moving window isn't affected.
5750 // - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5751 void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5752 {
5753 ImGuiContext& g = *GImGui;
5754 ImGuiWindow* hovered_window = NULL;
5755 ImGuiWindow* hovered_window_under_moving_window = NULL;
5756
5757 if (find_first_and_in_any_viewport == false && g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5758 hovered_window = g.MovingWindow;
5759
5760 ImVec2 padding_regular = g.Style.TouchExtraPadding;
5761 ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5762 for (int i = g.Windows.Size - 1; i >= 0; i--)
5763 {
5764 ImGuiWindow* window = g.Windows[i];
5765 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5766 if (!window->WasActive || window->Hidden)
5767 continue;
5768 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5769 continue;
5770
5771 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5772 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5773 if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
5774 continue;
5775
5776 // Support for one rectangular hole in any given window
5777 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5778 if (window->HitTestHoleSize.x != 0)
5779 {
5780 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5781 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5782 if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
5783 continue;
5784 }
5785
5786 if (find_first_and_in_any_viewport)
5787 {
5788 hovered_window = window;
5789 break;
5790 }
5791 else
5792 {
5793 if (hovered_window == NULL)
5794 hovered_window = window;
5795 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5796 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
5797 hovered_window_under_moving_window = window;
5798 if (hovered_window && hovered_window_under_moving_window)
5799 break;
5800 }
5801 }
5802
5803 *out_hovered_window = hovered_window;
5804 if (out_hovered_window_under_moving_window != NULL)
5805 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5806 }
5807
5808 bool ImGui::IsItemActive()
5809 {
5810 ImGuiContext& g = *GImGui;
5811 if (g.ActiveId)
5812 return g.ActiveId == g.LastItemData.ID;
5813 return false;
5814 }
5815
5816 bool ImGui::IsItemActivated()
5817 {
5818 ImGuiContext& g = *GImGui;
5819 if (g.ActiveId)
5820 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5821 return true;
5822 return false;
5823 }
5824
5825 bool ImGui::IsItemDeactivated()
5826 {
5827 ImGuiContext& g = *GImGui;
5828 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5829 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5830 return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5831 }
5832
5833 bool ImGui::IsItemDeactivatedAfterEdit()
5834 {
5835 ImGuiContext& g = *GImGui;
5836 return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5837 }
5838
5839 // == (GetItemID() == GetFocusID() && GetFocusID() != 0)
5840 bool ImGui::IsItemFocused()
5841 {
5842 ImGuiContext& g = *GImGui;
5843 return g.NavId == g.LastItemData.ID && g.NavId != 0;
5844 }
5845
5846 // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5847 // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5848 bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5849 {
5850 return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5851 }
5852
5853 bool ImGui::IsItemToggledOpen()
5854 {
5855 ImGuiContext& g = *GImGui;
5856 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5857 }
5858
5859 // Call after a Selectable() or TreeNode() involved in multi-selection.
5860 // Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
5861 // This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
5862 // (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
5863 // return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
5864 bool ImGui::IsItemToggledSelection()
5865 {
5866 ImGuiContext& g = *GImGui;
5867 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
5868 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5869 }
5870
5871 // IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5872 // you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5873 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5874 bool ImGui::IsAnyItemHovered()
5875 {
5876 ImGuiContext& g = *GImGui;
5877 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5878 }
5879
5880 bool ImGui::IsAnyItemActive()
5881 {
5882 ImGuiContext& g = *GImGui;
5883 return g.ActiveId != 0;
5884 }
5885
5886 bool ImGui::IsAnyItemFocused()
5887 {
5888 ImGuiContext& g = *GImGui;
5889 return g.NavId != 0 && g.NavCursorVisible;
5890 }
5891
5892 bool ImGui::IsItemVisible()
5893 {
5894 ImGuiContext& g = *GImGui;
5895 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5896 }
5897
5898 bool ImGui::IsItemEdited()
5899 {
5900 ImGuiContext& g = *GImGui;
5901 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5902 }
5903
5904 // Allow next item to be overlapped by subsequent items.
5905 // This works by requiring HoveredId to match for two subsequent frames,
5906 // so if a following items overwrite it our interactions will naturally be disabled.
5907 void ImGui::SetNextItemAllowOverlap()
5908 {
5909 ImGuiContext& g = *GImGui;
5910 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5911 }
5912
5913 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5914 // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5915 // FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5916 void ImGui::SetItemAllowOverlap()
5917 {
5918 ImGuiContext& g = *GImGui;
5919 ImGuiID id = g.LastItemData.ID;
5920 if (g.HoveredId == id)
5921 g.HoveredIdAllowOverlap = true;
5922 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5923 g.ActiveIdAllowOverlap = true;
5924 }
5925 #endif
5926
5927 // This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
5928 // FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
5929 void ImGui::SetActiveIdUsingAllKeyboardKeys()
5930 {
5931 ImGuiContext& g = *GImGui;
5932 IM_ASSERT(g.ActiveId != 0);
5933 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5934 g.ActiveIdUsingAllKeyboardKeys = true;
5935 NavMoveRequestCancel();
5936 }
5937
5938 ImGuiID ImGui::GetItemID()
5939 {
5940 ImGuiContext& g = *GImGui;
5941 return g.LastItemData.ID;
5942 }
5943
5944 ImVec2 ImGui::GetItemRectMin()
5945 {
5946 ImGuiContext& g = *GImGui;
5947 return g.LastItemData.Rect.Min;
5948 }
5949
5950 ImVec2 ImGui::GetItemRectMax()
5951 {
5952 ImGuiContext& g = *GImGui;
5953 return g.LastItemData.Rect.Max;
5954 }
5955
5956 ImVec2 ImGui::GetItemRectSize()
5957 {
5958 ImGuiContext& g = *GImGui;
5959 return g.LastItemData.Rect.GetSize();
5960 }
5961
5962 // Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5963 // ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5964 bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5965 {
5966 ImGuiID id = GetCurrentWindow()->GetID(str_id);
5967 return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5968 }
5969
5970 bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5971 {
5972 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5973 }
5974
5975 bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5976 {
5977 ImGuiContext& g = *GImGui;
5978 ImGuiWindow* parent_window = g.CurrentWindow;
5979 IM_ASSERT(id != 0);
5980
5981 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5982 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5983 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5984 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5985 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5986 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5987 {
5988 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5989 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5990 }
5991 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5992 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5993 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5994 if (window_flags & ImGuiWindowFlags_NavFlattened)
5995 child_flags |= ImGuiChildFlags_NavFlattened;
5996 #endif
5997 if (child_flags & ImGuiChildFlags_AutoResizeX)
5998 child_flags &= ~ImGuiChildFlags_ResizeX;
5999 if (child_flags & ImGuiChildFlags_AutoResizeY)
6000 child_flags &= ~ImGuiChildFlags_ResizeY;
6001
6002 // Set window flags
6003 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar;
6004 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
6005 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
6006 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
6007 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
6008 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
6009
6010 // Special framed style
6011 if (child_flags & ImGuiChildFlags_FrameStyle)
6012 {
6013 PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
6014 PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
6015 PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
6016 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
6017 child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding;
6018 window_flags |= ImGuiWindowFlags_NoMove;
6019 }
6020
6021 // Forward size
6022 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
6023 // (the alternative would to store conditional flags per axis, which is possible but more code)
6024 const ImVec2 size_avail = GetContentRegionAvail();
6025 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
6026 ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
6027
6028 // A SetNextWindowSize() call always has priority (#8020)
6029 // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
6030 // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
6031 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
6032 {
6033 if (g.NextWindowData.SizeVal.x > 0.0f)
6034 {
6035 size.x = g.NextWindowData.SizeVal.x;
6036 child_flags &= ~ImGuiChildFlags_ResizeX;
6037 }
6038 if (g.NextWindowData.SizeVal.y > 0.0f)
6039 {
6040 size.y = g.NextWindowData.SizeVal.y;
6041 child_flags &= ~ImGuiChildFlags_ResizeY;
6042 }
6043 }
6044 SetNextWindowSize(size);
6045
6046 // Forward child flags
6047 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
6048 g.NextWindowData.ChildFlags = child_flags;
6049
6050 // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
6051 // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
6052 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
6053 const char* temp_window_name;
6054 /*if (name && parent_window->IDStack.back() == parent_window->ID)
6055 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
6056 else*/
6057 if (name)
6058 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
6059 else
6060 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
6061
6062 // Set style
6063 const float backup_border_size = g.Style.ChildBorderSize;
6064 if ((child_flags & ImGuiChildFlags_Borders) == 0)
6065 g.Style.ChildBorderSize = 0.0f;
6066
6067 // Begin into window
6068 const bool ret = Begin(temp_window_name, NULL, window_flags);
6069
6070 // Restore style
6071 g.Style.ChildBorderSize = backup_border_size;
6072 if (child_flags & ImGuiChildFlags_FrameStyle)
6073 {
6074 PopStyleVar(3);
6075 PopStyleColor();
6076 }
6077
6078 ImGuiWindow* child_window = g.CurrentWindow;
6079 child_window->ChildId = id;
6080
6081 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
6082 // While this is not really documented/defined, it seems that the expected thing to do.
6083 if (child_window->BeginCount == 1)
6084 parent_window->DC.CursorPos = child_window->Pos;
6085
6086 // Process navigation-in immediately so NavInit can run on first frame
6087 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
6088 const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
6089 if (g.ActiveId == temp_id_for_activation)
6090 ClearActiveID();
6091 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
6092 {
6093 FocusWindow(child_window);
6094 NavInitWindow(child_window, false);
6095 SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
6096 g.ActiveIdSource = g.NavInputSource;
6097 }
6098 return ret;
6099 }
6100
6101 void ImGui::EndChild()
6102 {
6103 ImGuiContext& g = *GImGui;
6104 ImGuiWindow* child_window = g.CurrentWindow;
6105
6106 IM_ASSERT(g.WithinEndChild == false);
6107 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
6108
6109 g.WithinEndChild = true;
6110 ImVec2 child_size = child_window->Size;
6111 End();
6112 if (child_window->BeginCount == 1)
6113 {
6114 ImGuiWindow* parent_window = g.CurrentWindow;
6115 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
6116 ItemSize(child_size);
6117 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
6118 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
6119 {
6120 ItemAdd(bb, child_window->ChildId);
6121 RenderNavCursor(bb, child_window->ChildId);
6122
6123 // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
6124 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
6125 RenderNavCursor(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavRenderCursorFlags_Compact);
6126 }
6127 else
6128 {
6129 // Not navigable into
6130 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
6131 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
6132 ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
6133
6134 // But when flattened we directly reach items, adjust active layer mask accordingly
6135 if (nav_flattened)
6136 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6137 }
6138 if (g.HoveredWindow == child_window)
6139 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6140 }
6141 g.WithinEndChild = false;
6142 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6143 }
6144
6145 static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6146 {
6147 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
6148 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
6149 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6150 }
6151
6152 ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6153 {
6154 ImGuiContext& g = *GImGui;
6155 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6156 }
6157
6158 ImGuiWindow* ImGui::FindWindowByName(const char* name)
6159 {
6160 ImGuiID id = ImHashStr(name);
6161 return FindWindowByID(id);
6162 }
6163
6164 static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6165 {
6166 window->Pos = ImTrunc(ImVec2(settings->Pos.x, settings->Pos.y));
6167 if (settings->Size.x > 0 && settings->Size.y > 0)
6168 window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6169 window->Collapsed = settings->Collapsed;
6170 }
6171
6172 static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
6173 {
6174 ImGuiContext& g = *GImGui;
6175
6176 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
6177 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
6178 if ((just_created || child_flag_changed) && !new_is_explicit_child)
6179 {
6180 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
6181 g.WindowsFocusOrder.push_back(window);
6182 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
6183 }
6184 else if (!just_created && child_flag_changed && new_is_explicit_child)
6185 {
6186 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
6187 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
6188 g.WindowsFocusOrder[n]->FocusOrder--;
6189 g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
6190 window->FocusOrder = -1;
6191 }
6192 window->IsExplicitChild = new_is_explicit_child;
6193 }
6194
6195 static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6196 {
6197 // Initial window state with e.g. default/arbitrary window position
6198 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6199 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6200 window->Pos = main_viewport->Pos + ImVec2(60, 60);
6201 window->Size = window->SizeFull = ImVec2(0, 0);
6202 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6203
6204 if (settings != NULL)
6205 {
6206 SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6207 ApplyWindowSettings(window, settings);
6208 }
6209 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6210
6211 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6212 {
6213 window->AutoFitFramesX = window->AutoFitFramesY = 2;
6214 window->AutoFitOnlyGrows = false;
6215 }
6216 else
6217 {
6218 if (window->Size.x <= 0.0f)
6219 window->AutoFitFramesX = 2;
6220 if (window->Size.y <= 0.0f)
6221 window->AutoFitFramesY = 2;
6222 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6223 }
6224 }
6225
6226 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6227 {
6228 // Create window the first time
6229 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6230 ImGuiContext& g = *GImGui;
6231 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6232 window->Flags = flags;
6233 g.WindowsById.SetVoidPtr(window->ID, window);
6234
6235 ImGuiWindowSettings* settings = NULL;
6236 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6237 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6238 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6239
6240 InitOrLoadWindowSettings(window, settings);
6241
6242 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6243 g.Windows.push_front(window); // Quite slow but rare and only once
6244 else
6245 g.Windows.push_back(window);
6246
6247 return window;
6248 }
6249
6250 static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6251 {
6252 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6253 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6254 // Perhaps should tend further a neater test for this.
6255 ImGuiContext& g = *GImGui;
6256 ImVec2 size_min;
6257 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6258 {
6259 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6260 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6261 }
6262 else
6263 {
6264 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6265 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6266 }
6267
6268 // Reduce artifacts with very small windows
6269 ImGuiWindow* window_for_height = window;
6270 size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6271 return size_min;
6272 }
6273
6274 static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6275 {
6276 ImGuiContext& g = *GImGui;
6277 ImVec2 new_size = size_desired;
6278 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6279 {
6280 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6281 ImRect cr = g.NextWindowData.SizeConstraintRect;
6282 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6283 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6284 if (g.NextWindowData.SizeCallback)
6285 {
6286 ImGuiSizeCallbackData data;
6287 data.UserData = g.NextWindowData.SizeCallbackUserData;
6288 data.Pos = window->Pos;
6289 data.CurrentSize = window->SizeFull;
6290 data.DesiredSize = new_size;
6291 g.NextWindowData.SizeCallback(&data);
6292 new_size = data.DesiredSize;
6293 }
6294 new_size.x = IM_TRUNC(new_size.x);
6295 new_size.y = IM_TRUNC(new_size.y);
6296 }
6297
6298 // Minimum size
6299 ImVec2 size_min = CalcWindowMinSize(window);
6300 return ImMax(new_size, size_min);
6301 }
6302
6303 static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6304 {
6305 bool preserve_old_content_sizes = false;
6306 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6307 preserve_old_content_sizes = true;
6308 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6309 preserve_old_content_sizes = true;
6310 if (preserve_old_content_sizes)
6311 {
6312 *content_size_current = window->ContentSize;
6313 *content_size_ideal = window->ContentSizeIdeal;
6314 return;
6315 }
6316
6317 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6318 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6319 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6320 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6321 }
6322
6323 static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6324 {
6325 ImGuiContext& g = *GImGui;
6326 ImGuiStyle& style = g.Style;
6327 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6328 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6329 ImVec2 size_pad = window->WindowPadding * 2.0f;
6330 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6331 if (window->Flags & ImGuiWindowFlags_Tooltip)
6332 {
6333 // Tooltip always resize
6334 return size_desired;
6335 }
6336 else
6337 {
6338 // Maximum window size is determined by the viewport size or monitor size
6339 ImVec2 size_min = CalcWindowMinSize(window);
6340 ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6341 ImVec2 size_auto_fit = ImClamp(size_desired, size_min, size_max);
6342
6343 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6344 // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6345 // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6346 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
6347 size_auto_fit.y = window->SizeFull.y;
6348 else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
6349 size_auto_fit.x = window->SizeFull.x;
6350
6351 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6352 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6353 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6354 bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6355 bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6356 if (will_have_scrollbar_x)
6357 size_auto_fit.y += style.ScrollbarSize;
6358 if (will_have_scrollbar_y)
6359 size_auto_fit.x += style.ScrollbarSize;
6360 return size_auto_fit;
6361 }
6362 }
6363
6364 ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6365 {
6366 ImVec2 size_contents_current;
6367 ImVec2 size_contents_ideal;
6368 CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6369 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6370 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6371 return size_final;
6372 }
6373
6374 static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6375 {
6376 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6377 return ImGuiCol_PopupBg;
6378 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6379 return ImGuiCol_ChildBg;
6380 return ImGuiCol_WindowBg;
6381 }
6382
6383 static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6384 {
6385 ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
6386 ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6387 ImVec2 size_expected = pos_max - pos_min;
6388 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6389 *out_pos = pos_min;
6390 if (corner_norm.x == 0.0f)
6391 out_pos->x -= (size_constrained.x - size_expected.x);
6392 if (corner_norm.y == 0.0f)
6393 out_pos->y -= (size_constrained.y - size_expected.y);
6394 *out_size = size_constrained;
6395 }
6396
6397 // Data for resizing from resize grip / corner
6398 struct ImGuiResizeGripDef
6399 {
6400 ImVec2 CornerPosN;
6401 ImVec2 InnerDir;
6402 int AngleMin12, AngleMax12;
6403 };
6404 static const ImGuiResizeGripDef resize_grip_def[4] =
6405 {
6406 { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
6407 { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
6408 { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
6409 { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
6410 };
6411
6412 // Data for resizing from borders
6413 struct ImGuiResizeBorderDef
6414 {
6415 ImVec2 InnerDir; // Normal toward inside
6416 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6417 float OuterAngle; // Angle toward outside
6418 };
6419 static const ImGuiResizeBorderDef resize_border_def[4] =
6420 {
6421 { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6422 { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6423 { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6424 { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
6425 };
6426
6427 static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6428 {
6429 ImRect rect = window->Rect();
6430 if (thickness == 0.0f)
6431 rect.Max -= ImVec2(1, 1);
6432 if (border_n == ImGuiDir_Left) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); }
6433 if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); }
6434 if (border_n == ImGuiDir_Up) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); }
6435 if (border_n == ImGuiDir_Down) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); }
6436 IM_ASSERT(0);
6437 return ImRect();
6438 }
6439
6440 // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6441 ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6442 {
6443 IM_ASSERT(n >= 0 && n < 4);
6444 ImGuiID id = window->ID;
6445 id = ImHashStr("#RESIZE", 0, id);
6446 id = ImHashData(&n, sizeof(int), id);
6447 return id;
6448 }
6449
6450 // Borders (Left, Right, Up, Down)
6451 ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6452 {
6453 IM_ASSERT(dir >= 0 && dir < 4);
6454 int n = (int)dir + 4;
6455 ImGuiID id = window->ID;
6456 id = ImHashStr("#RESIZE", 0, id);
6457 id = ImHashData(&n, sizeof(int), id);
6458 return id;
6459 }
6460
6461 // Handle resize for: Resize Grips, Borders, Gamepad
6462 // Return true when using auto-fit (double-click on resize grip)
6463 static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6464 {
6465 ImGuiContext& g = *GImGui;
6466 ImGuiWindowFlags flags = window->Flags;
6467
6468 if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6469 return false;
6470 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6471 return false;
6472
6473 int ret_auto_fit_mask = 0x00;
6474 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6475 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6476 const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6477
6478 ImRect clamp_rect = visibility_rect;
6479 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6480 if (window_move_from_title_bar)
6481 clamp_rect.Min.y -= window->TitleBarHeight;
6482
6483 ImVec2 pos_target(FLT_MAX, FLT_MAX);
6484 ImVec2 size_target(FLT_MAX, FLT_MAX);
6485
6486 // Resize grips and borders are on layer 1
6487 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6488
6489 // Manual resize grips
6490 PushID("#RESIZE");
6491 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6492 {
6493 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6494 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6495
6496 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6497 bool hovered, held;
6498 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6499 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6500 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6501 ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6502 ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6503 ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6504 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6505 if (hovered || held)
6506 SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
6507
6508 if (held && g.IO.MouseDoubleClicked[0])
6509 {
6510 // Auto-fit when double-clicking
6511 size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6512 ret_auto_fit_mask = 0x03; // Both axises
6513 ClearActiveID();
6514 }
6515 else if (held)
6516 {
6517 // Resize from any of the four corners
6518 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6519 ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6520 ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6521 ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6522 corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6523 CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6524 }
6525
6526 // Only lower-left grip is visible before hovering/activating
6527 if (resize_grip_n == 0 || held || hovered)
6528 resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6529 }
6530
6531 int resize_border_mask = 0x00;
6532 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6533 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6534 else
6535 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6536 for (int border_n = 0; border_n < 4; border_n++)
6537 {
6538 if ((resize_border_mask & (1 << border_n)) == 0)
6539 continue;
6540 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6541 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6542
6543 bool hovered, held;
6544 ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6545 ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6546 ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6547 ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6548 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6549 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6550 hovered = false;
6551 if (hovered || held)
6552 SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
6553 if (held && g.IO.MouseDoubleClicked[0])
6554 {
6555 // Double-clicking bottom or right border auto-fit on this axis
6556 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6557 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6558 if (border_n == 1 || border_n == 3) // Right and bottom border
6559 {
6560 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6561 ret_auto_fit_mask |= (1 << axis);
6562 hovered = held = false; // So border doesn't show highlighted at new position
6563 }
6564 ClearActiveID();
6565 }
6566 else if (held)
6567 {
6568 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6569 // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6570 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6571 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false));
6572 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6573 {
6574 g.WindowResizeBorderExpectedRect = border_rect;
6575 g.WindowResizeRelativeMode = false;
6576 }
6577 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6578 g.WindowResizeRelativeMode = true;
6579
6580 const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6581 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6582 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6583
6584 // Use absolute mode position
6585 ImVec2 border_target = window->Pos;
6586 border_target[axis] = border_target_abs_mode_for_axis;
6587
6588 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6589 bool ignore_resize = false;
6590 if (g.WindowResizeRelativeMode)
6591 {
6592 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6593 border_target[axis] = border_target_rel_mode_for_axis;
6594 if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6595 ignore_resize = true;
6596 }
6597
6598 // Clamp, apply
6599 ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6600 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6601 border_target = ImClamp(border_target, clamp_min, clamp_max);
6602 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6603 {
6604 ImGuiWindow* parent_window = window->ParentWindow;
6605 ImGuiWindowFlags parent_flags = parent_window->Flags;
6606 ImRect border_limit_rect = parent_window->InnerRect;
6607 border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6608 if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6609 border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6610 if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6611 border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6612 }
6613 if (!ignore_resize)
6614 CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6615 }
6616 if (hovered)
6617 *border_hovered = border_n;
6618 if (held)
6619 *border_held = border_n;
6620 }
6621 PopID();
6622
6623 // Restore nav layer
6624 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6625
6626 // Navigation resize (keyboard/gamepad)
6627 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6628 // Not even sure the callback works here.
6629 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
6630 {
6631 ImVec2 nav_resize_dir;
6632 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6633 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6634 if (g.NavInputSource == ImGuiInputSource_Gamepad)
6635 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6636 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6637 {
6638 const float NAV_RESIZE_SPEED = 600.0f;
6639 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6640 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6641 g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6642 g.NavWindowingToggleLayer = false;
6643 g.NavHighlightItemUnderNav = true;
6644 resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6645 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6646 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6647 {
6648 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6649 size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6650 g.NavWindowingAccumDeltaSize -= accum_floored;
6651 }
6652 }
6653 }
6654
6655 // Apply back modified position/size to window
6656 const ImVec2 curr_pos = window->Pos;
6657 const ImVec2 curr_size = window->SizeFull;
6658 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6659 window->Size.x = window->SizeFull.x = size_target.x;
6660 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6661 window->Size.y = window->SizeFull.y = size_target.y;
6662 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6663 window->Pos.x = ImTrunc(pos_target.x);
6664 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6665 window->Pos.y = ImTrunc(pos_target.y);
6666 if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6667 MarkIniSettingsDirty(window);
6668
6669 // Recalculate next expected border expected coordinates
6670 if (*border_held != -1)
6671 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6672
6673 return ret_auto_fit_mask;
6674 }
6675
6676 static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6677 {
6678 ImGuiContext& g = *GImGui;
6679 ImVec2 size_for_clamping = window->Size;
6680 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6681 size_for_clamping.y = window->TitleBarHeight;
6682 window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6683 }
6684
6685 static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6686 {
6687 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6688 const float rounding = window->WindowRounding;
6689 const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6690 window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6691 window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6692 window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6693 }
6694
6695 static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6696 {
6697 ImGuiContext& g = *GImGui;
6698 const float border_size = window->WindowBorderSize;
6699 const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6700 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6701 window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6702 else if (border_size > 0.0f)
6703 {
6704 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6705 RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6706 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6707 RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6708 }
6709 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6710 {
6711 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6712 const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6713 RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6714 }
6715 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6716 {
6717 float y = window->Pos.y + window->TitleBarHeight - 1;
6718 window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6719 }
6720 }
6721
6722 // Draw background and borders
6723 // Draw and handle scrollbars
6724 void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6725 {
6726 ImGuiContext& g = *GImGui;
6727 ImGuiStyle& style = g.Style;
6728 ImGuiWindowFlags flags = window->Flags;
6729
6730 // Ensure that ScrollBar doesn't read last frame's SkipItems
6731 IM_ASSERT(window->BeginCount == 0);
6732 window->SkipItems = false;
6733
6734 // Draw window + handle manual resize
6735 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6736 const float window_rounding = window->WindowRounding;
6737 const float window_border_size = window->WindowBorderSize;
6738 if (window->Collapsed)
6739 {
6740 // Title bar only
6741 const float backup_border_size = style.FrameBorderSize;
6742 g.Style.FrameBorderSize = window->WindowBorderSize;
6743 ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6744 RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6745 g.Style.FrameBorderSize = backup_border_size;
6746 }
6747 else
6748 {
6749 // Window background
6750 if (!(flags & ImGuiWindowFlags_NoBackground))
6751 {
6752 ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6753 bool override_alpha = false;
6754 float alpha = 1.0f;
6755 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6756 {
6757 alpha = g.NextWindowData.BgAlphaVal;
6758 override_alpha = true;
6759 }
6760 if (override_alpha)
6761 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6762 window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6763 }
6764
6765 // Title bar
6766 if (!(flags & ImGuiWindowFlags_NoTitleBar))
6767 {
6768 ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6769 window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6770 }
6771
6772 // Menu bar
6773 if (flags & ImGuiWindowFlags_MenuBar)
6774 {
6775 ImRect menu_bar_rect = window->MenuBarRect();
6776 menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6777 window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6778 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6779 window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6780 }
6781
6782 // Scrollbars
6783 if (window->ScrollbarX)
6784 Scrollbar(ImGuiAxis_X);
6785 if (window->ScrollbarY)
6786 Scrollbar(ImGuiAxis_Y);
6787
6788 // Render resize grips (after their input handling so we don't have a frame of latency)
6789 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6790 {
6791 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6792 {
6793 const ImU32 col = resize_grip_col[resize_grip_n];
6794 if ((col & IM_COL32_A_MASK) == 0)
6795 continue;
6796 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6797 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6798 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6799 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6800 window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6801 window->DrawList->PathFillConvex(col);
6802 }
6803 }
6804
6805 // Borders
6806 if (handle_borders_and_resize_grips)
6807 RenderWindowOuterBorders(window);
6808 }
6809 }
6810
6811 // Render title text, collapse button, close button
6812 void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6813 {
6814 ImGuiContext& g = *GImGui;
6815 ImGuiStyle& style = g.Style;
6816 ImGuiWindowFlags flags = window->Flags;
6817
6818 const bool has_close_button = (p_open != NULL);
6819 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6820
6821 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6822 // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6823 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6824 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6825 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6826
6827 // Layout buttons
6828 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6829 float pad_l = style.FramePadding.x;
6830 float pad_r = style.FramePadding.x;
6831 float button_sz = g.FontSize;
6832 ImVec2 close_button_pos;
6833 ImVec2 collapse_button_pos;
6834 if (has_close_button)
6835 {
6836 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6837 pad_r += button_sz + style.ItemInnerSpacing.x;
6838 }
6839 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6840 {
6841 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6842 pad_r += button_sz + style.ItemInnerSpacing.x;
6843 }
6844 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6845 {
6846 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6847 pad_l += button_sz + style.ItemInnerSpacing.x;
6848 }
6849
6850 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6851 if (has_collapse_button)
6852 if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
6853 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6854
6855 // Close button
6856 if (has_close_button)
6857 if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6858 *p_open = false;
6859
6860 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6861 g.CurrentItemFlags = item_flags_backup;
6862
6863 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6864 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6865 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6866 const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6867
6868 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6869 // while uncentered title text will still reach edges correctly.
6870 if (pad_l > style.FramePadding.x)
6871 pad_l += g.Style.ItemInnerSpacing.x;
6872 if (pad_r > style.FramePadding.x)
6873 pad_r += g.Style.ItemInnerSpacing.x;
6874 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6875 {
6876 float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6877 float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6878 pad_l = ImMax(pad_l, pad_extend * centerness);
6879 pad_r = ImMax(pad_r, pad_extend * centerness);
6880 }
6881
6882 ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6883 ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6884 if (flags & ImGuiWindowFlags_UnsavedDocument)
6885 {
6886 ImVec2 marker_pos;
6887 marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6888 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6889 if (marker_pos.x > layout_r.Min.x)
6890 {
6891 RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6892 clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6893 }
6894 }
6895 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6896 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6897 RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6898 }
6899
6900 void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6901 {
6902 window->ParentWindow = parent_window;
6903 window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6904 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6905 window->RootWindow = parent_window->RootWindow;
6906 if (parent_window && (flags & ImGuiWindowFlags_Popup))
6907 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6908 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
6909 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6910 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6911 {
6912 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6913 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6914 }
6915 }
6916
6917 // [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6918 // This is designed as a toy/test-bed for
6919 void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6920 {
6921 ImGuiContext& g = *GImGui;
6922 window->SkipRefresh = false;
6923 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6924 return;
6925 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6926 {
6927 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6928 if (window->Appearing) // If currently appearing
6929 return;
6930 if (window->Hidden) // If was hidden (previous frame)
6931 return;
6932 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow)
6933 if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, window))
6934 return;
6935 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow)
6936 if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(g.NavWindow->RootWindow, window))
6937 return;
6938 window->DrawList = NULL;
6939 window->SkipRefresh = true;
6940 }
6941 }
6942
6943 static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
6944 {
6945 window->Active = true;
6946 for (ImGuiWindow* child : window->DC.ChildWindows)
6947 if (!child->Hidden)
6948 {
6949 child->Active = child->SkipRefresh = true;
6950 SetWindowActiveForSkipRefresh(child);
6951 }
6952 }
6953
6954 // When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6955 // should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6956 // In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6957 // - WindowA // FindBlockingModal() returns Modal1
6958 // - WindowB // .. returns Modal1
6959 // - Modal1 // .. returns Modal2
6960 // - WindowC // .. returns Modal2
6961 // - WindowD // .. returns Modal2
6962 // - Modal2 // .. returns Modal2
6963 // - WindowE // .. returns NULL
6964 // Notes:
6965 // - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6966 // Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6967 ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6968 {
6969 ImGuiContext& g = *GImGui;
6970 if (g.OpenPopupStack.Size <= 0)
6971 return NULL;
6972
6973 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6974 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6975 {
6976 ImGuiWindow* popup_window = popup_data.Window;
6977 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6978 continue;
6979 if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6980 continue;
6981 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6982 return popup_window;
6983 if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
6984 continue;
6985 return popup_window; // Place window right below first block modal
6986 }
6987 return NULL;
6988 }
6989
6990 // Push a new Dear ImGui window to add widgets to.
6991 // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6992 // - Begin/End can be called multiple times during the frame with the same window name to append content.
6993 // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6994 // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6995 // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6996 // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6997 bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6998 {
6999 ImGuiContext& g = *GImGui;
7000 const ImGuiStyle& style = g.Style;
7001 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
7002 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
7003 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
7004
7005 // Find or create
7006 ImGuiWindow* window = FindWindowByName(name);
7007 const bool window_just_created = (window == NULL);
7008 if (window_just_created)
7009 window = CreateNewWindow(name, flags);
7010
7011 // [DEBUG] Debug break requested by user
7012 if (g.DebugBreakInWindow == window->ID)
7013 IM_DEBUG_BREAK();
7014
7015 // Automatically disable manual moving/resizing when NoInputs is set
7016 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
7017 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
7018
7019 const int current_frame = g.FrameCount;
7020 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
7021 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
7022
7023 // Update the Appearing flag
7024 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
7025 if (flags & ImGuiWindowFlags_Popup)
7026 {
7027 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7028 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
7029 window_just_activated_by_user |= (window != popup_ref.Window);
7030 }
7031 window->Appearing = window_just_activated_by_user;
7032 if (window->Appearing)
7033 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7034
7035 // Update Flags, LastFrameActive, BeginOrderXXX fields
7036 if (first_begin_of_the_frame)
7037 {
7038 UpdateWindowInFocusOrderList(window, window_just_created, flags);
7039 window->Flags = (ImGuiWindowFlags)flags;
7040 window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7041 window->LastFrameActive = current_frame;
7042 window->LastTimeActive = (float)g.Time;
7043 window->BeginOrderWithinParent = 0;
7044 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7045 }
7046 else
7047 {
7048 flags = window->Flags;
7049 }
7050
7051 // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
7052 ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7053 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7054 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7055
7056 // We allow window memory to be compacted so recreate the base stack when needed.
7057 if (window->IDStack.Size == 0)
7058 window->IDStack.push_back(window->ID);
7059
7060 // Add to stack
7061 g.CurrentWindow = window;
7062 g.CurrentWindowStack.resize(g.CurrentWindowStack.Size + 1);
7063 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7064 window_stack_data.Window = window;
7065 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7066 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7067 ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin);
7068 g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
7069 if (flags & ImGuiWindowFlags_ChildMenu)
7070 g.BeginMenuDepth++;
7071
7072 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7073 if (first_begin_of_the_frame)
7074 {
7075 UpdateWindowParentAndRootLinks(window, flags, parent_window);
7076 window->ParentWindowInBeginStack = parent_window_in_stack;
7077
7078 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7079 // e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7080 window->ParentWindowForFocusRoute = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window_in_stack : NULL;
7081 }
7082
7083 // Add to focus scope stack
7084 PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7085 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7086
7087 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7088 if (flags & ImGuiWindowFlags_Popup)
7089 {
7090 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7091 popup_ref.Window = window;
7092 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7093 g.BeginPopupStack.push_back(popup_ref);
7094 window->PopupId = popup_ref.PopupId;
7095 }
7096
7097 // Process SetNextWindow***() calls
7098 // (FIXME: Consider splitting the HasXXX flags into X/Y components
7099 bool window_pos_set_by_api = false;
7100 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7101 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
7102 {
7103 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7104 if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7105 {
7106 // May be processed on the next frame if this is our first frame and we are measuring size
7107 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7108 window->SetWindowPosVal = g.NextWindowData.PosVal;
7109 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7110 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7111 }
7112 else
7113 {
7114 SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7115 }
7116 }
7117 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
7118 {
7119 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7120 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7121 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7122 g.NextWindowData.SizeVal.x = window->SizeFull.x;
7123 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7124 g.NextWindowData.SizeVal.y = window->SizeFull.y;
7125 SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7126 }
7127 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
7128 {
7129 if (g.NextWindowData.ScrollVal.x >= 0.0f)
7130 {
7131 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7132 window->ScrollTargetCenterRatio.x = 0.0f;
7133 }
7134 if (g.NextWindowData.ScrollVal.y >= 0.0f)
7135 {
7136 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7137 window->ScrollTargetCenterRatio.y = 0.0f;
7138 }
7139 }
7140 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
7141 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7142 else if (first_begin_of_the_frame)
7143 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7144 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
7145 SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7146 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
7147 FocusWindow(window);
7148 if (window->Appearing)
7149 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7150
7151 // [EXPERIMENTAL] Skip Refresh mode
7152 UpdateWindowSkipRefresh(window);
7153
7154 // Nested root windows (typically tooltips) override disabled state
7155 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7156 BeginDisabledOverrideReenable();
7157
7158 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7159 g.CurrentWindow = NULL;
7160
7161 // When reusing window again multiple times a frame, just append content (don't need to setup again)
7162 if (first_begin_of_the_frame && !window->SkipRefresh)
7163 {
7164 // Initialize
7165 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7166 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7167 window->Active = true;
7168 window->HasCloseButton = (p_open != NULL);
7169 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7170 window->IDStack.resize(1);
7171 window->DrawList->_ResetForNewFrame();
7172 window->DC.CurrentTableIdx = -1;
7173
7174 // Restore buffer capacity when woken from a compacted state, to avoid
7175 if (window->MemoryCompacted)
7176 GcAwakeTransientWindowBuffers(window);
7177
7178 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7179 // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7180 bool window_title_visible_elsewhere = false;
7181 if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
7182 window_title_visible_elsewhere = true;
7183 if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7184 {
7185 size_t buf_len = (size_t)window->NameBufLen;
7186 window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7187 window->NameBufLen = (int)buf_len;
7188 }
7189
7190 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7191
7192 // Update contents size from last frame for auto-fitting (or use explicit size)
7193 CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7194 if (window->HiddenFramesCanSkipItems > 0)
7195 window->HiddenFramesCanSkipItems--;
7196 if (window->HiddenFramesCannotSkipItems > 0)
7197 window->HiddenFramesCannotSkipItems--;
7198 if (window->HiddenFramesForRenderOnly > 0)
7199 window->HiddenFramesForRenderOnly--;
7200
7201 // Hide new windows for one frame until they calculate their size
7202 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7203 window->HiddenFramesCannotSkipItems = 1;
7204
7205 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7206 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7207 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7208 {
7209 window->HiddenFramesCannotSkipItems = 1;
7210 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7211 {
7212 if (!window_size_x_set_by_api)
7213 window->Size.x = window->SizeFull.x = 0.f;
7214 if (!window_size_y_set_by_api)
7215 window->Size.y = window->SizeFull.y = 0.f;
7216 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7217 }
7218 }
7219
7220 // SELECT VIEWPORT
7221 // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
7222
7223 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
7224 SetWindowViewport(window, viewport);
7225 SetCurrentWindow(window);
7226
7227 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7228
7229 if (flags & ImGuiWindowFlags_ChildWindow)
7230 window->WindowBorderSize = style.ChildBorderSize;
7231 else
7232 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7233 window->WindowPadding = style.WindowPadding;
7234 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7235 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7236
7237 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7238 window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7239 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7240 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7241 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7242
7243 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7244 // Those flags will be altered further down in the function depending on more conditions.
7245 bool use_current_size_for_scrollbar_x = window_just_created;
7246 bool use_current_size_for_scrollbar_y = window_just_created;
7247 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7248 use_current_size_for_scrollbar_x = true;
7249 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7250 use_current_size_for_scrollbar_y = true;
7251
7252 // Collapse window by double-clicking on title bar
7253 // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7254 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
7255 {
7256 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
7257 // so verify that we don't have items over the title bar.
7258 ImRect title_bar_rect = window->TitleBarRect();
7259 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7260 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7261 window->WantCollapseToggle = true;
7262 if (window->WantCollapseToggle)
7263 {
7264 window->Collapsed = !window->Collapsed;
7265 if (!window->Collapsed)
7266 use_current_size_for_scrollbar_y = true;
7267 MarkIniSettingsDirty(window);
7268 }
7269 }
7270 else
7271 {
7272 window->Collapsed = false;
7273 }
7274 window->WantCollapseToggle = false;
7275
7276 // SIZE
7277
7278 // Outer Decoration Sizes
7279 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7280 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7281 window->DecoOuterSizeX1 = 0.0f;
7282 window->DecoOuterSizeX2 = 0.0f;
7283 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7284 window->DecoOuterSizeY2 = 0.0f;
7285 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7286
7287 // Calculate auto-fit size, handle automatic resize
7288 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7289 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7290 {
7291 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7292 if (!window_size_x_set_by_api)
7293 {
7294 window->SizeFull.x = size_auto_fit.x;
7295 use_current_size_for_scrollbar_x = true;
7296 }
7297 if (!window_size_y_set_by_api)
7298 {
7299 window->SizeFull.y = size_auto_fit.y;
7300 use_current_size_for_scrollbar_y = true;
7301 }
7302 }
7303 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7304 {
7305 // Auto-fit may only grow window during the first few frames
7306 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7307 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7308 {
7309 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7310 use_current_size_for_scrollbar_x = true;
7311 }
7312 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7313 {
7314 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7315 use_current_size_for_scrollbar_y = true;
7316 }
7317 if (!window->Collapsed)
7318 MarkIniSettingsDirty(window);
7319 }
7320
7321 // Apply minimum/maximum window size constraints and final size
7322 window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7323 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7324
7325 // POSITION
7326
7327 // Popup latch its initial position, will position itself when it appears next frame
7328 if (window_just_activated_by_user)
7329 {
7330 window->AutoPosLastDirection = ImGuiDir_None;
7331 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7332 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7333 }
7334
7335 // Position child window
7336 if (flags & ImGuiWindowFlags_ChildWindow)
7337 {
7338 IM_ASSERT(parent_window && parent_window->Active);
7339 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7340 parent_window->DC.ChildWindows.push_back(window);
7341 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7342 window->Pos = parent_window->DC.CursorPos;
7343 }
7344
7345 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7346 if (window_pos_with_pivot)
7347 SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7348 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7349 window->Pos = FindBestWindowPosForPopup(window);
7350 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7351 window->Pos = FindBestWindowPosForPopup(window);
7352 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7353 window->Pos = FindBestWindowPosForPopup(window);
7354
7355 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7356 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7357 ImRect viewport_rect(viewport->GetMainRect());
7358 ImRect viewport_work_rect(viewport->GetWorkRect());
7359 ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7360 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7361
7362 // Clamp position/size so window stays visible within its viewport or monitor
7363 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7364 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7365 if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
7366 ClampWindowPos(window, visibility_rect);
7367 window->Pos = ImTrunc(window->Pos);
7368
7369 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7370 // Large values tend to lead to variety of artifacts and are not recommended.
7371 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7372
7373 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7374 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7375 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7376
7377 // Apply window focus (new and reactivated windows are moved to front)
7378 bool want_focus = false;
7379 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7380 {
7381 if (flags & ImGuiWindowFlags_Popup)
7382 want_focus = true;
7383 else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
7384 want_focus = true;
7385 }
7386
7387 // [Test Engine] Register whole window in the item system (before submitting further decorations)
7388 #ifdef IMGUI_ENABLE_TEST_ENGINE
7389 if (g.TestEngineHookItems)
7390 {
7391 IM_ASSERT(window->IDStack.Size == 1);
7392 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7393 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7394 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7395 window->IDStack.Size = 1;
7396 }
7397 #endif
7398
7399 // Handle manual resize: Resize Grips, Borders, Gamepad
7400 int border_hovered = -1, border_held = -1;
7401 ImU32 resize_grip_col[4] = {};
7402 const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7403 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7404 if (!window->Collapsed)
7405 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7406 {
7407 if (auto_fit_mask & (1 << ImGuiAxis_X))
7408 use_current_size_for_scrollbar_x = true;
7409 if (auto_fit_mask & (1 << ImGuiAxis_Y))
7410 use_current_size_for_scrollbar_y = true;
7411 }
7412 window->ResizeBorderHovered = (signed char)border_hovered;
7413 window->ResizeBorderHeld = (signed char)border_held;
7414
7415 // SCROLLBAR VISIBILITY
7416
7417 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7418 if (!window->Collapsed)
7419 {
7420 // When reading the current size we need to read it after size constraints have been applied.
7421 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7422 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7423 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7424 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7425 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7426 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7427 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7428 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7429 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7430 window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7431 if (window->ScrollbarX && !window->ScrollbarY)
7432 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7433 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7434
7435 // Amend the partially filled window->DecorationXXX values.
7436 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7437 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7438 }
7439
7440 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7441 // Update various regions. Variables they depend on should be set above in this function.
7442 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7443
7444 // Outer rectangle
7445 // Not affected by window border size. Used by:
7446 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7447 // - Begin() initial clipping rect for drawing window background and borders.
7448 // - Begin() clipping whole child
7449 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7450 const ImRect outer_rect = window->Rect();
7451 const ImRect title_bar_rect = window->TitleBarRect();
7452 window->OuterRectClipped = outer_rect;
7453 window->OuterRectClipped.ClipWith(host_rect);
7454
7455 // Inner rectangle
7456 // Not affected by window border size. Used by:
7457 // - InnerClipRect
7458 // - ScrollToRectEx()
7459 // - NavUpdatePageUpPageDown()
7460 // - Scrollbar()
7461 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7462 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7463 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7464 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7465
7466 // Inner clipping rectangle.
7467 // - Extend a outside of normal work region up to borders.
7468 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7469 // - It also makes clipped items be more noticeable.
7470 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7471 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7472 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7473 // Affected by window/frame border size. Used by:
7474 // - Begin() initial clip rect
7475 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7476
7477 // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner.
7478 // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize,
7479 // see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5f here).
7480 window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f);
7481 window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size * 0.5f);
7482 window->InnerClipRect.Max.x = ImFloor(window->InnerRect.Max.x - window->WindowBorderSize * 0.5f);
7483 window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
7484 window->InnerClipRect.ClipWithFull(host_rect);
7485
7486 // Default item width. Make it proportional to window size if window manually resizes
7487 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7488 window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7489 else
7490 window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7491
7492 // SCROLLING
7493
7494 // Lock down maximum scrolling
7495 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7496 // for right/bottom aligned items without creating a scrollbar.
7497 window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7498 window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7499
7500 // Apply scrolling
7501 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7502 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7503 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7504
7505 // DRAWING
7506
7507 // Setup draw list and outer clipping rectangle
7508 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7509 window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7510 PushClipRect(host_rect.Min, host_rect.Max, false);
7511
7512 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7513 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7514 // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7515 {
7516 bool render_decorations_in_parent = false;
7517 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7518 {
7519 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7520 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7521 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7522 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7523 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7524 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7525 render_decorations_in_parent = true;
7526 }
7527 if (render_decorations_in_parent)
7528 window->DrawList = parent_window->DrawList;
7529
7530 // Handle title bar, scrollbar, resize grips and resize borders
7531 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7532 const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
7533 const bool handle_borders_and_resize_grips = true; // This exists to facilitate merge with 'docking' branch.
7534 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7535
7536 if (render_decorations_in_parent)
7537 window->DrawList = &window->DrawListInst;
7538 }
7539
7540 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7541
7542 // Work rectangle.
7543 // Affected by window padding and border size. Used by:
7544 // - Columns() for right-most edge
7545 // - TreeNode(), CollapsingHeader() for right-most edge
7546 // - BeginTabBar() for right-most edge
7547 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7548 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7549 const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7550 const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7551 window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7552 window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7553 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7554 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7555 window->ParentWorkRect = window->WorkRect;
7556
7557 // [LEGACY] Content Region
7558 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7559 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7560 // Used by:
7561 // - Mouse wheel scrolling + many other things
7562 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7563 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7564 window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7565 window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7566
7567 // Setup drawing context
7568 // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7569 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7570 window->DC.GroupOffset.x = 0.0f;
7571 window->DC.ColumnsOffset.x = 0.0f;
7572
7573 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7574 // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7575 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7576 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7577 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7578 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7579 window->DC.CursorPos = window->DC.CursorStartPos;
7580 window->DC.CursorPosPrevLine = window->DC.CursorPos;
7581 window->DC.CursorMaxPos = window->DC.CursorStartPos;
7582 window->DC.IdealMaxPos = window->DC.CursorStartPos;
7583 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7584 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7585 window->DC.IsSameLine = window->DC.IsSetPos = false;
7586
7587 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7588 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7589 window->DC.NavLayersActiveMaskNext = 0x00;
7590 window->DC.NavIsScrollPushableX = true;
7591 window->DC.NavHideHighlightOneFrame = false;
7592 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7593
7594 window->DC.MenuBarAppending = false;
7595 window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7596 window->DC.TreeDepth = 0;
7597 window->DC.TreeHasStackDataDepthMask = 0x00;
7598 window->DC.ChildWindows.resize(0);
7599 window->DC.StateStorage = &window->StateStorage;
7600 window->DC.CurrentColumns = NULL;
7601 window->DC.LayoutType = ImGuiLayoutType_Vertical;
7602 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7603
7604 window->DC.ItemWidth = window->ItemWidthDefault;
7605 window->DC.TextWrapPos = -1.0f; // disabled
7606 window->DC.ItemWidthStack.resize(0);
7607 window->DC.TextWrapPosStack.resize(0);
7608 if (flags & ImGuiWindowFlags_Modal)
7609 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7610
7611 if (window->AutoFitFramesX > 0)
7612 window->AutoFitFramesX--;
7613 if (window->AutoFitFramesY > 0)
7614 window->AutoFitFramesY--;
7615
7616 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7617 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7618 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7619 // - Position window behind the modal that is not a begin-parent of this window.
7620 if (want_focus)
7621 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7622 if (want_focus && window == g.NavWindow)
7623 NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7624
7625 // Pressing CTRL+C copy window content into the clipboard
7626 // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
7627 // [EXPERIMENTAL] Text outputs has many issues.
7628 if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
7629 if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C))
7630 LogToClipboard(0);
7631
7632 // Title bar
7633 if (!(flags & ImGuiWindowFlags_NoTitleBar))
7634 RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7635
7636 // Clear hit test shape every frame
7637 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7638
7639 if (flags & ImGuiWindowFlags_Tooltip)
7640 g.TooltipPreviousWindow = window;
7641
7642 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7643 // This is useful to allow creating context menus on title bar only, etc.
7644 SetLastItemDataForWindow(window, title_bar_rect);
7645
7646 // [DEBUG]
7647 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
7648 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7649 DebugLocateItemResolveWithLastItem();
7650 #endif
7651
7652 // [Test Engine] Register title bar / tab with MoveId.
7653 #ifdef IMGUI_ENABLE_TEST_ENGINE
7654 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7655 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7656 #endif
7657 }
7658 else
7659 {
7660 // Skip refresh always mark active
7661 if (window->SkipRefresh)
7662 SetWindowActiveForSkipRefresh(window);
7663
7664 // Append
7665 SetCurrentWindow(window);
7666 SetLastItemDataForWindow(window, window->TitleBarRect());
7667 }
7668
7669 if (!window->SkipRefresh)
7670 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7671
7672 // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7673 window->WriteAccessed = false;
7674 window->BeginCount++;
7675 g.NextWindowData.ClearFlags();
7676
7677 // Update visibility
7678 if (first_begin_of_the_frame && !window->SkipRefresh)
7679 {
7680 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7681 {
7682 // Child window can be out of sight and have "negative" clip windows.
7683 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7684 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
7685 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7686 if (!g.LogEnabled && !nav_request)
7687 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7688 {
7689 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7690 window->HiddenFramesCannotSkipItems = 1;
7691 else
7692 window->HiddenFramesCanSkipItems = 1;
7693 }
7694
7695 // Hide along with parent or if parent is collapsed
7696 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7697 window->HiddenFramesCanSkipItems = 1;
7698 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7699 window->HiddenFramesCannotSkipItems = 1;
7700 }
7701
7702 // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7703 if (style.Alpha <= 0.0f)
7704 window->HiddenFramesCanSkipItems = 1;
7705
7706 // Update the Hidden flag
7707 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7708 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7709
7710 // Disable inputs for requested number of frames
7711 if (window->DisableInputsFrames > 0)
7712 {
7713 window->DisableInputsFrames--;
7714 window->Flags |= ImGuiWindowFlags_NoInputs;
7715 }
7716
7717 // Update the SkipItems flag, used to early out of all items functions (no layout required)
7718 bool skip_items = false;
7719 if (window->Collapsed || !window->Active || hidden_regular)
7720 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7721 skip_items = true;
7722 window->SkipItems = skip_items;
7723 }
7724 else if (first_begin_of_the_frame)
7725 {
7726 // Skip refresh mode
7727 window->SkipItems = true;
7728 }
7729
7730 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7731 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7732 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
7733 if (!window->IsFallbackWindow)
7734 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7735 {
7736 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7737 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7738 return false;
7739 }
7740 #endif
7741
7742 return !window->SkipItems;
7743 }
7744
7745 static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7746 {
7747 ImGuiContext& g = *GImGui;
7748 SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7749 }
7750
7751 void ImGui::End()
7752 {
7753 ImGuiContext& g = *GImGui;
7754 ImGuiWindow* window = g.CurrentWindow;
7755
7756 // Error checking: verify that user hasn't called End() too many times!
7757 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7758 {
7759 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7760 return;
7761 }
7762 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7763
7764 // Error checking: verify that user doesn't directly call End() on a child window.
7765 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7766 IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7767
7768 // Close anything that is open
7769 if (window->DC.CurrentColumns)
7770 EndColumns();
7771 if (!window->SkipRefresh)
7772 PopClipRect(); // Inner window clip rectangle
7773 PopFocusScope();
7774 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7775 EndDisabledOverrideReenable();
7776
7777 if (window->SkipRefresh)
7778 {
7779 IM_ASSERT(window->DrawList == NULL);
7780 window->DrawList = &window->DrawListInst;
7781 }
7782
7783 // Stop logging
7784 if (g.LogWindow == window) // FIXME: add more options for scope of logging
7785 LogFinish();
7786
7787 if (window->DC.IsSetPos)
7788 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7789
7790 // Pop from window stack
7791 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7792 if (window->Flags & ImGuiWindowFlags_ChildMenu)
7793 g.BeginMenuDepth--;
7794 if (window->Flags & ImGuiWindowFlags_Popup)
7795 g.BeginPopupStack.pop_back();
7796
7797 // Error handling, state recovery
7798 if (g.IO.ConfigErrorRecovery)
7799 ErrorRecoveryTryToRecoverWindowState(&window_stack_data.StackSizesInBegin);
7800
7801 g.CurrentWindowStack.pop_back();
7802 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7803 }
7804
7805 void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7806 {
7807 ImGuiContext& g = *GImGui;
7808 IM_ASSERT(window == window->RootWindow);
7809
7810 const int cur_order = window->FocusOrder;
7811 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7812 if (g.WindowsFocusOrder.back() == window)
7813 return;
7814
7815 const int new_order = g.WindowsFocusOrder.Size - 1;
7816 for (int n = cur_order; n < new_order; n++)
7817 {
7818 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7819 g.WindowsFocusOrder[n]->FocusOrder--;
7820 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7821 }
7822 g.WindowsFocusOrder[new_order] = window;
7823 window->FocusOrder = (short)new_order;
7824 }
7825
7826 void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7827 {
7828 ImGuiContext& g = *GImGui;
7829 ImGuiWindow* current_front_window = g.Windows.back();
7830 if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
7831 return;
7832 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7833 if (g.Windows[i] == window)
7834 {
7835 memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7836 g.Windows[g.Windows.Size - 1] = window;
7837 break;
7838 }
7839 }
7840
7841 void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7842 {
7843 ImGuiContext& g = *GImGui;
7844 if (g.Windows[0] == window)
7845 return;
7846 for (int i = 0; i < g.Windows.Size; i++)
7847 if (g.Windows[i] == window)
7848 {
7849 memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7850 g.Windows[0] = window;
7851 break;
7852 }
7853 }
7854
7855 void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7856 {
7857 IM_ASSERT(window != NULL && behind_window != NULL);
7858 ImGuiContext& g = *GImGui;
7859 window = window->RootWindow;
7860 behind_window = behind_window->RootWindow;
7861 int pos_wnd = FindWindowDisplayIndex(window);
7862 int pos_beh = FindWindowDisplayIndex(behind_window);
7863 if (pos_wnd < pos_beh)
7864 {
7865 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7866 memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7867 g.Windows[pos_beh - 1] = window;
7868 }
7869 else
7870 {
7871 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7872 memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7873 g.Windows[pos_beh] = window;
7874 }
7875 }
7876
7877 int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7878 {
7879 ImGuiContext& g = *GImGui;
7880 return g.Windows.index_from_ptr(g.Windows.find(window));
7881 }
7882
7883 // Moving window to front of display and set focus (which happens to be back of our sorted list)
7884 void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7885 {
7886 ImGuiContext& g = *GImGui;
7887
7888 // Modal check?
7889 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7890 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7891 {
7892 // This block would typically be reached in two situations:
7893 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
7894 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
7895 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7896 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7897 BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
7898 ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
7899 return;
7900 }
7901
7902 // Find last focused child (if any) and focus it instead.
7903 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7904 window = NavRestoreLastChildNavWindow(window);
7905
7906 // Apply focus
7907 if (g.NavWindow != window)
7908 {
7909 SetNavWindow(window);
7910 if (window && g.NavHighlightItemUnderNav)
7911 g.NavMousePosDirty = true;
7912 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7913 g.NavLayer = ImGuiNavLayer_Main;
7914 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7915 g.NavIdIsAlive = false;
7916 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7917
7918 // Close popups if any
7919 ClosePopupsOverWindow(window, false);
7920 }
7921
7922 // Move the root window to the top of the pile
7923 IM_ASSERT(window == NULL || window->RootWindow != NULL);
7924 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
7925 ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
7926
7927 // Steal active widgets. Some of the cases it triggers includes:
7928 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7929 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7930 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7931 if (!g.ActiveIdNoClearOnFocusLoss)
7932 ClearActiveID();
7933
7934 // Passing NULL allow to disable keyboard focus
7935 if (!window)
7936 return;
7937
7938 // Bring to front
7939 BringWindowToFocusFront(focus_front_window);
7940 if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7941 BringWindowToDisplayFront(display_front_window);
7942 }
7943
7944 void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7945 {
7946 ImGuiContext& g = *GImGui;
7947 IM_UNUSED(filter_viewport); // Unused in master branch.
7948 int start_idx = g.WindowsFocusOrder.Size - 1;
7949 if (under_this_window != NULL)
7950 {
7951 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7952 int offset = -1;
7953 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7954 {
7955 under_this_window = under_this_window->ParentWindow;
7956 offset = 0;
7957 }
7958 start_idx = FindWindowFocusIndex(under_this_window) + offset;
7959 }
7960 for (int i = start_idx; i >= 0; i--)
7961 {
7962 // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7963 ImGuiWindow* window = g.WindowsFocusOrder[i];
7964 if (window == ignore_window || !window->WasActive)
7965 continue;
7966 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7967 {
7968 FocusWindow(window, flags);
7969 return;
7970 }
7971 }
7972 FocusWindow(NULL, flags);
7973 }
7974
7975 // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7976 void ImGui::SetCurrentFont(ImFont* font)
7977 {
7978 ImGuiContext& g = *GImGui;
7979 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7980 IM_ASSERT(font->Scale > 0.0f);
7981 g.Font = font;
7982 g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7983 g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7984 g.FontScale = g.FontSize / g.Font->FontSize;
7985
7986 ImFontAtlas* atlas = g.Font->ContainerAtlas;
7987 g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7988 g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7989 g.DrawListSharedData.Font = g.Font;
7990 g.DrawListSharedData.FontSize = g.FontSize;
7991 g.DrawListSharedData.FontScale = g.FontScale;
7992 }
7993
7994 // Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authorative against window-local ImDrawList.
7995 // - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls.
7996 // - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
7997 // - Some code paths never really fully worked with multiple atlas textures.
7998 // - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID()
7999 // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
8000 // because we have a concrete need and a test bed for multiple atlas textures.
8001 void ImGui::PushFont(ImFont* font)
8002 {
8003 ImGuiContext& g = *GImGui;
8004 if (font == NULL)
8005 font = GetDefaultFont();
8006 g.FontStack.push_back(font);
8007 SetCurrentFont(font);
8008 g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID);
8009 }
8010
8011 void ImGui::PopFont()
8012 {
8013 ImGuiContext& g = *GImGui;
8014 if (g.FontStack.Size <= 0)
8015 {
8016 IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
8017 return;
8018 }
8019 g.FontStack.pop_back();
8020 ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back();
8021 SetCurrentFont(font);
8022 g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID);
8023 }
8024
8025 void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8026 {
8027 ImGuiContext& g = *GImGui;
8028 ImGuiItemFlags item_flags = g.CurrentItemFlags;
8029 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8030 if (enabled)
8031 item_flags |= option;
8032 else
8033 item_flags &= ~option;
8034 g.CurrentItemFlags = item_flags;
8035 g.ItemFlagsStack.push_back(item_flags);
8036 }
8037
8038 void ImGui::PopItemFlag()
8039 {
8040 ImGuiContext& g = *GImGui;
8041 if (g.ItemFlagsStack.Size <= 1)
8042 {
8043 IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!");
8044 return;
8045 }
8046 g.ItemFlagsStack.pop_back();
8047 g.CurrentItemFlags = g.ItemFlagsStack.back();
8048 }
8049
8050 // BeginDisabled()/EndDisabled()
8051 // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8052 // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8053 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8054 // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
8055 // (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls)
8056 // - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
8057 void ImGui::BeginDisabled(bool disabled)
8058 {
8059 ImGuiContext& g = *GImGui;
8060 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8061 if (!was_disabled && disabled)
8062 {
8063 g.DisabledAlphaBackup = g.Style.Alpha;
8064 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8065 }
8066 if (was_disabled || disabled)
8067 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8068 g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8069 g.DisabledStackSize++;
8070 }
8071
8072 void ImGui::EndDisabled()
8073 {
8074 ImGuiContext& g = *GImGui;
8075 if (g.DisabledStackSize <= 0)
8076 {
8077 IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!");
8078 return;
8079 }
8080 g.DisabledStackSize--;
8081 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8082 //PopItemFlag();
8083 g.ItemFlagsStack.pop_back();
8084 g.CurrentItemFlags = g.ItemFlagsStack.back();
8085 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8086 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8087 }
8088
8089 // Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8090 // Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8091 // The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8092 void ImGui::BeginDisabledOverrideReenable()
8093 {
8094 ImGuiContext& g = *GImGui;
8095 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8096 g.Style.Alpha = g.DisabledAlphaBackup;
8097 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8098 g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8099 g.DisabledStackSize++;
8100 }
8101
8102 void ImGui::EndDisabledOverrideReenable()
8103 {
8104 ImGuiContext& g = *GImGui;
8105 g.DisabledStackSize--;
8106 IM_ASSERT(g.DisabledStackSize > 0);
8107 g.ItemFlagsStack.pop_back();
8108 g.CurrentItemFlags = g.ItemFlagsStack.back();
8109 g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
8110 }
8111
8112 void ImGui::PushTextWrapPos(float wrap_pos_x)
8113 {
8114 ImGuiContext& g = *GImGui;
8115 ImGuiWindow* window = g.CurrentWindow;
8116 window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8117 window->DC.TextWrapPos = wrap_pos_x;
8118 }
8119
8120 void ImGui::PopTextWrapPos()
8121 {
8122 ImGuiContext& g = *GImGui;
8123 ImGuiWindow* window = g.CurrentWindow;
8124 if (window->DC.TextWrapPosStack.Size <= 0)
8125 {
8126 IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
8127 return;
8128 }
8129 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8130 window->DC.TextWrapPosStack.pop_back();
8131 }
8132
8133 static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)
8134 {
8135 ImGuiWindow* last_window = NULL;
8136 while (last_window != window)
8137 {
8138 last_window = window;
8139 window = window->RootWindow;
8140 if (popup_hierarchy)
8141 window = window->RootWindowPopupTree;
8142 }
8143 return window;
8144 }
8145
8146 bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)
8147 {
8148 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);
8149 if (window_root == potential_parent)
8150 return true;
8151 while (window != NULL)
8152 {
8153 if (window == potential_parent)
8154 return true;
8155 if (window == window_root) // end of chain
8156 return false;
8157 window = window->ParentWindow;
8158 }
8159 return false;
8160 }
8161
8162 bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8163 {
8164 if (window->RootWindow == potential_parent)
8165 return true;
8166 while (window != NULL)
8167 {
8168 if (window == potential_parent)
8169 return true;
8170 window = window->ParentWindowInBeginStack;
8171 }
8172 return false;
8173 }
8174
8175 bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8176 {
8177 ImGuiContext& g = *GImGui;
8178
8179 // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8180 const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8181 if (display_layer_delta != 0)
8182 return display_layer_delta > 0;
8183
8184 for (int i = g.Windows.Size - 1; i >= 0; i--)
8185 {
8186 ImGuiWindow* candidate_window = g.Windows[i];
8187 if (candidate_window == potential_above)
8188 return true;
8189 if (candidate_window == potential_below)
8190 return false;
8191 }
8192 return false;
8193 }
8194
8195 // Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8196 // IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8197 // you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8198 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8199 bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8200 {
8201 ImGuiContext& g = *GImGui;
8202 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
8203
8204 ImGuiWindow* ref_window = g.HoveredWindow;
8205 ImGuiWindow* cur_window = g.CurrentWindow;
8206 if (ref_window == NULL)
8207 return false;
8208
8209 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8210 {
8211 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8212 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8213 if (flags & ImGuiHoveredFlags_RootWindow)
8214 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
8215
8216 bool result;
8217 if (flags & ImGuiHoveredFlags_ChildWindows)
8218 result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
8219 else
8220 result = (ref_window == cur_window);
8221 if (!result)
8222 return false;
8223 }
8224
8225 if (!IsWindowContentHoverable(ref_window, flags))
8226 return false;
8227 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8228 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8229 return false;
8230
8231 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8232 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8233 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8234 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8235 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8236 if (flags & ImGuiHoveredFlags_ForTooltip)
8237 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8238 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8239 return false;
8240
8241 return true;
8242 }
8243
8244 bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8245 {
8246 ImGuiContext& g = *GImGui;
8247 ImGuiWindow* ref_window = g.NavWindow;
8248 ImGuiWindow* cur_window = g.CurrentWindow;
8249
8250 if (ref_window == NULL)
8251 return false;
8252 if (flags & ImGuiFocusedFlags_AnyWindow)
8253 return true;
8254
8255 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8256 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8257 if (flags & ImGuiHoveredFlags_RootWindow)
8258 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
8259
8260 if (flags & ImGuiHoveredFlags_ChildWindows)
8261 return IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
8262 else
8263 return (ref_window == cur_window);
8264 }
8265
8266 // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8267 // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8268 // If you want a window to never be focused, you may use the e.g. NoInputs flag.
8269 bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8270 {
8271 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8272 }
8273
8274 float ImGui::GetWindowWidth()
8275 {
8276 ImGuiWindow* window = GImGui->CurrentWindow;
8277 return window->Size.x;
8278 }
8279
8280 float ImGui::GetWindowHeight()
8281 {
8282 ImGuiWindow* window = GImGui->CurrentWindow;
8283 return window->Size.y;
8284 }
8285
8286 ImVec2 ImGui::GetWindowPos()
8287 {
8288 ImGuiContext& g = *GImGui;
8289 ImGuiWindow* window = g.CurrentWindow;
8290 return window->Pos;
8291 }
8292
8293 void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8294 {
8295 // Test condition (NB: bit 0 is always true) and clear flags for next time
8296 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8297 return;
8298
8299 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8300 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8301 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8302
8303 // Set
8304 const ImVec2 old_pos = window->Pos;
8305 window->Pos = ImTrunc(pos);
8306 ImVec2 offset = window->Pos - old_pos;
8307 if (offset.x == 0.0f && offset.y == 0.0f)
8308 return;
8309 MarkIniSettingsDirty(window);
8310 window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8311 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8312 window->DC.IdealMaxPos += offset;
8313 window->DC.CursorStartPos += offset;
8314 }
8315
8316 void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8317 {
8318 ImGuiWindow* window = GetCurrentWindowRead();
8319 SetWindowPos(window, pos, cond);
8320 }
8321
8322 void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8323 {
8324 if (ImGuiWindow* window = FindWindowByName(name))
8325 SetWindowPos(window, pos, cond);
8326 }
8327
8328 ImVec2 ImGui::GetWindowSize()
8329 {
8330 ImGuiWindow* window = GetCurrentWindowRead();
8331 return window->Size;
8332 }
8333
8334 void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8335 {
8336 // Test condition (NB: bit 0 is always true) and clear flags for next time
8337 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8338 return;
8339
8340 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8341 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8342
8343 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8344 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8345 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8346 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8347 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8348
8349 // Set
8350 ImVec2 old_size = window->SizeFull;
8351 if (size.x <= 0.0f)
8352 window->AutoFitOnlyGrows = false;
8353 else
8354 window->SizeFull.x = IM_TRUNC(size.x);
8355 if (size.y <= 0.0f)
8356 window->AutoFitOnlyGrows = false;
8357 else
8358 window->SizeFull.y = IM_TRUNC(size.y);
8359 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8360 MarkIniSettingsDirty(window);
8361 }
8362
8363 void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8364 {
8365 SetWindowSize(GImGui->CurrentWindow, size, cond);
8366 }
8367
8368 void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8369 {
8370 if (ImGuiWindow* window = FindWindowByName(name))
8371 SetWindowSize(window, size, cond);
8372 }
8373
8374 void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8375 {
8376 // Test condition (NB: bit 0 is always true) and clear flags for next time
8377 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8378 return;
8379 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8380
8381 // Set
8382 window->Collapsed = collapsed;
8383 }
8384
8385 void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8386 {
8387 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8388 window->HitTestHoleSize = ImVec2ih(size);
8389 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8390 }
8391
8392 void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8393 {
8394 window->Hidden = window->SkipItems = true;
8395 window->HiddenFramesCanSkipItems = 1;
8396 }
8397
8398 void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8399 {
8400 SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8401 }
8402
8403 bool ImGui::IsWindowCollapsed()
8404 {
8405 ImGuiWindow* window = GetCurrentWindowRead();
8406 return window->Collapsed;
8407 }
8408
8409 bool ImGui::IsWindowAppearing()
8410 {
8411 ImGuiWindow* window = GetCurrentWindowRead();
8412 return window->Appearing;
8413 }
8414
8415 void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8416 {
8417 if (ImGuiWindow* window = FindWindowByName(name))
8418 SetWindowCollapsed(window, collapsed, cond);
8419 }
8420
8421 void ImGui::SetWindowFocus()
8422 {
8423 FocusWindow(GImGui->CurrentWindow);
8424 }
8425
8426 void ImGui::SetWindowFocus(const char* name)
8427 {
8428 if (name)
8429 {
8430 if (ImGuiWindow* window = FindWindowByName(name))
8431 FocusWindow(window);
8432 }
8433 else
8434 {
8435 FocusWindow(NULL);
8436 }
8437 }
8438
8439 void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8440 {
8441 ImGuiContext& g = *GImGui;
8442 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8443 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8444 g.NextWindowData.PosVal = pos;
8445 g.NextWindowData.PosPivotVal = pivot;
8446 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8447 }
8448
8449 void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8450 {
8451 ImGuiContext& g = *GImGui;
8452 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8453 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8454 g.NextWindowData.SizeVal = size;
8455 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8456 }
8457
8458 // For each axis:
8459 // - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8460 // - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8461 // - See "Demo->Examples->Constrained-resizing window" for examples.
8462 void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8463 {
8464 ImGuiContext& g = *GImGui;
8465 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8466 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8467 g.NextWindowData.SizeCallback = custom_callback;
8468 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8469 }
8470
8471 // Content size = inner scrollable rectangle, padded with WindowPadding.
8472 // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8473 void ImGui::SetNextWindowContentSize(const ImVec2& size)
8474 {
8475 ImGuiContext& g = *GImGui;
8476 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8477 g.NextWindowData.ContentSizeVal = ImTrunc(size);
8478 }
8479
8480 void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8481 {
8482 ImGuiContext& g = *GImGui;
8483 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8484 g.NextWindowData.ScrollVal = scroll;
8485 }
8486
8487 void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8488 {
8489 ImGuiContext& g = *GImGui;
8490 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8491 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8492 g.NextWindowData.CollapsedVal = collapsed;
8493 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8494 }
8495
8496 void ImGui::SetNextWindowFocus()
8497 {
8498 ImGuiContext& g = *GImGui;
8499 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8500 }
8501
8502 void ImGui::SetNextWindowBgAlpha(float alpha)
8503 {
8504 ImGuiContext& g = *GImGui;
8505 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8506 g.NextWindowData.BgAlphaVal = alpha;
8507 }
8508
8509 // This is experimental and meant to be a toy for exploring a future/wider range of features.
8510 void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8511 {
8512 ImGuiContext& g = *GImGui;
8513 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8514 g.NextWindowData.RefreshFlagsVal = flags;
8515 }
8516
8517 ImDrawList* ImGui::GetWindowDrawList()
8518 {
8519 ImGuiWindow* window = GetCurrentWindow();
8520 return window->DrawList;
8521 }
8522
8523 ImFont* ImGui::GetFont()
8524 {
8525 return GImGui->Font;
8526 }
8527
8528 float ImGui::GetFontSize()
8529 {
8530 return GImGui->FontSize;
8531 }
8532
8533 ImVec2 ImGui::GetFontTexUvWhitePixel()
8534 {
8535 return GImGui->DrawListSharedData.TexUvWhitePixel;
8536 }
8537
8538 void ImGui::SetWindowFontScale(float scale)
8539 {
8540 IM_ASSERT(scale > 0.0f);
8541 ImGuiContext& g = *GImGui;
8542 ImGuiWindow* window = GetCurrentWindow();
8543 window->FontWindowScale = scale;
8544 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8545 g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
8546 }
8547
8548 void ImGui::PushFocusScope(ImGuiID id)
8549 {
8550 ImGuiContext& g = *GImGui;
8551 ImGuiFocusScopeData data;
8552 data.ID = id;
8553 data.WindowID = g.CurrentWindow->ID;
8554 g.FocusScopeStack.push_back(data);
8555 g.CurrentFocusScopeId = id;
8556 }
8557
8558 void ImGui::PopFocusScope()
8559 {
8560 ImGuiContext& g = *GImGui;
8561 if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack)
8562 {
8563 IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
8564 return;
8565 }
8566 g.FocusScopeStack.pop_back();
8567 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8568 }
8569
8570 void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8571 {
8572 ImGuiContext& g = *GImGui;
8573 g.NavFocusScopeId = focus_scope_id;
8574 g.NavFocusRoute.resize(0); // Invalidate
8575 if (focus_scope_id == 0)
8576 return;
8577 IM_ASSERT(g.NavWindow != NULL);
8578
8579 // Store current path (in reverse order)
8580 if (focus_scope_id == g.CurrentFocusScopeId)
8581 {
8582 // Top of focus stack contains local focus scopes inside current window
8583 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8584 g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8585 }
8586 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8587 g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8588 else
8589 return;
8590
8591 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8592 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8593 g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8594 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8595 }
8596
8597 // Focus = move navigation cursor, set scrolling, set focus window.
8598 void ImGui::FocusItem()
8599 {
8600 ImGuiContext& g = *GImGui;
8601 ImGuiWindow* window = g.CurrentWindow;
8602 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8603 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8604 {
8605 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8606 return;
8607 }
8608
8609 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
8610 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8611 SetNavWindow(window);
8612 NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8613 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8614 }
8615
8616 void ImGui::ActivateItemByID(ImGuiID id)
8617 {
8618 ImGuiContext& g = *GImGui;
8619 g.NavNextActivateId = id;
8620 g.NavNextActivateFlags = ImGuiActivateFlags_None;
8621 }
8622
8623 // Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8624 // But ActivateItem() should function without altering scroll/focus?
8625 void ImGui::SetKeyboardFocusHere(int offset)
8626 {
8627 ImGuiContext& g = *GImGui;
8628 ImGuiWindow* window = g.CurrentWindow;
8629 IM_ASSERT(offset >= -1); // -1 is allowed but not below
8630 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8631
8632 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8633 // When we refactor this function into ActivateItem() we may want to make this an option.
8634 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8635 // is also automatically dropped in the event g.ActiveId is stolen.
8636 if (g.DragDropActive || g.MovingWindow != NULL)
8637 {
8638 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8639 return;
8640 }
8641
8642 SetNavWindow(window);
8643
8644 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
8645 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8646 NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8647 if (offset == -1)
8648 {
8649 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8650 }
8651 else
8652 {
8653 g.NavTabbingDir = 1;
8654 g.NavTabbingCounter = offset + 1;
8655 }
8656 }
8657
8658 void ImGui::SetItemDefaultFocus()
8659 {
8660 ImGuiContext& g = *GImGui;
8661 ImGuiWindow* window = g.CurrentWindow;
8662 if (!window->Appearing)
8663 return;
8664 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8665 return;
8666
8667 g.NavInitRequest = false;
8668 NavApplyItemToResult(&g.NavInitResult);
8669 NavUpdateAnyRequestFlag();
8670
8671 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8672 if (!window->ClipRect.Contains(g.LastItemData.Rect))
8673 ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8674 }
8675
8676 void ImGui::SetStateStorage(ImGuiStorage* tree)
8677 {
8678 ImGuiWindow* window = GImGui->CurrentWindow;
8679 window->DC.StateStorage = tree ? tree : &window->StateStorage;
8680 }
8681
8682 ImGuiStorage* ImGui::GetStateStorage()
8683 {
8684 ImGuiWindow* window = GImGui->CurrentWindow;
8685 return window->DC.StateStorage;
8686 }
8687
8688 bool ImGui::IsRectVisible(const ImVec2& size)
8689 {
8690 ImGuiWindow* window = GImGui->CurrentWindow;
8691 return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8692 }
8693
8694 bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8695 {
8696 ImGuiWindow* window = GImGui->CurrentWindow;
8697 return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8698 }
8699
8700 //-----------------------------------------------------------------------------
8701 // [SECTION] ID STACK
8702 //-----------------------------------------------------------------------------
8703
8704 // This is one of the very rare legacy case where we use ImGuiWindow methods,
8705 // it should ideally be flattened at some point but it's been used a lots by widgets.
8706 IM_MSVC_RUNTIME_CHECKS_OFF
8707 ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8708 {
8709 ImGuiID seed = IDStack.back();
8710 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8711 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8712 ImGuiContext& g = *Ctx;
8713 if (g.DebugHookIdInfo == id)
8714 ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8715 #endif
8716 return id;
8717 }
8718
8719 ImGuiID ImGuiWindow::GetID(const void* ptr)
8720 {
8721 ImGuiID seed = IDStack.back();
8722 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8723 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8724 ImGuiContext& g = *Ctx;
8725 if (g.DebugHookIdInfo == id)
8726 ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8727 #endif
8728 return id;
8729 }
8730
8731 ImGuiID ImGuiWindow::GetID(int n)
8732 {
8733 ImGuiID seed = IDStack.back();
8734 ImGuiID id = ImHashData(&n, sizeof(n), seed);
8735 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8736 ImGuiContext& g = *Ctx;
8737 if (g.DebugHookIdInfo == id)
8738 ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8739 #endif
8740 return id;
8741 }
8742
8743 // This is only used in rare/specific situations to manufacture an ID out of nowhere.
8744 // FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
8745 ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs)
8746 {
8747 ImGuiID seed = IDStack.back();
8748 ImVec2 p_rel = ImGui::WindowPosAbsToRel(this, p_abs);
8749 ImGuiID id = ImHashData(&p_rel, sizeof(p_rel), seed);
8750 return id;
8751 }
8752
8753 // "
8754 ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8755 {
8756 ImGuiID seed = IDStack.back();
8757 ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8758 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8759 return id;
8760 }
8761
8762 void ImGui::PushID(const char* str_id)
8763 {
8764 ImGuiContext& g = *GImGui;
8765 ImGuiWindow* window = g.CurrentWindow;
8766 ImGuiID id = window->GetID(str_id);
8767 window->IDStack.push_back(id);
8768 }
8769
8770 void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8771 {
8772 ImGuiContext& g = *GImGui;
8773 ImGuiWindow* window = g.CurrentWindow;
8774 ImGuiID id = window->GetID(str_id_begin, str_id_end);
8775 window->IDStack.push_back(id);
8776 }
8777
8778 void ImGui::PushID(const void* ptr_id)
8779 {
8780 ImGuiContext& g = *GImGui;
8781 ImGuiWindow* window = g.CurrentWindow;
8782 ImGuiID id = window->GetID(ptr_id);
8783 window->IDStack.push_back(id);
8784 }
8785
8786 void ImGui::PushID(int int_id)
8787 {
8788 ImGuiContext& g = *GImGui;
8789 ImGuiWindow* window = g.CurrentWindow;
8790 ImGuiID id = window->GetID(int_id);
8791 window->IDStack.push_back(id);
8792 }
8793
8794 // Push a given id value ignoring the ID stack as a seed.
8795 void ImGui::PushOverrideID(ImGuiID id)
8796 {
8797 ImGuiContext& g = *GImGui;
8798 ImGuiWindow* window = g.CurrentWindow;
8799 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8800 if (g.DebugHookIdInfo == id)
8801 DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8802 #endif
8803 window->IDStack.push_back(id);
8804 }
8805
8806 // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8807 // (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8808 // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8809 ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8810 {
8811 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8812 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8813 ImGuiContext& g = *GImGui;
8814 if (g.DebugHookIdInfo == id)
8815 DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8816 #endif
8817 return id;
8818 }
8819
8820 ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8821 {
8822 ImGuiID id = ImHashData(&n, sizeof(n), seed);
8823 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8824 ImGuiContext& g = *GImGui;
8825 if (g.DebugHookIdInfo == id)
8826 DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8827 #endif
8828 return id;
8829 }
8830
8831 void ImGui::PopID()
8832 {
8833 ImGuiWindow* window = GImGui->CurrentWindow;
8834 if (window->IDStack.Size <= 1)
8835 {
8836 IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!");
8837 return;
8838 }
8839 window->IDStack.pop_back();
8840 }
8841
8842 ImGuiID ImGui::GetID(const char* str_id)
8843 {
8844 ImGuiWindow* window = GImGui->CurrentWindow;
8845 return window->GetID(str_id);
8846 }
8847
8848 ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8849 {
8850 ImGuiWindow* window = GImGui->CurrentWindow;
8851 return window->GetID(str_id_begin, str_id_end);
8852 }
8853
8854 ImGuiID ImGui::GetID(const void* ptr_id)
8855 {
8856 ImGuiWindow* window = GImGui->CurrentWindow;
8857 return window->GetID(ptr_id);
8858 }
8859
8860 ImGuiID ImGui::GetID(int int_id)
8861 {
8862 ImGuiWindow* window = GImGui->CurrentWindow;
8863 return window->GetID(int_id);
8864 }
8865 IM_MSVC_RUNTIME_CHECKS_RESTORE
8866
8867 //-----------------------------------------------------------------------------
8868 // [SECTION] INPUTS
8869 //-----------------------------------------------------------------------------
8870 // - GetModForLRModKey() [Internal]
8871 // - FixupKeyChord() [Internal]
8872 // - GetKeyData() [Internal]
8873 // - GetKeyIndex() [Internal]
8874 // - GetKeyName()
8875 // - GetKeyChordName() [Internal]
8876 // - CalcTypematicRepeatAmount() [Internal]
8877 // - GetTypematicRepeatRate() [Internal]
8878 // - GetKeyPressedAmount() [Internal]
8879 // - GetKeyMagnitude2d() [Internal]
8880 //-----------------------------------------------------------------------------
8881 // - UpdateKeyRoutingTable() [Internal]
8882 // - GetRoutingIdFromOwnerId() [Internal]
8883 // - GetShortcutRoutingData() [Internal]
8884 // - CalcRoutingScore() [Internal]
8885 // - SetShortcutRouting() [Internal]
8886 // - TestShortcutRouting() [Internal]
8887 //-----------------------------------------------------------------------------
8888 // - IsKeyDown()
8889 // - IsKeyPressed()
8890 // - IsKeyReleased()
8891 //-----------------------------------------------------------------------------
8892 // - IsMouseDown()
8893 // - IsMouseClicked()
8894 // - IsMouseReleased()
8895 // - IsMouseDoubleClicked()
8896 // - GetMouseClickedCount()
8897 // - IsMouseHoveringRect() [Internal]
8898 // - IsMouseDragPastThreshold() [Internal]
8899 // - IsMouseDragging()
8900 // - GetMousePos()
8901 // - SetMousePos() [Internal]
8902 // - GetMousePosOnOpeningCurrentPopup()
8903 // - IsMousePosValid()
8904 // - IsAnyMouseDown()
8905 // - GetMouseDragDelta()
8906 // - ResetMouseDragDelta()
8907 // - GetMouseCursor()
8908 // - SetMouseCursor()
8909 //-----------------------------------------------------------------------------
8910 // - UpdateAliasKey()
8911 // - GetMergedModsFromKeys()
8912 // - UpdateKeyboardInputs()
8913 // - UpdateMouseInputs()
8914 //-----------------------------------------------------------------------------
8915 // - LockWheelingWindow [Internal]
8916 // - FindBestWheelingWindow [Internal]
8917 // - UpdateMouseWheel() [Internal]
8918 //-----------------------------------------------------------------------------
8919 // - SetNextFrameWantCaptureKeyboard()
8920 // - SetNextFrameWantCaptureMouse()
8921 //-----------------------------------------------------------------------------
8922 // - GetInputSourceName() [Internal]
8923 // - DebugPrintInputEvent() [Internal]
8924 // - UpdateInputEvents() [Internal]
8925 //-----------------------------------------------------------------------------
8926 // - GetKeyOwner() [Internal]
8927 // - TestKeyOwner() [Internal]
8928 // - SetKeyOwner() [Internal]
8929 // - SetItemKeyOwner() [Internal]
8930 // - Shortcut() [Internal]
8931 //-----------------------------------------------------------------------------
8932
8933 static ImGuiKeyChord GetModForLRModKey(ImGuiKey key)
8934 {
8935 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
8936 return ImGuiMod_Ctrl;
8937 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
8938 return ImGuiMod_Shift;
8939 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
8940 return ImGuiMod_Alt;
8941 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
8942 return ImGuiMod_Super;
8943 return ImGuiMod_None;
8944 }
8945
8946 ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
8947 {
8948 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8949 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8950 if (IsLRModKey(key))
8951 key_chord |= GetModForLRModKey(key);
8952 return key_chord;
8953 }
8954
8955 ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8956 {
8957 ImGuiContext& g = *ctx;
8958
8959 // Special storage location for mods
8960 if (key & ImGuiMod_Mask_)
8961 key = ConvertSingleModFlagToKey(key);
8962
8963 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8964 return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
8965 }
8966
8967 // Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8968 static const char* const GKeyNames[] =
8969 {
8970 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8971 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8972 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8973 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8974 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8975 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8976 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8977 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8978 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8979 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8980 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8981 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8982 "AppBack", "AppForward",
8983 "GamepadStart", "GamepadBack",
8984 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8985 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8986 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8987 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8988 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8989 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8990 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8991 };
8992 IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8993
8994 const char* ImGui::GetKeyName(ImGuiKey key)
8995 {
8996 if (key == ImGuiKey_None)
8997 return "None";
8998 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8999 if (key & ImGuiMod_Mask_)
9000 key = ConvertSingleModFlagToKey(key);
9001 if (!IsNamedKey(key))
9002 return "Unknown";
9003
9004 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9005 }
9006
9007 // Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9008 // Lifetime of return value: valid until next call to same function.
9009 const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9010 {
9011 ImGuiContext& g = *GImGui;
9012
9013 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9014 if (IsLRModKey(key))
9015 key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9016 ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9017 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9018 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9019 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9020 (key_chord & ImGuiMod_Super) ? "Super+" : "",
9021 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9022 size_t len;
9023 if (key == ImGuiKey_None && key_chord != 0)
9024 if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9025 g.TempKeychordName[len - 1] = 0;
9026 return g.TempKeychordName;
9027 }
9028
9029 // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9030 // t1 = current time (e.g.: g.Time)
9031 // An event is triggered at:
9032 // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
9033 int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9034 {
9035 if (t1 == 0.0f)
9036 return 1;
9037 if (t0 >= t1)
9038 return 0;
9039 if (repeat_rate <= 0.0f)
9040 return (t0 < repeat_delay) && (t1 >= repeat_delay);
9041 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9042 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9043 const int count = count_t1 - count_t0;
9044 return count;
9045 }
9046
9047 void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9048 {
9049 ImGuiContext& g = *GImGui;
9050 switch (flags & ImGuiInputFlags_RepeatRateMask_)
9051 {
9052 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9053 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9054 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9055 }
9056 }
9057
9058 // Return value representing the number of presses in the last time period, for the given repeat rate
9059 // (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9060 int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9061 {
9062 ImGuiContext& g = *GImGui;
9063 const ImGuiKeyData* key_data = GetKeyData(key);
9064 if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9065 return 0;
9066 const float t = key_data->DownDuration;
9067 return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9068 }
9069
9070 // Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9071 ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9072 {
9073 return ImVec2(
9074 GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9075 GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9076 }
9077
9078 // Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9079 // Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
9080 // Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
9081 // See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9082 static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9083 {
9084 ImGuiContext& g = *GImGui;
9085 rt->EntriesNext.resize(0);
9086 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9087 {
9088 const int new_routing_start_idx = rt->EntriesNext.Size;
9089 ImGuiKeyRoutingData* routing_entry;
9090 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9091 {
9092 routing_entry = &rt->Entries[old_routing_idx];
9093 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9094 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9095 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9096 routing_entry->RoutingNextScore = 255;
9097 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9098 continue;
9099 rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9100
9101 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9102 // This is the result of previous frame's SetShortcutRouting() call.
9103 if (routing_entry->Mods == g.IO.KeyMods)
9104 {
9105 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9106 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9107 {
9108 owner_data->OwnerCurr = routing_entry->RoutingCurr;
9109 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9110 }
9111 }
9112 }
9113
9114 // Rewrite linked-list
9115 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9116 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9117 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9118 }
9119 rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9120 }
9121
9122 // owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9123 static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9124 {
9125 ImGuiContext& g = *GImGui;
9126 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9127 }
9128
9129 ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9130 {
9131 // Majority of shortcuts will be Key + any number of Mods
9132 // We accept _Single_ mod with ImGuiKey_None.
9133 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
9134 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
9135 // - Shortcut(ImGuiMod_Ctrl); // Legal
9136 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
9137 ImGuiContext& g = *GImGui;
9138 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9139 ImGuiKeyRoutingData* routing_data;
9140 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9141 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9142 if (key == ImGuiKey_None)
9143 key = ConvertSingleModFlagToKey(mods);
9144 IM_ASSERT(IsNamedKey(key));
9145
9146 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9147 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9148 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9149 {
9150 routing_data = &rt->Entries[idx];
9151 if (routing_data->Mods == mods)
9152 return routing_data;
9153 }
9154
9155 // Add to linked-list
9156 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9157 rt->Entries.push_back(ImGuiKeyRoutingData());
9158 routing_data = &rt->Entries[routing_data_idx];
9159 routing_data->Mods = (ImU16)mods;
9160 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9161 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9162 return routing_data;
9163 }
9164
9165 // Current score encoding (lower is highest priority):
9166 // - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9167 // - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
9168 // - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9169 // - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9170 // - 254: ImGuiInputFlags_RouteGlobal
9171 // - 255: never route
9172 // 'flags' should include an explicit routing policy
9173 static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9174 {
9175 ImGuiContext& g = *GImGui;
9176 if (flags & ImGuiInputFlags_RouteFocused)
9177 {
9178 // ActiveID gets top priority
9179 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9180 if (owner_id != 0 && g.ActiveId == owner_id)
9181 return 1;
9182
9183 // Score based on distance to focused window (lower is better)
9184 // Assuming both windows are submitting a routing request,
9185 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9186 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
9187 // Assuming only WindowA is submitting a routing request,
9188 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9189 // This essentially follow the window->ParentWindowForFocusRoute chain.
9190 if (focus_scope_id == 0)
9191 return 255;
9192 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9193 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9194 return 3 + index_in_focus_path;
9195 return 255;
9196 }
9197 else if (flags & ImGuiInputFlags_RouteActive)
9198 {
9199 if (owner_id != 0 && g.ActiveId == owner_id)
9200 return 1;
9201 return 255;
9202 }
9203 else if (flags & ImGuiInputFlags_RouteGlobal)
9204 {
9205 if (flags & ImGuiInputFlags_RouteOverActive)
9206 return 0;
9207 if (flags & ImGuiInputFlags_RouteOverFocused)
9208 return 2;
9209 return 254;
9210 }
9211 IM_ASSERT(0);
9212 return 0;
9213 }
9214
9215 // - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9216 // e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9217 // - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey_G also emitting a G character.
9218 static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9219 {
9220 // Mimic 'ignore_char_inputs' logic in InputText()
9221 ImGuiContext& g = *GImGui;
9222
9223 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9224 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9225 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9226 if (ignore_char_inputs)
9227 return false;
9228
9229 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9230 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9231 if (key == ImGuiKey_None)
9232 return false;
9233 return g.KeysMayBeCharInput.TestBit(key);
9234 }
9235
9236 // Request a desired route for an input chord (key + mods).
9237 // Return true if the route is available this frame.
9238 // - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9239 // (Conceptually this does a "Submit for next frame" + "Test for current frame".
9240 // As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9241 bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9242 {
9243 ImGuiContext& g = *GImGui;
9244 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9245 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9246 else
9247 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9248 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9249 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
9250 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9251
9252 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9253 key_chord = FixupKeyChord(key_chord);
9254
9255 // [DEBUG] Debug break requested by user
9256 if (g.DebugBreakInShortcutRouting == key_chord)
9257 IM_DEBUG_BREAK();
9258
9259 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9260 if (g.NavWindow == NULL)
9261 return false;
9262
9263 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9264 if (flags & ImGuiInputFlags_RouteAlways)
9265 {
9266 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9267 return true;
9268 }
9269
9270 // Specific culling when there's an active item.
9271 if (g.ActiveId != 0 && g.ActiveId != owner_id)
9272 {
9273 if (flags & ImGuiInputFlags_RouteActive)
9274 return false;
9275
9276 // Cull shortcuts with no modifiers when it could generate a character.
9277 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9278 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9279 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9280 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9281 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9282 {
9283 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9284 return false;
9285 }
9286
9287 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9288 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9289 {
9290 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9291 if (key == ImGuiKey_None)
9292 key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9293 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9294 return false;
9295 }
9296 }
9297
9298 // Where do we evaluate route for?
9299 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9300 if (flags & ImGuiInputFlags_RouteFromRootWindow)
9301 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9302
9303 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9304 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9305 if (score == 255)
9306 return false;
9307
9308 // Submit routing for NEXT frame (assuming score is sufficient)
9309 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9310 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9311 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9312 if (score < routing_data->RoutingNextScore)
9313 {
9314 routing_data->RoutingNext = owner_id;
9315 routing_data->RoutingNextScore = (ImU8)score;
9316 }
9317
9318 // Return routing state for CURRENT frame
9319 if (routing_data->RoutingCurr == owner_id)
9320 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9321 return routing_data->RoutingCurr == owner_id;
9322 }
9323
9324 // Currently unused by core (but used by tests)
9325 // Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9326 bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9327 {
9328 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9329 key_chord = FixupKeyChord(key_chord);
9330 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9331 return routing_data->RoutingCurr == routing_id;
9332 }
9333
9334 // Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9335 // Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9336 bool ImGui::IsKeyDown(ImGuiKey key)
9337 {
9338 return IsKeyDown(key, ImGuiKeyOwner_Any);
9339 }
9340
9341 bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9342 {
9343 const ImGuiKeyData* key_data = GetKeyData(key);
9344 if (!key_data->Down)
9345 return false;
9346 if (!TestKeyOwner(key, owner_id))
9347 return false;
9348 return true;
9349 }
9350
9351 bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9352 {
9353 return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9354 }
9355
9356 // Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9357 bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9358 {
9359 const ImGuiKeyData* key_data = GetKeyData(key);
9360 if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9361 return false;
9362 const float t = key_data->DownDuration;
9363 if (t < 0.0f)
9364 return false;
9365 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9366 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9367 flags |= ImGuiInputFlags_Repeat;
9368
9369 bool pressed = (t == 0.0f);
9370 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9371 {
9372 float repeat_delay, repeat_rate;
9373 GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9374 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9375 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9376 {
9377 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9378 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9379 ImGuiContext& g = *GImGui;
9380 double key_pressed_time = g.Time - t + 0.00001f;
9381 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9382 pressed = false;
9383 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9384 pressed = false;
9385 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9386 pressed = false;
9387 }
9388 }
9389 if (!pressed)
9390 return false;
9391 if (!TestKeyOwner(key, owner_id))
9392 return false;
9393 return true;
9394 }
9395
9396 bool ImGui::IsKeyReleased(ImGuiKey key)
9397 {
9398 return IsKeyReleased(key, ImGuiKeyOwner_Any);
9399 }
9400
9401 bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9402 {
9403 const ImGuiKeyData* key_data = GetKeyData(key);
9404 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9405 return false;
9406 if (!TestKeyOwner(key, owner_id))
9407 return false;
9408 return true;
9409 }
9410
9411 bool ImGui::IsMouseDown(ImGuiMouseButton button)
9412 {
9413 ImGuiContext& g = *GImGui;
9414 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9415 return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9416 }
9417
9418 bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9419 {
9420 ImGuiContext& g = *GImGui;
9421 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9422 return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9423 }
9424
9425 bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9426 {
9427 return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9428 }
9429
9430 bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
9431 {
9432 ImGuiContext& g = *GImGui;
9433 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9434 if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9435 return false;
9436 const float t = g.IO.MouseDownDuration[button];
9437 if (t < 0.0f)
9438 return false;
9439 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9440
9441 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9442 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9443 if (!pressed)
9444 return false;
9445
9446 if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9447 return false;
9448
9449 return true;
9450 }
9451
9452 bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9453 {
9454 ImGuiContext& g = *GImGui;
9455 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9456 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9457 }
9458
9459 bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9460 {
9461 ImGuiContext& g = *GImGui;
9462 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9463 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9464 }
9465
9466 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9467 {
9468 ImGuiContext& g = *GImGui;
9469 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9470 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9471 }
9472
9473 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9474 {
9475 ImGuiContext& g = *GImGui;
9476 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9477 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9478 }
9479
9480 int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9481 {
9482 ImGuiContext& g = *GImGui;
9483 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9484 return g.IO.MouseClickedCount[button];
9485 }
9486
9487 // Test if mouse cursor is hovering given rectangle
9488 // NB- Rectangle is clipped by our current clip setting
9489 // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9490 bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9491 {
9492 ImGuiContext& g = *GImGui;
9493
9494 // Clip
9495 ImRect rect_clipped(r_min, r_max);
9496 if (clip)
9497 rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9498
9499 // Hit testing, expanded for touch input
9500 if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9501 return false;
9502 return true;
9503 }
9504
9505 // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9506 // [Internal] This doesn't test if the button is pressed
9507 bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9508 {
9509 ImGuiContext& g = *GImGui;
9510 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9511 if (lock_threshold < 0.0f)
9512 lock_threshold = g.IO.MouseDragThreshold;
9513 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9514 }
9515
9516 bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9517 {
9518 ImGuiContext& g = *GImGui;
9519 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9520 if (!g.IO.MouseDown[button])
9521 return false;
9522 return IsMouseDragPastThreshold(button, lock_threshold);
9523 }
9524
9525 ImVec2 ImGui::GetMousePos()
9526 {
9527 ImGuiContext& g = *GImGui;
9528 return g.IO.MousePos;
9529 }
9530
9531 // This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9532 // It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9533 void ImGui::TeleportMousePos(const ImVec2& pos)
9534 {
9535 ImGuiContext& g = *GImGui;
9536 g.IO.MousePos = g.IO.MousePosPrev = pos;
9537 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9538 g.IO.WantSetMousePos = true;
9539 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9540 }
9541
9542 // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9543 ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9544 {
9545 ImGuiContext& g = *GImGui;
9546 if (g.BeginPopupStack.Size > 0)
9547 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9548 return g.IO.MousePos;
9549 }
9550
9551 // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9552 bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9553 {
9554 // The assert is only to silence a false-positive in XCode Static Analysis.
9555 // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9556 IM_ASSERT(GImGui != NULL);
9557 const float MOUSE_INVALID = -256000.0f;
9558 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9559 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9560 }
9561
9562 // [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9563 bool ImGui::IsAnyMouseDown()
9564 {
9565 ImGuiContext& g = *GImGui;
9566 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9567 if (g.IO.MouseDown[n])
9568 return true;
9569 return false;
9570 }
9571
9572 // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9573 // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9574 // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9575 ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9576 {
9577 ImGuiContext& g = *GImGui;
9578 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9579 if (lock_threshold < 0.0f)
9580 lock_threshold = g.IO.MouseDragThreshold;
9581 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9582 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9583 if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9584 return g.IO.MousePos - g.IO.MouseClickedPos[button];
9585 return ImVec2(0.0f, 0.0f);
9586 }
9587
9588 void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9589 {
9590 ImGuiContext& g = *GImGui;
9591 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9592 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9593 g.IO.MouseClickedPos[button] = g.IO.MousePos;
9594 }
9595
9596 // Get desired mouse cursor shape.
9597 // Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9598 // updated during the frame, and locked in EndFrame()/Render().
9599 // If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9600 ImGuiMouseCursor ImGui::GetMouseCursor()
9601 {
9602 ImGuiContext& g = *GImGui;
9603 return g.MouseCursor;
9604 }
9605
9606 // We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
9607 // Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may
9608 // handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
9609 void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9610 {
9611 ImGuiContext& g = *GImGui;
9612 g.MouseCursor = cursor_type;
9613 }
9614
9615 static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9616 {
9617 IM_ASSERT(ImGui::IsAliasKey(key));
9618 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9619 key_data->Down = v;
9620 key_data->AnalogValue = analog_value;
9621 }
9622
9623 // [Internal] Do not use directly
9624 static ImGuiKeyChord GetMergedModsFromKeys()
9625 {
9626 ImGuiKeyChord mods = 0;
9627 if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
9628 if (ImGui::IsKeyDown(ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
9629 if (ImGui::IsKeyDown(ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
9630 if (ImGui::IsKeyDown(ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
9631 return mods;
9632 }
9633
9634 static void ImGui::UpdateKeyboardInputs()
9635 {
9636 ImGuiContext& g = *GImGui;
9637 ImGuiIO& io = g.IO;
9638
9639 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9640 io.ClearInputKeys();
9641
9642 // Update aliases
9643 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9644 UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9645 UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9646 UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9647
9648 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9649 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9650 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9651 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9652 const ImGuiKeyChord prev_key_mods = io.KeyMods;
9653 io.KeyMods = GetMergedModsFromKeys();
9654 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9655 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9656 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9657 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9658 if (prev_key_mods != io.KeyMods)
9659 g.LastKeyModsChangeTime = g.Time;
9660 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9661 g.LastKeyModsChangeFromNoneTime = g.Time;
9662
9663 // Clear gamepad data if disabled
9664 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9665 for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
9666 {
9667 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
9668 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
9669 }
9670
9671 // Update keys
9672 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
9673 {
9674 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
9675 key_data->DownDurationPrev = key_data->DownDuration;
9676 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9677 if (key_data->DownDuration == 0.0f)
9678 {
9679 if (IsKeyboardKey((ImGuiKey)key))
9680 g.LastKeyboardKeyPressTime = g.Time;
9681 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9682 g.LastKeyboardKeyPressTime = g.Time;
9683 }
9684 }
9685
9686 // Update keys/input owner (named keys only): one entry per key
9687 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9688 {
9689 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
9690 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9691 owner_data->OwnerCurr = owner_data->OwnerNext;
9692 if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9693 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9694 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
9695 }
9696
9697 // Update key routing (for e.g. shortcuts)
9698 UpdateKeyRoutingTable(&g.KeysRoutingTable);
9699 }
9700
9701 static void ImGui::UpdateMouseInputs()
9702 {
9703 ImGuiContext& g = *GImGui;
9704 ImGuiIO& io = g.IO;
9705
9706 // Mouse Wheel swapping flag
9707 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9708 // - We avoid doing it on OSX as it the OS input layer handles this already.
9709 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9710 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9711 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9712
9713 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9714 if (IsMousePosValid(&io.MousePos))
9715 io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9716
9717 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9718 if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9719 io.MouseDelta = io.MousePos - io.MousePosPrev;
9720 else
9721 io.MouseDelta = ImVec2(0.0f, 0.0f);
9722
9723 // Update stationary timer.
9724 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9725 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9726 const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9727 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9728 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9729
9730 // If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9731 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9732 g.NavHighlightItemUnderNav = false;
9733
9734 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9735 {
9736 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9737 io.MouseClickedCount[i] = 0; // Will be filled below
9738 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9739 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9740 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9741 if (io.MouseClicked[i])
9742 {
9743 bool is_repeated_click = false;
9744 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9745 {
9746 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9747 if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9748 is_repeated_click = true;
9749 }
9750 if (is_repeated_click)
9751 io.MouseClickedLastCount[i]++;
9752 else
9753 io.MouseClickedLastCount[i] = 1;
9754 io.MouseClickedTime[i] = g.Time;
9755 io.MouseClickedPos[i] = io.MousePos;
9756 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9757 io.MouseDragMaxDistanceSqr[i] = 0.0f;
9758 }
9759 else if (io.MouseDown[i])
9760 {
9761 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9762 float delta_sqr_click_pos = IsMousePosValid(&io.MousePos) ? ImLengthSqr(io.MousePos - io.MouseClickedPos[i]) : 0.0f;
9763 io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], delta_sqr_click_pos);
9764 }
9765
9766 // We provide io.MouseDoubleClicked[] as a legacy service
9767 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9768
9769 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
9770 if (io.MouseClicked[i])
9771 g.NavHighlightItemUnderNav = false;
9772 }
9773 }
9774
9775 static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9776 {
9777 ImGuiContext& g = *GImGui;
9778 if (window)
9779 g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9780 else
9781 g.WheelingWindowReleaseTimer = 0.0f;
9782 if (g.WheelingWindow == window)
9783 return;
9784 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9785 g.WheelingWindow = window;
9786 g.WheelingWindowRefMousePos = g.IO.MousePos;
9787 if (window == NULL)
9788 {
9789 g.WheelingWindowStartFrame = -1;
9790 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9791 }
9792 }
9793
9794 static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9795 {
9796 // For each axis, find window in the hierarchy that may want to use scrolling
9797 ImGuiContext& g = *GImGui;
9798 ImGuiWindow* windows[2] = { NULL, NULL };
9799 for (int axis = 0; axis < 2; axis++)
9800 if (wheel[axis] != 0.0f)
9801 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9802 {
9803 // Bubble up into parent window if:
9804 // - a child window doesn't allow any scrolling.
9805 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9806 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9807 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9808 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9809 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9810 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9811 break; // select this window
9812 }
9813 if (windows[0] == NULL && windows[1] == NULL)
9814 return NULL;
9815
9816 // If there's only one window or only one axis then there's no ambiguity
9817 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9818 return windows[1] ? windows[1] : windows[0];
9819
9820 // If candidate are different windows we need to decide which one to prioritize
9821 // - First frame: only find a winner if one axis is zero.
9822 // - Subsequent frames: only find a winner when one is more than the other.
9823 if (g.WheelingWindowStartFrame == -1)
9824 g.WheelingWindowStartFrame = g.FrameCount;
9825 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9826 {
9827 g.WheelingWindowWheelRemainder = wheel;
9828 return NULL;
9829 }
9830 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9831 }
9832
9833 // Called by NewFrame()
9834 void ImGui::UpdateMouseWheel()
9835 {
9836 // Reset the locked window if we move the mouse or after the timer elapses.
9837 // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9838 ImGuiContext& g = *GImGui;
9839 if (g.WheelingWindow != NULL)
9840 {
9841 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9842 if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9843 g.WheelingWindowReleaseTimer = 0.0f;
9844 if (g.WheelingWindowReleaseTimer <= 0.0f)
9845 LockWheelingWindow(NULL, 0.0f);
9846 }
9847
9848 ImVec2 wheel;
9849 wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
9850 wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
9851
9852 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9853 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9854 if (!mouse_window || mouse_window->Collapsed)
9855 return;
9856
9857 // Zoom / Scale window
9858 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9859 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9860 {
9861 LockWheelingWindow(mouse_window, wheel.y);
9862 ImGuiWindow* window = mouse_window;
9863 const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9864 const float scale = new_font_scale / window->FontWindowScale;
9865 window->FontWindowScale = new_font_scale;
9866 if (window == window->RootWindow)
9867 {
9868 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9869 SetWindowPos(window, window->Pos + offset, 0);
9870 window->Size = ImTrunc(window->Size * scale);
9871 window->SizeFull = ImTrunc(window->SizeFull * scale);
9872 }
9873 return;
9874 }
9875 if (g.IO.KeyCtrl)
9876 return;
9877
9878 // Mouse wheel scrolling
9879 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9880 if (g.IO.MouseWheelRequestAxisSwap)
9881 wheel = ImVec2(wheel.y, 0.0f);
9882
9883 // Maintain a rough average of moving magnitude on both axises
9884 // FIXME: should by based on wall clock time rather than frame-counter
9885 g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9886 g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9887
9888 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9889 wheel += g.WheelingWindowWheelRemainder;
9890 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9891 if (wheel.x == 0.0f && wheel.y == 0.0f)
9892 return;
9893
9894 // Mouse wheel scrolling: find target and apply
9895 // - don't renew lock if axis doesn't apply on the window.
9896 // - select a main axis when both axises are being moved.
9897 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9898 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9899 {
9900 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9901 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9902 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9903 if (do_scroll[ImGuiAxis_X])
9904 {
9905 LockWheelingWindow(window, wheel.x);
9906 float max_step = window->InnerRect.GetWidth() * 0.67f;
9907 float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9908 SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9909 g.WheelingWindowScrolledFrame = g.FrameCount;
9910 }
9911 if (do_scroll[ImGuiAxis_Y])
9912 {
9913 LockWheelingWindow(window, wheel.y);
9914 float max_step = window->InnerRect.GetHeight() * 0.67f;
9915 float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9916 SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9917 g.WheelingWindowScrolledFrame = g.FrameCount;
9918 }
9919 }
9920 }
9921
9922 void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9923 {
9924 ImGuiContext& g = *GImGui;
9925 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9926 }
9927
9928 void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9929 {
9930 ImGuiContext& g = *GImGui;
9931 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9932 }
9933
9934 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9935 static const char* GetInputSourceName(ImGuiInputSource source)
9936 {
9937 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
9938 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9939 return input_source_names[source];
9940 }
9941 static const char* GetMouseSourceName(ImGuiMouseSource source)
9942 {
9943 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9944 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9945 return mouse_source_names[source];
9946 }
9947 static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9948 {
9949 ImGuiContext& g = *GImGui;
9950 if (e->Type == ImGuiInputEventType_MousePos) { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9951 if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9952 if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9953 if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9954 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9955 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9956 }
9957 #endif
9958
9959 // Process input queue
9960 // We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9961 // - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9962 // - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9963 void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9964 {
9965 ImGuiContext& g = *GImGui;
9966 ImGuiIO& io = g.IO;
9967
9968 // Only trickle chars<>key when working with InputText()
9969 // FIXME: InputText() could parse event trail?
9970 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9971 const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9972
9973 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
9974 int mouse_button_changed = 0x00;
9975 ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
9976
9977 int event_n = 0;
9978 for (; event_n < g.InputEventsQueue.Size; event_n++)
9979 {
9980 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9981 if (e->Type == ImGuiInputEventType_MousePos)
9982 {
9983 if (g.IO.WantSetMousePos)
9984 continue;
9985 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9986 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9987 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9988 break;
9989 io.MousePos = event_pos;
9990 io.MouseSource = e->MousePos.MouseSource;
9991 mouse_moved = true;
9992 }
9993 else if (e->Type == ImGuiInputEventType_MouseButton)
9994 {
9995 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9996 const ImGuiMouseButton button = e->MouseButton.Button;
9997 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9998 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9999 break;
10000 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10001 break;
10002 io.MouseDown[button] = e->MouseButton.Down;
10003 io.MouseSource = e->MouseButton.MouseSource;
10004 mouse_button_changed |= (1 << button);
10005 }
10006 else if (e->Type == ImGuiInputEventType_MouseWheel)
10007 {
10008 // Trickling Rule: Stop processing queued events if we got multiple action on the event
10009 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10010 break;
10011 io.MouseWheelH += e->MouseWheel.WheelX;
10012 io.MouseWheel += e->MouseWheel.WheelY;
10013 io.MouseSource = e->MouseWheel.MouseSource;
10014 mouse_wheeled = true;
10015 }
10016 else if (e->Type == ImGuiInputEventType_Key)
10017 {
10018 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10019 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10020 continue;
10021 ImGuiKey key = e->Key.Key;
10022 IM_ASSERT(key != ImGuiKey_None);
10023 ImGuiKeyData* key_data = GetKeyData(key);
10024 const int key_data_index = (int)(key_data - g.IO.KeysData);
10025 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || mouse_button_changed != 0))
10026 break;
10027
10028 const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(GetMergedModsFromKeys() | key);
10029 if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
10030 break;
10031
10032 key_data->Down = e->Key.Down;
10033 key_data->AnalogValue = e->Key.AnalogValue;
10034 key_changed = true;
10035 key_changed_mask.SetBit(key_data_index);
10036 if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
10037 key_changed_nonchar = true;
10038 }
10039 else if (e->Type == ImGuiInputEventType_Text)
10040 {
10041 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10042 continue;
10043 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10044 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10045 break;
10046 if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar)
10047 break;
10048 unsigned int c = e->Text.Char;
10049 io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10050 if (trickle_interleaved_nonchar_keys_and_text)
10051 text_inputted = true;
10052 }
10053 else if (e->Type == ImGuiInputEventType_Focus)
10054 {
10055 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10056 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10057 const bool focus_lost = !e->AppFocused.Focused;
10058 io.AppFocusLost = focus_lost;
10059 }
10060 else
10061 {
10062 IM_ASSERT(0 && "Unknown event!");
10063 }
10064 }
10065
10066 // Record trail (for domain-specific applications wanting to access a precise trail)
10067 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10068 for (int n = 0; n < event_n; n++)
10069 g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10070
10071 // [DEBUG]
10072 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
10073 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10074 for (int n = 0; n < g.InputEventsQueue.Size; n++)
10075 DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10076 #endif
10077
10078 // Remaining events will be processed on the next frame
10079 if (event_n == g.InputEventsQueue.Size)
10080 g.InputEventsQueue.resize(0);
10081 else
10082 g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10083
10084 // Clear buttons state when focus is lost
10085 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10086 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10087 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10088 if (g.IO.AppFocusLost)
10089 {
10090 g.IO.ClearInputKeys();
10091 g.IO.ClearInputMouse();
10092 }
10093 }
10094
10095 ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10096 {
10097 if (!IsNamedKeyOrMod(key))
10098 return ImGuiKeyOwner_NoOwner;
10099
10100 ImGuiContext& g = *GImGui;
10101 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10102 ImGuiID owner_id = owner_data->OwnerCurr;
10103
10104 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10105 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10106 return ImGuiKeyOwner_NoOwner;
10107
10108 return owner_id;
10109 }
10110
10111 // TestKeyOwner(..., ID) : (owner == None || owner == ID)
10112 // TestKeyOwner(..., None) : (owner == None)
10113 // TestKeyOwner(..., Any) : no owner test
10114 // All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10115 bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10116 {
10117 if (!IsNamedKeyOrMod(key))
10118 return true;
10119
10120 ImGuiContext& g = *GImGui;
10121 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10122 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10123 return false;
10124
10125 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10126 if (owner_id == ImGuiKeyOwner_Any)
10127 return (owner_data->LockThisFrame == false);
10128
10129 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10130 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10131 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10132 if (owner_data->OwnerCurr != owner_id)
10133 {
10134 if (owner_data->LockThisFrame)
10135 return false;
10136 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10137 return false;
10138 }
10139
10140 return true;
10141 }
10142
10143 // _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10144 // When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10145 // - SetKeyOwner(..., None) : clears owner
10146 // - SetKeyOwner(..., Any, !Lock) : illegal (assert)
10147 // - SetKeyOwner(..., Any or None, Lock) : set lock
10148 void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10149 {
10150 ImGuiContext& g = *GImGui;
10151 IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10152 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10153 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10154
10155 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10156 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10157
10158 // We cannot lock by default as it would likely break lots of legacy code.
10159 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10160 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10161 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10162 }
10163
10164 // Rarely used helper
10165 void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10166 {
10167 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10168 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10169 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10170 if (key_chord & ImGuiMod_Super) { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10171 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10172 }
10173
10174 // This is more or less equivalent to:
10175 // if (IsItemHovered() || IsItemActive())
10176 // SetKeyOwner(key, GetItemID());
10177 // Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10178 // More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10179 // Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10180 void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10181 {
10182 ImGuiContext& g = *GImGui;
10183 ImGuiID id = g.LastItemData.ID;
10184 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10185 return;
10186 if ((flags & ImGuiInputFlags_CondMask_) == 0)
10187 flags |= ImGuiInputFlags_CondDefault_;
10188 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10189 {
10190 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10191 SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10192 }
10193 }
10194
10195 void ImGui::SetItemKeyOwner(ImGuiKey key)
10196 {
10197 SetItemKeyOwner(key, ImGuiInputFlags_None);
10198 }
10199
10200 // This is the only public API until we expose owner_id versions of the API as replacements.
10201 bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10202 {
10203 return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10204 }
10205
10206 // This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10207 bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10208 {
10209 ImGuiContext& g = *GImGui;
10210 key_chord = FixupKeyChord(key_chord);
10211 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10212 if (g.IO.KeyMods != mods)
10213 return false;
10214
10215 // Special storage location for mods
10216 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10217 if (key == ImGuiKey_None)
10218 key = ConvertSingleModFlagToKey(mods);
10219 if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10220 return false;
10221 return true;
10222 }
10223
10224 void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10225 {
10226 ImGuiContext& g = *GImGui;
10227 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
10228 g.NextItemData.Shortcut = key_chord;
10229 g.NextItemData.ShortcutFlags = flags;
10230 }
10231
10232 // Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10233 void ImGui::ItemHandleShortcut(ImGuiID id)
10234 {
10235 ImGuiContext& g = *GImGui;
10236 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10237 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10238
10239 if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
10240 return;
10241 if (flags & ImGuiInputFlags_Tooltip)
10242 {
10243 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10244 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10245 }
10246 if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10247 return;
10248
10249 // FIXME: Generalize Activation queue?
10250 g.NavActivateId = id; // Will effectively disable clipping.
10251 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10252 //if (g.ActiveId == 0 || g.ActiveId == id)
10253 g.NavActivateDownId = g.NavActivatePressedId = id;
10254 NavHighlightActivated(id);
10255 }
10256
10257 bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10258 {
10259 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10260 }
10261
10262 bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10263 {
10264 ImGuiContext& g = *GImGui;
10265 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10266
10267 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10268 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10269 flags |= ImGuiInputFlags_RouteFocused;
10270
10271 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10272 // Effectively makes Shortcut() always input-owner aware.
10273 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10274 owner_id = GetRoutingIdFromOwnerId(owner_id);
10275
10276 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10277 return false;
10278
10279 // Submit route
10280 if (!SetShortcutRouting(key_chord, flags, owner_id))
10281 return false;
10282
10283 // Default repeat behavior for Shortcut()
10284 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10285 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10286 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10287
10288 if (!IsKeyChordPressed(key_chord, flags, owner_id))
10289 return false;
10290
10291 // Claim mods during the press
10292 SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10293
10294 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10295 return true;
10296 }
10297
10298
10299 //-----------------------------------------------------------------------------
10300 // [SECTION] ERROR CHECKING, STATE RECOVERY
10301 //-----------------------------------------------------------------------------
10302 // - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
10303 // - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10304 // - ErrorCheckNewFrameSanityChecks()
10305 // - ErrorCheckEndFrameSanityChecks()
10306 // - ErrorRecoveryStoreState()
10307 // - ErrorRecoveryTryToRecoverState()
10308 // - ErrorRecoveryTryToRecoverWindowState()
10309 // - ErrorLog()
10310 //-----------------------------------------------------------------------------
10311
10312 // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
10313 // Called by IMGUI_CHECKVERSION().
10314 // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10315 // If this triggers you have mismatched headers and compiled code versions.
10316 // - It could be because of a build issue (using new headers with old compiled code)
10317 // - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
10318 // THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
10319 // Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
10320 // Otherwise it is possible that different compilation units would see different structure layout.
10321 // If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
10322 bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10323 {
10324 bool error = false;
10325 if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10326 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10327 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10328 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10329 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10330 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10331 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10332 return !error;
10333 }
10334
10335 // Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10336 // This is causing issues and ambiguity and we need to retire that.
10337 // See https://github.com/ocornut/imgui/issues/5548 for more details.
10338 // [Scenario 1]
10339 // Previously this would make the window content size ~200x200:
10340 // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK
10341 // Instead, please submit an item:
10342 // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10343 // Alternative:
10344 // Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10345 // [Scenario 2]
10346 // For reference this is one of the issue what we aim to fix with this change:
10347 // BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10348 // The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10349 // While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10350 void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10351 {
10352 ImGuiContext& g = *GImGui;
10353 ImGuiWindow* window = g.CurrentWindow;
10354 IM_ASSERT(window->DC.IsSetPos);
10355 window->DC.IsSetPos = false;
10356 #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10357 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10358 return;
10359 if (window->SkipItems)
10360 return;
10361 IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10362 #else
10363 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10364 #endif
10365 }
10366
10367 static void ImGui::ErrorCheckNewFrameSanityChecks()
10368 {
10369 ImGuiContext& g = *GImGui;
10370
10371 // Check user IM_ASSERT macro
10372 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10373 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10374 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10375 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
10376 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
10377 if (true) IM_ASSERT(1); else IM_ASSERT(0);
10378
10379 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10380 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10381 #ifdef __EMSCRIPTEN__
10382 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10383 g.IO.DeltaTime = 0.00001f;
10384 #endif
10385
10386 // Check user data
10387 // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10388 IM_ASSERT(g.Initialized);
10389 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
10390 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10391 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
10392 IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10393 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
10394 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
10395 IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10396 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10397 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10398 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10399
10400 // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
10401 if (g.IO.ConfigErrorRecovery)
10402 IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
10403
10404 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10405 // Remap legacy names
10406 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
10407 {
10408 g.IO.ConfigNavMoveSetMousePos = true;
10409 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
10410 }
10411 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
10412 {
10413 g.IO.ConfigNavCaptureKeyboard = false;
10414 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
10415 }
10416
10417 // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
10418 if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
10419 g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
10420 if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
10421 g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); };
10422 #endif
10423 }
10424
10425 static void ImGui::ErrorCheckEndFrameSanityChecks()
10426 {
10427 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10428 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10429 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10430 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10431 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10432 // while still correctly asserting on mid-frame key press events.
10433 ImGuiContext& g = *GImGui;
10434 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10435 IM_UNUSED(g);
10436 IM_UNUSED(key_mods);
10437 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10438 IM_UNUSED(key_mods);
10439
10440 IM_ASSERT(g.CurrentWindowStack.Size == 1);
10441 IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
10442 }
10443
10444 // Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
10445 void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
10446 {
10447 ImGuiContext& g = *GImGui;
10448 state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
10449 state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
10450 state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
10451 state_out->SizeOfColorStack = (short)g.ColorStack.Size;
10452 state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10453 state_out->SizeOfFontStack = (short)g.FontStack.Size;
10454 state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10455 state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
10456 state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10457 state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10458 state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
10459 }
10460
10461 // Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
10462 // Called by e.g. EndFrame() but may be called for manual recovery.
10463 // Attempt to recover full window stack.
10464 void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
10465 {
10466 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10467 ImGuiContext& g = *GImGui;
10468 while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
10469 {
10470 // Recap:
10471 // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
10472 // - Always call a matching End() for each Begin() call, regardless of its return value!
10473 // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
10474 // - We will fix that in a future major update.
10475 ImGuiWindow* window = g.CurrentWindow;
10476 if (window->Flags & ImGuiWindowFlags_ChildWindow)
10477 {
10478 IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
10479 EndChild();
10480 }
10481 else
10482 {
10483 IM_ASSERT_USER_ERROR(0, "Missing End()");
10484 End();
10485 }
10486 }
10487 if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
10488 ErrorRecoveryTryToRecoverWindowState(state_in);
10489 }
10490
10491 // Called by e.g. End() but may be called for manual recovery.
10492 // Read '// Error Handling [BETA]' block in imgui_internal.h for details.
10493 // Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10494 void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
10495 {
10496 ImGuiContext& g = *GImGui;
10497
10498 while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
10499 {
10500 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
10501 EndTable();
10502 }
10503
10504 ImGuiWindow* window = g.CurrentWindow;
10505
10506 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10507 while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
10508 {
10509 IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
10510 EndTabBar();
10511 }
10512 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
10513 {
10514 IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
10515 EndMultiSelect();
10516 }
10517 while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
10518 {
10519 IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
10520 TreePop();
10521 }
10522 while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
10523 {
10524 IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
10525 EndGroup();
10526 }
10527 IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
10528 while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
10529 {
10530 IM_ASSERT_USER_ERROR(0, "Missing PopID()");
10531 PopID();
10532 }
10533 while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
10534 {
10535 IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
10536 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10537 EndDisabled();
10538 else
10539 {
10540 EndDisabledOverrideReenable();
10541 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10542 }
10543 }
10544 IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
10545 while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
10546 {
10547 IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
10548 PopStyleColor();
10549 }
10550 while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
10551 {
10552 IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
10553 PopItemFlag();
10554 }
10555 while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
10556 {
10557 IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
10558 PopStyleVar();
10559 }
10560 while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
10561 {
10562 IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
10563 PopFont();
10564 }
10565 while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
10566 {
10567 IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
10568 PopFocusScope();
10569 }
10570 //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
10571 }
10572
10573 bool ImGui::ErrorLog(const char* msg)
10574 {
10575 ImGuiContext& g = *GImGui;
10576
10577 // Output to debug log
10578 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
10579 ImGuiWindow* window = g.CurrentWindow;
10580
10581 if (g.IO.ConfigErrorRecoveryEnableDebugLog)
10582 {
10583 if (g.ErrorFirst)
10584 IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
10585 g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
10586 IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
10587 }
10588 g.ErrorFirst = false;
10589
10590 // Output to tooltip
10591 if (g.IO.ConfigErrorRecoveryEnableTooltip)
10592 {
10593 if (g.WithinFrameScope && BeginErrorTooltip())
10594 {
10595 if (g.ErrorCountCurrentFrame < 20)
10596 {
10597 Text("In window '%s': %s", window ? window->Name : "NULL", msg);
10598 if (window && (!window->IsFallbackWindow || window->WasActive))
10599 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
10600 }
10601 if (g.ErrorCountCurrentFrame == 20)
10602 Text("(and more errors)");
10603 // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
10604 EndErrorTooltip();
10605 }
10606 g.ErrorCountCurrentFrame++;
10607 }
10608 #endif
10609
10610 // Output to callback
10611 if (g.ErrorCallback != NULL)
10612 g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
10613
10614 // Return whether we should assert
10615 return g.IO.ConfigErrorRecoveryEnableAssert;
10616 }
10617
10618 void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
10619 {
10620 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
10621 ImGuiContext& g = *GImGui;
10622 if (g.DebugDrawIdConflicts != 0 && g.IO.KeyCtrl == false)
10623 g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
10624 if (g.DebugDrawIdConflicts != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
10625 {
10626 Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
10627 BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
10628 BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
10629 //BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused.
10630 BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
10631 Separator();
10632 Text("(Hold CTRL to: use");
10633 SameLine();
10634 if (SmallButton("Item Picker"))
10635 DebugStartItemPicker();
10636 SameLine();
10637 Text("to break in item call-stack, or");
10638 SameLine();
10639 if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
10640 g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
10641 EndErrorTooltip();
10642 }
10643
10644 if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
10645 {
10646 Separator();
10647 Text("(Hold CTRL to:");
10648 SameLine();
10649 if (SmallButton("Enable Asserts"))
10650 g.IO.ConfigErrorRecoveryEnableAssert = true;
10651 //SameLine();
10652 //if (SmallButton("Hide Error Tooltips"))
10653 // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
10654 SameLine(0, 0);
10655 Text(")");
10656 EndErrorTooltip();
10657 }
10658 #endif
10659 }
10660
10661 // Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it.
10662 bool ImGui::BeginErrorTooltip()
10663 {
10664 ImGuiContext& g = *GImGui;
10665 ImGuiWindow* window = FindWindowByName("##Tooltip_Error");
10666 const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
10667 PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.15f));
10668 if (use_locked_pos)
10669 SetNextWindowPos(g.ErrorTooltipLockedPos);
10670 bool is_visible = Begin("##Tooltip_Error", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
10671 PopStyleColor();
10672 if (is_visible && g.CurrentWindow->BeginCount == 1)
10673 {
10674 SeparatorText("MESSAGE FROM DEAR IMGUI");
10675 BringWindowToDisplayFront(g.CurrentWindow);
10676 BringWindowToFocusFront(g.CurrentWindow);
10677 g.ErrorTooltipLockedPos = GetWindowPos();
10678 }
10679 else if (!is_visible)
10680 {
10681 End();
10682 }
10683 return is_visible;
10684 }
10685
10686 void ImGui::EndErrorTooltip()
10687 {
10688 End();
10689 }
10690
10691 //-----------------------------------------------------------------------------
10692 // [SECTION] ITEM SUBMISSION
10693 //-----------------------------------------------------------------------------
10694 // - KeepAliveID()
10695 // - ItemAdd()
10696 //-----------------------------------------------------------------------------
10697
10698 // Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10699 void ImGui::KeepAliveID(ImGuiID id)
10700 {
10701 ImGuiContext& g = *GImGui;
10702 if (g.ActiveId == id)
10703 g.ActiveIdIsAlive = id;
10704 if (g.ActiveIdPreviousFrame == id)
10705 g.ActiveIdPreviousFrameIsAlive = true;
10706 }
10707
10708 // Declare item bounding box for clipping and interaction.
10709 // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10710 // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10711 // THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10712 IM_MSVC_RUNTIME_CHECKS_OFF
10713 bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10714 {
10715 ImGuiContext& g = *GImGui;
10716 ImGuiWindow* window = g.CurrentWindow;
10717
10718 // Set item data
10719 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10720 g.LastItemData.ID = id;
10721 g.LastItemData.Rect = bb;
10722 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10723 g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10724 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10725 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10726
10727 if (id != 0)
10728 {
10729 KeepAliveID(id);
10730
10731 // Directional navigation processing
10732 // Runs prior to clipping early-out
10733 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10734 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10735 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10736 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10737 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10738 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10739 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10740 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10741 if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
10742 {
10743 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10744 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10745 if (g.NavId == id || g.NavAnyRequest)
10746 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10747 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10748 NavProcessItem();
10749 }
10750
10751 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
10752 ItemHandleShortcut(id);
10753 }
10754
10755 // Lightweight clear of SetNextItemXXX data.
10756 g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
10757 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10758
10759 #ifdef IMGUI_ENABLE_TEST_ENGINE
10760 if (id != 0)
10761 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10762 #endif
10763
10764 // Clipping test
10765 // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10766 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10767 const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10768 if (!is_rect_visible)
10769 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10770 if (!g.ItemUnclipByLog)
10771 return false;
10772
10773 // [DEBUG]
10774 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
10775 if (id != 0)
10776 {
10777 if (id == g.DebugLocateId)
10778 DebugLocateItemResolveWithLastItem();
10779
10780 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10781 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10782 // READ THE FAQ: https://dearimgui.com/faq
10783 IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10784 }
10785 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10786 //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
10787 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10788 #endif
10789
10790 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10791 if (is_rect_visible)
10792 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10793 if (IsMouseHoveringRect(bb.Min, bb.Max))
10794 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10795 return true;
10796 }
10797 IM_MSVC_RUNTIME_CHECKS_RESTORE
10798
10799 //-----------------------------------------------------------------------------
10800 // [SECTION] LAYOUT
10801 //-----------------------------------------------------------------------------
10802 // - ItemSize()
10803 // - SameLine()
10804 // - GetCursorScreenPos()
10805 // - SetCursorScreenPos()
10806 // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10807 // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10808 // - GetCursorStartPos()
10809 // - Indent()
10810 // - Unindent()
10811 // - SetNextItemWidth()
10812 // - PushItemWidth()
10813 // - PushMultiItemsWidths()
10814 // - PopItemWidth()
10815 // - CalcItemWidth()
10816 // - CalcItemSize()
10817 // - GetTextLineHeight()
10818 // - GetTextLineHeightWithSpacing()
10819 // - GetFrameHeight()
10820 // - GetFrameHeightWithSpacing()
10821 // - GetContentRegionMax()
10822 // - GetContentRegionAvail(),
10823 // - BeginGroup()
10824 // - EndGroup()
10825 // Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10826 //-----------------------------------------------------------------------------
10827
10828 // Advance cursor given item size for layout.
10829 // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10830 // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10831 // THIS IS IN THE PERFORMANCE CRITICAL PATH.
10832 IM_MSVC_RUNTIME_CHECKS_OFF
10833 void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10834 {
10835 ImGuiContext& g = *GImGui;
10836 ImGuiWindow* window = g.CurrentWindow;
10837 if (window->SkipItems)
10838 return;
10839
10840 // We increase the height in this function to accommodate for baseline offset.
10841 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10842 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10843 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10844
10845 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10846 const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10847
10848 // Always align ourselves on pixel boundaries
10849 //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10850 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10851 window->DC.CursorPosPrevLine.y = line_y1;
10852 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
10853 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
10854 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10855 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10856 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10857
10858 window->DC.PrevLineSize.y = line_height;
10859 window->DC.CurrLineSize.y = 0.0f;
10860 window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10861 window->DC.CurrLineTextBaseOffset = 0.0f;
10862 window->DC.IsSameLine = window->DC.IsSetPos = false;
10863
10864 // Horizontal layout mode
10865 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10866 SameLine();
10867 }
10868 IM_MSVC_RUNTIME_CHECKS_RESTORE
10869
10870 // Gets back to previous line and continue with horizontal layout
10871 // offset_from_start_x == 0 : follow right after previous item
10872 // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10873 // spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10874 // spacing_w >= 0 : enforce spacing amount
10875 void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10876 {
10877 ImGuiContext& g = *GImGui;
10878 ImGuiWindow* window = g.CurrentWindow;
10879 if (window->SkipItems)
10880 return;
10881
10882 if (offset_from_start_x != 0.0f)
10883 {
10884 if (spacing_w < 0.0f)
10885 spacing_w = 0.0f;
10886 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10887 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10888 }
10889 else
10890 {
10891 if (spacing_w < 0.0f)
10892 spacing_w = g.Style.ItemSpacing.x;
10893 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10894 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10895 }
10896 window->DC.CurrLineSize = window->DC.PrevLineSize;
10897 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10898 window->DC.IsSameLine = true;
10899 }
10900
10901 ImVec2 ImGui::GetCursorScreenPos()
10902 {
10903 ImGuiWindow* window = GetCurrentWindowRead();
10904 return window->DC.CursorPos;
10905 }
10906
10907 void ImGui::SetCursorScreenPos(const ImVec2& pos)
10908 {
10909 ImGuiWindow* window = GetCurrentWindow();
10910 window->DC.CursorPos = pos;
10911 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10912 window->DC.IsSetPos = true;
10913 }
10914
10915 // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10916 // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10917 ImVec2 ImGui::GetCursorPos()
10918 {
10919 ImGuiWindow* window = GetCurrentWindowRead();
10920 return window->DC.CursorPos - window->Pos + window->Scroll;
10921 }
10922
10923 float ImGui::GetCursorPosX()
10924 {
10925 ImGuiWindow* window = GetCurrentWindowRead();
10926 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10927 }
10928
10929 float ImGui::GetCursorPosY()
10930 {
10931 ImGuiWindow* window = GetCurrentWindowRead();
10932 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10933 }
10934
10935 void ImGui::SetCursorPos(const ImVec2& local_pos)
10936 {
10937 ImGuiWindow* window = GetCurrentWindow();
10938 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10939 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10940 window->DC.IsSetPos = true;
10941 }
10942
10943 void ImGui::SetCursorPosX(float x)
10944 {
10945 ImGuiWindow* window = GetCurrentWindow();
10946 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10947 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10948 window->DC.IsSetPos = true;
10949 }
10950
10951 void ImGui::SetCursorPosY(float y)
10952 {
10953 ImGuiWindow* window = GetCurrentWindow();
10954 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10955 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10956 window->DC.IsSetPos = true;
10957 }
10958
10959 ImVec2 ImGui::GetCursorStartPos()
10960 {
10961 ImGuiWindow* window = GetCurrentWindowRead();
10962 return window->DC.CursorStartPos - window->Pos;
10963 }
10964
10965 void ImGui::Indent(float indent_w)
10966 {
10967 ImGuiContext& g = *GImGui;
10968 ImGuiWindow* window = GetCurrentWindow();
10969 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10970 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10971 }
10972
10973 void ImGui::Unindent(float indent_w)
10974 {
10975 ImGuiContext& g = *GImGui;
10976 ImGuiWindow* window = GetCurrentWindow();
10977 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10978 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10979 }
10980
10981 // Affect large frame+labels widgets only.
10982 void ImGui::SetNextItemWidth(float item_width)
10983 {
10984 ImGuiContext& g = *GImGui;
10985 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
10986 g.NextItemData.Width = item_width;
10987 }
10988
10989 // FIXME: Remove the == 0.0f behavior?
10990 void ImGui::PushItemWidth(float item_width)
10991 {
10992 ImGuiContext& g = *GImGui;
10993 ImGuiWindow* window = g.CurrentWindow;
10994 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10995 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10996 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
10997 }
10998
10999 void ImGui::PushMultiItemsWidths(int components, float w_full)
11000 {
11001 ImGuiContext& g = *GImGui;
11002 ImGuiWindow* window = g.CurrentWindow;
11003 IM_ASSERT(components > 0);
11004 const ImGuiStyle& style = g.Style;
11005 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11006 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11007 float prev_split = w_items;
11008 for (int i = components - 1; i > 0; i--)
11009 {
11010 float next_split = IM_TRUNC(w_items * i / components);
11011 window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11012 prev_split = next_split;
11013 }
11014 window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11015 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
11016 }
11017
11018 void ImGui::PopItemWidth()
11019 {
11020 ImGuiContext& g = *GImGui;
11021 ImGuiWindow* window = g.CurrentWindow;
11022 if (window->DC.ItemWidthStack.Size <= 0)
11023 {
11024 IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
11025 return;
11026 }
11027 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11028 window->DC.ItemWidthStack.pop_back();
11029 }
11030
11031 // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11032 // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11033 float ImGui::CalcItemWidth()
11034 {
11035 ImGuiContext& g = *GImGui;
11036 ImGuiWindow* window = g.CurrentWindow;
11037 float w;
11038 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
11039 w = g.NextItemData.Width;
11040 else
11041 w = window->DC.ItemWidth;
11042 if (w < 0.0f)
11043 {
11044 float region_avail_x = GetContentRegionAvail().x;
11045 w = ImMax(1.0f, region_avail_x + w);
11046 }
11047 w = IM_TRUNC(w);
11048 return w;
11049 }
11050
11051 // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11052 // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11053 // Note that only CalcItemWidth() is publicly exposed.
11054 // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11055 ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11056 {
11057 ImVec2 avail;
11058 if (size.x < 0.0f || size.y < 0.0f)
11059 avail = GetContentRegionAvail();
11060
11061 if (size.x == 0.0f)
11062 size.x = default_w;
11063 else if (size.x < 0.0f)
11064 size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting
11065
11066 if (size.y == 0.0f)
11067 size.y = default_h;
11068 else if (size.y < 0.0f)
11069 size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting
11070
11071 return size;
11072 }
11073
11074 float ImGui::GetTextLineHeight()
11075 {
11076 ImGuiContext& g = *GImGui;
11077 return g.FontSize;
11078 }
11079
11080 float ImGui::GetTextLineHeightWithSpacing()
11081 {
11082 ImGuiContext& g = *GImGui;
11083 return g.FontSize + g.Style.ItemSpacing.y;
11084 }
11085
11086 float ImGui::GetFrameHeight()
11087 {
11088 ImGuiContext& g = *GImGui;
11089 return g.FontSize + g.Style.FramePadding.y * 2.0f;
11090 }
11091
11092 float ImGui::GetFrameHeightWithSpacing()
11093 {
11094 ImGuiContext& g = *GImGui;
11095 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11096 }
11097
11098 ImVec2 ImGui::GetContentRegionAvail()
11099 {
11100 ImGuiContext& g = *GImGui;
11101 ImGuiWindow* window = g.CurrentWindow;
11102 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11103 return mx - window->DC.CursorPos;
11104 }
11105
11106 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11107
11108 // You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
11109 // They are bizarre local-coordinates which don't play well with scrolling.
11110 ImVec2 ImGui::GetContentRegionMax()
11111 {
11112 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
11113 }
11114
11115 ImVec2 ImGui::GetWindowContentRegionMin()
11116 {
11117 ImGuiWindow* window = GImGui->CurrentWindow;
11118 return window->ContentRegionRect.Min - window->Pos;
11119 }
11120
11121 ImVec2 ImGui::GetWindowContentRegionMax()
11122 {
11123 ImGuiWindow* window = GImGui->CurrentWindow;
11124 return window->ContentRegionRect.Max - window->Pos;
11125 }
11126 #endif
11127
11128 // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
11129 // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11130 // FIXME-OPT: Could we safely early out on ->SkipItems?
11131 void ImGui::BeginGroup()
11132 {
11133 ImGuiContext& g = *GImGui;
11134 ImGuiWindow* window = g.CurrentWindow;
11135
11136 g.GroupStack.resize(g.GroupStack.Size + 1);
11137 ImGuiGroupData& group_data = g.GroupStack.back();
11138 group_data.WindowID = window->ID;
11139 group_data.BackupCursorPos = window->DC.CursorPos;
11140 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11141 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11142 group_data.BackupIndent = window->DC.Indent;
11143 group_data.BackupGroupOffset = window->DC.GroupOffset;
11144 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11145 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11146 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11147 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11148 group_data.BackupIsSameLine = window->DC.IsSameLine;
11149 group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
11150 group_data.EmitItem = true;
11151
11152 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11153 window->DC.Indent = window->DC.GroupOffset;
11154 window->DC.CursorMaxPos = window->DC.CursorPos;
11155 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11156 if (g.LogEnabled)
11157 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11158 }
11159
11160 void ImGui::EndGroup()
11161 {
11162 ImGuiContext& g = *GImGui;
11163 ImGuiWindow* window = g.CurrentWindow;
11164 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11165
11166 ImGuiGroupData& group_data = g.GroupStack.back();
11167 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11168
11169 if (window->DC.IsSetPos)
11170 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11171
11172 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
11173 ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos));
11174 window->DC.CursorPos = group_data.BackupCursorPos;
11175 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11176 window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max);
11177 window->DC.Indent = group_data.BackupIndent;
11178 window->DC.GroupOffset = group_data.BackupGroupOffset;
11179 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11180 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11181 window->DC.IsSameLine = group_data.BackupIsSameLine;
11182 if (g.LogEnabled)
11183 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11184
11185 if (!group_data.EmitItem)
11186 {
11187 g.GroupStack.pop_back();
11188 return;
11189 }
11190
11191 window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11192 ItemSize(group_bb.GetSize());
11193 ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11194
11195 // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11196 // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11197 // Also if you grep for LastItemId you'll notice it is only used in that context.
11198 // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11199 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11200 const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11201 if (group_contains_curr_active_id)
11202 g.LastItemData.ID = g.ActiveId;
11203 else if (group_contains_prev_active_id)
11204 g.LastItemData.ID = g.ActiveIdPreviousFrame;
11205 g.LastItemData.Rect = group_bb;
11206
11207 // Forward Hovered flag
11208 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11209 if (group_contains_curr_hovered_id)
11210 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11211
11212 // Forward Edited flag
11213 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11214 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11215
11216 // Forward Deactivated flag
11217 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11218 if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11219 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11220
11221 g.GroupStack.pop_back();
11222 if (g.DebugShowGroupRects)
11223 window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
11224 }
11225
11226
11227 //-----------------------------------------------------------------------------
11228 // [SECTION] SCROLLING
11229 //-----------------------------------------------------------------------------
11230
11231 // Helper to snap on edges when aiming at an item very close to the edge,
11232 // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11233 // When we refactor the scrolling API this may be configurable with a flag?
11234 // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11235 static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11236 {
11237 if (target <= snap_min + snap_threshold)
11238 return ImLerp(snap_min, target, center_ratio);
11239 if (target >= snap_max - snap_threshold)
11240 return ImLerp(target, snap_max, center_ratio);
11241 return target;
11242 }
11243
11244 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11245 {
11246 ImVec2 scroll = window->Scroll;
11247 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11248 for (int axis = 0; axis < 2; axis++)
11249 {
11250 if (window->ScrollTarget[axis] < FLT_MAX)
11251 {
11252 float center_ratio = window->ScrollTargetCenterRatio[axis];
11253 float scroll_target = window->ScrollTarget[axis];
11254 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11255 {
11256 float snap_min = 0.0f;
11257 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11258 scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11259 }
11260 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11261 }
11262 scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11263 if (!window->Collapsed && !window->SkipItems)
11264 scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11265 }
11266 return scroll;
11267 }
11268
11269 void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11270 {
11271 ImGuiContext& g = *GImGui;
11272 ImGuiWindow* window = g.CurrentWindow;
11273 ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11274 }
11275
11276 void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11277 {
11278 ScrollToRectEx(window, item_rect, flags);
11279 }
11280
11281 // Scroll to keep newly navigated item fully into view
11282 ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11283 {
11284 ImGuiContext& g = *GImGui;
11285 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11286 scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11287 scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11288 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11289 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11290
11291 // Check that only one behavior is selected per axis
11292 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11293 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11294
11295 // Defaults
11296 ImGuiScrollFlags in_flags = flags;
11297 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11298 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11299 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11300 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11301
11302 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11303 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11304 const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11305 const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11306
11307 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11308 {
11309 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11310 SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11311 else if (item_rect.Max.x >= scroll_rect.Max.x)
11312 SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11313 }
11314 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11315 {
11316 if (can_be_fully_visible_x)
11317 SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11318 else
11319 SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11320 }
11321
11322 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11323 {
11324 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11325 SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11326 else if (item_rect.Max.y >= scroll_rect.Max.y)
11327 SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11328 }
11329 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11330 {
11331 if (can_be_fully_visible_y)
11332 SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11333 else
11334 SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11335 }
11336
11337 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11338 ImVec2 delta_scroll = next_scroll - window->Scroll;
11339
11340 // Also scroll parent window to keep us into view if necessary
11341 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11342 {
11343 // FIXME-SCROLL: May be an option?
11344 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11345 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11346 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11347 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11348 delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11349 }
11350
11351 return delta_scroll;
11352 }
11353
11354 float ImGui::GetScrollX()
11355 {
11356 ImGuiWindow* window = GImGui->CurrentWindow;
11357 return window->Scroll.x;
11358 }
11359
11360 float ImGui::GetScrollY()
11361 {
11362 ImGuiWindow* window = GImGui->CurrentWindow;
11363 return window->Scroll.y;
11364 }
11365
11366 float ImGui::GetScrollMaxX()
11367 {
11368 ImGuiWindow* window = GImGui->CurrentWindow;
11369 return window->ScrollMax.x;
11370 }
11371
11372 float ImGui::GetScrollMaxY()
11373 {
11374 ImGuiWindow* window = GImGui->CurrentWindow;
11375 return window->ScrollMax.y;
11376 }
11377
11378 void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11379 {
11380 window->ScrollTarget.x = scroll_x;
11381 window->ScrollTargetCenterRatio.x = 0.0f;
11382 window->ScrollTargetEdgeSnapDist.x = 0.0f;
11383 }
11384
11385 void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11386 {
11387 window->ScrollTarget.y = scroll_y;
11388 window->ScrollTargetCenterRatio.y = 0.0f;
11389 window->ScrollTargetEdgeSnapDist.y = 0.0f;
11390 }
11391
11392 void ImGui::SetScrollX(float scroll_x)
11393 {
11394 ImGuiContext& g = *GImGui;
11395 SetScrollX(g.CurrentWindow, scroll_x);
11396 }
11397
11398 void ImGui::SetScrollY(float scroll_y)
11399 {
11400 ImGuiContext& g = *GImGui;
11401 SetScrollY(g.CurrentWindow, scroll_y);
11402 }
11403
11404 // Note that a local position will vary depending on initial scroll value,
11405 // This is a little bit confusing so bear with us:
11406 // - local_pos = (absolution_pos - window->Pos)
11407 // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11408 // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11409 // - They mostly exist because of legacy API.
11410 // Following the rules above, when trying to work with scrolling code, consider that:
11411 // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11412 // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11413 // We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11414 void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11415 {
11416 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11417 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11418 window->ScrollTargetCenterRatio.x = center_x_ratio;
11419 window->ScrollTargetEdgeSnapDist.x = 0.0f;
11420 }
11421
11422 void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11423 {
11424 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11425 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11426 window->ScrollTargetCenterRatio.y = center_y_ratio;
11427 window->ScrollTargetEdgeSnapDist.y = 0.0f;
11428 }
11429
11430 void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11431 {
11432 ImGuiContext& g = *GImGui;
11433 SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11434 }
11435
11436 void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11437 {
11438 ImGuiContext& g = *GImGui;
11439 SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11440 }
11441
11442 // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11443 void ImGui::SetScrollHereX(float center_x_ratio)
11444 {
11445 ImGuiContext& g = *GImGui;
11446 ImGuiWindow* window = g.CurrentWindow;
11447 float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11448 float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11449 SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11450
11451 // Tweak: snap on edges when aiming at an item very close to the edge
11452 window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11453 }
11454
11455 // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11456 void ImGui::SetScrollHereY(float center_y_ratio)
11457 {
11458 ImGuiContext& g = *GImGui;
11459 ImGuiWindow* window = g.CurrentWindow;
11460 float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11461 float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11462 SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11463
11464 // Tweak: snap on edges when aiming at an item very close to the edge
11465 window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11466 }
11467
11468 //-----------------------------------------------------------------------------
11469 // [SECTION] TOOLTIPS
11470 //-----------------------------------------------------------------------------
11471
11472 bool ImGui::BeginTooltip()
11473 {
11474 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11475 }
11476
11477 bool ImGui::BeginItemTooltip()
11478 {
11479 if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11480 return false;
11481 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11482 }
11483
11484 bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11485 {
11486 ImGuiContext& g = *GImGui;
11487
11488 const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
11489 if (is_dragdrop_tooltip)
11490 {
11491 // Drag and Drop tooltips are positioning differently than other tooltips:
11492 // - offset visibility to increase visibility around mouse.
11493 // - never clamp within outer viewport boundary.
11494 // We call SetNextWindowPos() to enforce position and disable clamping.
11495 // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11496 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11497 const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
11498 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11499 {
11500 ImVec2 tooltip_pos = is_touchscreen ? (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale) : (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale);
11501 ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
11502 SetNextWindowPos(tooltip_pos, ImGuiCond_None, tooltip_pivot);
11503 }
11504
11505 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11506 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11507 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11508 }
11509
11510 const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
11511 char window_name[32];
11512 ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, g.TooltipOverrideCount);
11513 if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active)
11514 {
11515 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11516 //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
11517 SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
11518 ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, ++g.TooltipOverrideCount);
11519 }
11520 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
11521 Begin(window_name, NULL, flags | extra_window_flags);
11522 // 2023-03-09: Added bool return value to the API, but currently always returning true.
11523 // If this ever returns false we need to update BeginDragDropSource() accordingly.
11524 //if (!ret)
11525 // End();
11526 //return ret;
11527 return true;
11528 }
11529
11530 void ImGui::EndTooltip()
11531 {
11532 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
11533 End();
11534 }
11535
11536 void ImGui::SetTooltip(const char* fmt, ...)
11537 {
11538 va_list args;
11539 va_start(args, fmt);
11540 SetTooltipV(fmt, args);
11541 va_end(args);
11542 }
11543
11544 void ImGui::SetTooltipV(const char* fmt, va_list args)
11545 {
11546 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11547 return;
11548 TextV(fmt, args);
11549 EndTooltip();
11550 }
11551
11552 // Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11553 // Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11554 void ImGui::SetItemTooltip(const char* fmt, ...)
11555 {
11556 va_list args;
11557 va_start(args, fmt);
11558 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11559 SetTooltipV(fmt, args);
11560 va_end(args);
11561 }
11562
11563 void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11564 {
11565 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11566 SetTooltipV(fmt, args);
11567 }
11568
11569
11570 //-----------------------------------------------------------------------------
11571 // [SECTION] POPUPS
11572 //-----------------------------------------------------------------------------
11573
11574 // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11575 bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11576 {
11577 ImGuiContext& g = *GImGui;
11578 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11579 {
11580 // Return true if any popup is open at the current BeginPopup() level of the popup stack
11581 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11582 IM_ASSERT(id == 0);
11583 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11584 return g.OpenPopupStack.Size > 0;
11585 else
11586 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11587 }
11588 else
11589 {
11590 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11591 {
11592 // Return true if the popup is open anywhere in the popup stack
11593 for (int n = 0; n < g.OpenPopupStack.Size; n++)
11594 if (g.OpenPopupStack[n].PopupId == id)
11595 return true;
11596 return false;
11597 }
11598 else
11599 {
11600 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11601 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11602 }
11603 }
11604 }
11605
11606 bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11607 {
11608 ImGuiContext& g = *GImGui;
11609 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11610 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11611 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11612 return IsPopupOpen(id, popup_flags);
11613 }
11614
11615 // Also see FindBlockingModal(NULL)
11616 ImGuiWindow* ImGui::GetTopMostPopupModal()
11617 {
11618 ImGuiContext& g = *GImGui;
11619 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11620 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11621 if (popup->Flags & ImGuiWindowFlags_Modal)
11622 return popup;
11623 return NULL;
11624 }
11625
11626 // See Demo->Stacked Modal to confirm what this is for.
11627 ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11628 {
11629 ImGuiContext& g = *GImGui;
11630 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11631 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11632 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11633 return popup;
11634 return NULL;
11635 }
11636
11637 void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11638 {
11639 ImGuiContext& g = *GImGui;
11640 ImGuiID id = g.CurrentWindow->GetID(str_id);
11641 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11642 OpenPopupEx(id, popup_flags);
11643 }
11644
11645 void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11646 {
11647 OpenPopupEx(id, popup_flags);
11648 }
11649
11650 // Mark popup as open (toggle toward open state).
11651 // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11652 // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11653 // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11654 void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11655 {
11656 ImGuiContext& g = *GImGui;
11657 ImGuiWindow* parent_window = g.CurrentWindow;
11658 const int current_stack_size = g.BeginPopupStack.Size;
11659
11660 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11661 if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11662 return;
11663
11664 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11665 popup_ref.PopupId = id;
11666 popup_ref.Window = NULL;
11667 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
11668 popup_ref.OpenFrameCount = g.FrameCount;
11669 popup_ref.OpenParentId = parent_window->IDStack.back();
11670 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11671 popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11672
11673 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11674 if (g.OpenPopupStack.Size < current_stack_size + 1)
11675 {
11676 g.OpenPopupStack.push_back(popup_ref);
11677 }
11678 else
11679 {
11680 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11681 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11682 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11683 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11684 bool keep_existing = false;
11685 if (g.OpenPopupStack[current_stack_size].PopupId == id)
11686 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11687 keep_existing = true;
11688 if (keep_existing)
11689 {
11690 // No reopen
11691 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11692 }
11693 else
11694 {
11695 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11696 ClosePopupToLevel(current_stack_size, true);
11697 g.OpenPopupStack.push_back(popup_ref);
11698 }
11699
11700 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11701 // This is equivalent to what ClosePopupToLevel() does.
11702 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11703 // FocusWindow(parent_window);
11704 }
11705 }
11706
11707 // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11708 // This function closes any popups that are over 'ref_window'.
11709 void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11710 {
11711 ImGuiContext& g = *GImGui;
11712 if (g.OpenPopupStack.Size == 0)
11713 return;
11714
11715 // Don't close our own child popup windows.
11716 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11717 int popup_count_to_keep = 0;
11718 if (ref_window)
11719 {
11720 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11721 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11722 {
11723 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11724 if (!popup.Window)
11725 continue;
11726 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11727
11728 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11729 // - Clicking/Focusing Window2 won't close Popup1:
11730 // Window -> Popup1 -> Window2(Ref)
11731 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11732 // Window -> Popup1(Ref) -> Popup2 -> Popup3
11733 // - Each popups may contain child windows, which is why we compare ->RootWindow!
11734 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11735 // We step through every popup from bottom to top to validate their position relative to reference window.
11736 bool ref_window_is_descendent_of_popup = false;
11737 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11738 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11739 if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11740 {
11741 ref_window_is_descendent_of_popup = true;
11742 break;
11743 }
11744 if (!ref_window_is_descendent_of_popup)
11745 break;
11746 }
11747 }
11748 if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11749 {
11750 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11751 ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11752 }
11753 }
11754
11755 void ImGui::ClosePopupsExceptModals()
11756 {
11757 ImGuiContext& g = *GImGui;
11758
11759 int popup_count_to_keep;
11760 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11761 {
11762 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11763 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11764 break;
11765 }
11766 if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11767 ClosePopupToLevel(popup_count_to_keep, true);
11768 }
11769
11770 void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11771 {
11772 ImGuiContext& g = *GImGui;
11773 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11774 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11775 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)
11776 for (int n = remaining; n < g.OpenPopupStack.Size; n++)
11777 IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"\n", g.OpenPopupStack[n].PopupId, g.OpenPopupStack[n].Window ? g.OpenPopupStack[n].Window->Name : NULL);
11778
11779 // Trim open popup stack
11780 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11781 g.OpenPopupStack.resize(remaining);
11782
11783 // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11784 if (restore_focus_to_window_under_popup && prev_popup.Window)
11785 {
11786 ImGuiWindow* popup_window = prev_popup.Window;
11787 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11788 if (focus_window && !focus_window->WasActive)
11789 FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11790 else
11791 FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11792 }
11793 }
11794
11795 // Close the popup we have begin-ed into.
11796 void ImGui::CloseCurrentPopup()
11797 {
11798 ImGuiContext& g = *GImGui;
11799 int popup_idx = g.BeginPopupStack.Size - 1;
11800 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11801 return;
11802
11803 // Closing a menu closes its top-most parent popup (unless a modal)
11804 while (popup_idx > 0)
11805 {
11806 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11807 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11808 bool close_parent = false;
11809 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11810 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11811 close_parent = true;
11812 if (!close_parent)
11813 break;
11814 popup_idx--;
11815 }
11816 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11817 ClosePopupToLevel(popup_idx, true);
11818
11819 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11820 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11821 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11822 if (ImGuiWindow* window = g.NavWindow)
11823 window->DC.NavHideHighlightOneFrame = true;
11824 }
11825
11826 // Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
11827 bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
11828 {
11829 ImGuiContext& g = *GImGui;
11830 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11831 {
11832 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11833 return false;
11834 }
11835
11836 char name[20];
11837 if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
11838 ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11839 else
11840 ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11841
11842 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup);
11843 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11844 EndPopup();
11845
11846 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11847
11848 return is_open;
11849 }
11850
11851 bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11852 {
11853 ImGuiContext& g = *GImGui;
11854 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11855 {
11856 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11857 return false;
11858 }
11859 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11860 ImGuiID id = g.CurrentWindow->GetID(str_id);
11861 return BeginPopupEx(id, flags);
11862 }
11863
11864 // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11865 // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11866 // - *p_open set back to false in BeginPopupModal() when popup is not open.
11867 // - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11868 bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11869 {
11870 ImGuiContext& g = *GImGui;
11871 ImGuiWindow* window = g.CurrentWindow;
11872 const ImGuiID id = window->GetID(name);
11873 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11874 {
11875 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11876 if (p_open && *p_open)
11877 *p_open = false;
11878 return false;
11879 }
11880
11881 // Center modal windows by default for increased visibility
11882 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11883 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11884 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11885 {
11886 const ImGuiViewport* viewport = GetMainViewport();
11887 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11888 }
11889
11890 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
11891 const bool is_open = Begin(name, p_open, flags);
11892 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11893 {
11894 EndPopup();
11895 if (is_open)
11896 ClosePopupToLevel(g.BeginPopupStack.Size, true);
11897 return false;
11898 }
11899 return is_open;
11900 }
11901
11902 void ImGui::EndPopup()
11903 {
11904 ImGuiContext& g = *GImGui;
11905 ImGuiWindow* window = g.CurrentWindow;
11906 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
11907 IM_ASSERT(g.BeginPopupStack.Size > 0);
11908
11909 // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11910 if (g.NavWindow == window)
11911 NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11912
11913 // Child-popups don't need to be laid out
11914 IM_ASSERT(g.WithinEndChild == false);
11915 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11916 g.WithinEndChild = true;
11917 End();
11918 g.WithinEndChild = false;
11919 }
11920
11921 // Helper to open a popup if mouse button is released over the item
11922 // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11923 void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11924 {
11925 ImGuiContext& g = *GImGui;
11926 ImGuiWindow* window = g.CurrentWindow;
11927 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11928 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11929 {
11930 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11931 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11932 OpenPopupEx(id, popup_flags);
11933 }
11934 }
11935
11936 // This is a helper to handle the simplest case of associating one named popup to one given widget.
11937 // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11938 // - To create a popup with a specific identifier, pass it in str_id.
11939 // - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11940 // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11941 // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11942 // This is essentially the same as:
11943 // id = str_id ? GetID(str_id) : GetItemID();
11944 // OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11945 // return BeginPopup(id);
11946 // Which is essentially the same as:
11947 // id = str_id ? GetID(str_id) : GetItemID();
11948 // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11949 // OpenPopup(id);
11950 // return BeginPopup(id);
11951 // The main difference being that this is tweaked to avoid computing the ID twice.
11952 bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11953 {
11954 ImGuiContext& g = *GImGui;
11955 ImGuiWindow* window = g.CurrentWindow;
11956 if (window->SkipItems)
11957 return false;
11958 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11959 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11960 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11961 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11962 OpenPopupEx(id, popup_flags);
11963 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11964 }
11965
11966 bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11967 {
11968 ImGuiContext& g = *GImGui;
11969 ImGuiWindow* window = g.CurrentWindow;
11970 if (!str_id)
11971 str_id = "window_context";
11972 ImGuiID id = window->GetID(str_id);
11973 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11974 if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11975 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11976 OpenPopupEx(id, popup_flags);
11977 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11978 }
11979
11980 bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11981 {
11982 ImGuiContext& g = *GImGui;
11983 ImGuiWindow* window = g.CurrentWindow;
11984 if (!str_id)
11985 str_id = "void_context";
11986 ImGuiID id = window->GetID(str_id);
11987 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11988 if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11989 if (GetTopMostPopupModal() == NULL)
11990 OpenPopupEx(id, popup_flags);
11991 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11992 }
11993
11994 // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11995 // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11996 // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11997 // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11998 // this allows us to have tooltips/popups displayed out of the parent viewport.)
11999 ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12000 {
12001 ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12002 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12003 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12004
12005 // Combo Box policy (we want a connecting edge)
12006 if (policy == ImGuiPopupPositionPolicy_ComboBox)
12007 {
12008 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12009 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12010 {
12011 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12012 if (n != -1 && dir == *last_dir) // Already tried this direction?
12013 continue;
12014 ImVec2 pos;
12015 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
12016 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12017 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12018 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12019 if (!r_outer.Contains(ImRect(pos, pos + size)))
12020 continue;
12021 *last_dir = dir;
12022 return pos;
12023 }
12024 }
12025
12026 // Tooltip and Default popup policy
12027 // (Always first try the direction we used on the last frame, if any)
12028 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12029 {
12030 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12031 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12032 {
12033 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12034 if (n != -1 && dir == *last_dir) // Already tried this direction?
12035 continue;
12036
12037 const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
12038 const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
12039
12040 // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
12041 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12042 continue;
12043 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12044 continue;
12045
12046 ImVec2 pos;
12047 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12048 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12049
12050 // Clamp top-left corner of popup
12051 pos.x = ImMax(pos.x, r_outer.Min.x);
12052 pos.y = ImMax(pos.y, r_outer.Min.y);
12053
12054 *last_dir = dir;
12055 return pos;
12056 }
12057 }
12058
12059 // Fallback when not enough room:
12060 *last_dir = ImGuiDir_None;
12061
12062 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12063 if (policy == ImGuiPopupPositionPolicy_Tooltip)
12064 return ref_pos + ImVec2(2, 2);
12065
12066 // Otherwise try to keep within display
12067 ImVec2 pos = ref_pos;
12068 pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12069 pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12070 return pos;
12071 }
12072
12073 // Note that this is used for popups, which can overlap the non work-area of individual viewports.
12074 ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12075 {
12076 ImGuiContext& g = *GImGui;
12077 IM_UNUSED(window);
12078 ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
12079 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12080 r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12081 return r_screen;
12082 }
12083
12084 ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12085 {
12086 ImGuiContext& g = *GImGui;
12087
12088 ImRect r_outer = GetPopupAllowedExtentRect(window);
12089 if (window->Flags & ImGuiWindowFlags_ChildMenu)
12090 {
12091 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12092 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12093 IM_ASSERT(g.CurrentWindow == window);
12094 ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;
12095 float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
12096 ImRect r_avoid;
12097 if (parent_window->DC.MenuBarAppending)
12098 r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
12099 else
12100 r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
12101 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12102 }
12103 if (window->Flags & ImGuiWindowFlags_Popup)
12104 {
12105 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12106 }
12107 if (window->Flags & ImGuiWindowFlags_Tooltip)
12108 {
12109 // Position tooltip (always follows mouse + clamp within outer boundaries)
12110 // FIXME:
12111 // - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default).
12112 // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
12113 // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
12114 // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
12115 IM_ASSERT(g.CurrentWindow == window);
12116 const float scale = g.Style.MouseCursorScale;
12117 const ImVec2 ref_pos = NavCalcPreferredRefPos();
12118
12119 if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
12120 {
12121 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
12122 if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
12123 return tooltip_pos;
12124 }
12125
12126 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
12127 ImRect r_avoid;
12128 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
12129 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12130 else
12131 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
12132 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12133
12134 return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
12135 }
12136 IM_ASSERT(0);
12137 return window->Pos;
12138 }
12139
12140 //-----------------------------------------------------------------------------
12141 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
12142 //-----------------------------------------------------------------------------
12143
12144 // FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
12145 // In our terminology those should be interchangeable, yet right now this is super confusing.
12146 // Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
12147
12148 void ImGui::SetNavCursorVisible(bool visible)
12149 {
12150 ImGuiContext& g = *GImGui;
12151 if (g.IO.ConfigNavCursorVisibleAlways)
12152 visible = true;
12153 g.NavCursorVisible = visible;
12154 }
12155
12156 // (was called NavRestoreHighlightAfterMove() before 1.91.4)
12157 void ImGui::SetNavCursorVisibleAfterMove()
12158 {
12159 ImGuiContext& g = *GImGui;
12160 if (g.IO.ConfigNavCursorVisibleAuto)
12161 g.NavCursorVisible = true;
12162 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
12163 }
12164
12165 void ImGui::SetNavWindow(ImGuiWindow* window)
12166 {
12167 ImGuiContext& g = *GImGui;
12168 if (g.NavWindow != window)
12169 {
12170 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
12171 g.NavWindow = window;
12172 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12173 }
12174 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12175 NavUpdateAnyRequestFlag();
12176 }
12177
12178 void ImGui::NavHighlightActivated(ImGuiID id)
12179 {
12180 ImGuiContext& g = *GImGui;
12181 g.NavHighlightActivatedId = id;
12182 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12183 }
12184
12185 void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12186 {
12187 ImGuiContext& g = *GImGui;
12188 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12189 }
12190
12191 void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12192 {
12193 ImGuiContext& g = *GImGui;
12194 IM_ASSERT(g.NavWindow != NULL);
12195 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12196 g.NavId = id;
12197 g.NavLayer = nav_layer;
12198 SetNavFocusScope(focus_scope_id);
12199 g.NavWindow->NavLastIds[nav_layer] = id;
12200 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12201
12202 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12203 NavClearPreferredPosForAxis(ImGuiAxis_X);
12204 NavClearPreferredPosForAxis(ImGuiAxis_Y);
12205 }
12206
12207 void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12208 {
12209 ImGuiContext& g = *GImGui;
12210 IM_ASSERT(id != 0);
12211
12212 if (g.NavWindow != window)
12213 SetNavWindow(window);
12214
12215 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12216 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12217 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12218 g.NavId = id;
12219 g.NavLayer = nav_layer;
12220 SetNavFocusScope(g.CurrentFocusScopeId);
12221 window->NavLastIds[nav_layer] = id;
12222 if (g.LastItemData.ID == id)
12223 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12224
12225 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12226 g.NavHighlightItemUnderNav = true;
12227 else if (g.IO.ConfigNavCursorVisibleAuto)
12228 g.NavCursorVisible = false;
12229
12230 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12231 NavClearPreferredPosForAxis(ImGuiAxis_X);
12232 NavClearPreferredPosForAxis(ImGuiAxis_Y);
12233 }
12234
12235 static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12236 {
12237 if (ImFabs(dx) > ImFabs(dy))
12238 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12239 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12240 }
12241
12242 static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12243 {
12244 if (cand_max < curr_min)
12245 return cand_max - curr_min;
12246 if (curr_max < cand_min)
12247 return cand_min - curr_max;
12248 return 0.0f;
12249 }
12250
12251 // Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
12252 static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12253 {
12254 ImGuiContext& g = *GImGui;
12255 ImGuiWindow* window = g.CurrentWindow;
12256 if (g.NavLayer != window->DC.NavLayerCurrent)
12257 return false;
12258
12259 // FIXME: Those are not good variables names
12260 ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
12261 const ImRect curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12262 g.NavScoringDebugCount++;
12263
12264 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12265 if (window->ParentWindow == g.NavWindow)
12266 {
12267 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
12268 if (!window->ClipRect.Overlaps(cand))
12269 return false;
12270 cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12271 }
12272
12273 // Compute distance between boxes
12274 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12275 float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12276 float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12277 if (dby != 0.0f && dbx != 0.0f)
12278 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12279 float dist_box = ImFabs(dbx) + ImFabs(dby);
12280
12281 // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12282 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12283 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12284 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12285
12286 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12287 ImGuiDir quadrant;
12288 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12289 if (dbx != 0.0f || dby != 0.0f)
12290 {
12291 // For non-overlapping boxes, use distance between boxes
12292 // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y
12293 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
12294 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
12295 dax = dbx;
12296 day = dby;
12297 dist_axial = dist_box;
12298 quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12299 }
12300 else if (dcx != 0.0f || dcy != 0.0f)
12301 {
12302 // For overlapping boxes with different centers, use distance between centers
12303 dax = dcx;
12304 day = dcy;
12305 dist_axial = dist_center;
12306 quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12307 }
12308 else
12309 {
12310 // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12311 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12312 }
12313
12314 const ImGuiDir move_dir = g.NavMoveDir;
12315 #if IMGUI_DEBUG_NAV_SCORING
12316 char buf[200];
12317 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12318 {
12319 if (quadrant == move_dir)
12320 {
12321 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12322 ImDrawList* draw_list = GetForegroundDrawList(window);
12323 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12324 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12325 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12326 }
12327 }
12328 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12329 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12330 if (debug_hovering || debug_tty)
12331 {
12332 ImFormatString(buf, IM_ARRAYSIZE(buf),
12333 "d-box (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12334 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12335 if (debug_hovering)
12336 {
12337 ImDrawList* draw_list = GetForegroundDrawList(window);
12338 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12339 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12340 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12341 draw_list->AddText(cand.Max, ~0U, buf);
12342 }
12343 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12344 }
12345 #endif
12346
12347 // Is it in the quadrant we're interested in moving to?
12348 bool new_best = false;
12349 if (quadrant == move_dir)
12350 {
12351 // Does it beat the current best candidate?
12352 if (dist_box < result->DistBox)
12353 {
12354 result->DistBox = dist_box;
12355 result->DistCenter = dist_center;
12356 return true;
12357 }
12358 if (dist_box == result->DistBox)
12359 {
12360 // Try using distance between center points to break ties
12361 if (dist_center < result->DistCenter)
12362 {
12363 result->DistCenter = dist_center;
12364 new_best = true;
12365 }
12366 else if (dist_center == result->DistCenter)
12367 {
12368 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12369 // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12370 // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12371 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12372 new_best = true;
12373 }
12374 }
12375 }
12376
12377 // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12378 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12379 // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12380 // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12381 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12382 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
12383 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12384 if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12385 {
12386 result->DistAxial = dist_axial;
12387 new_best = true;
12388 }
12389
12390 return new_best;
12391 }
12392
12393 static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12394 {
12395 ImGuiContext& g = *GImGui;
12396 ImGuiWindow* window = g.CurrentWindow;
12397 result->Window = window;
12398 result->ID = g.LastItemData.ID;
12399 result->FocusScopeId = g.CurrentFocusScopeId;
12400 result->ItemFlags = g.LastItemData.ItemFlags;
12401 result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12402 if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
12403 {
12404 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12405 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12406 }
12407 }
12408
12409 // True when current work location may be scrolled horizontally when moving left / right.
12410 // This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12411 void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12412 {
12413 ImGuiContext& g = *GImGui;
12414 ImGuiWindow* window = g.CurrentWindow;
12415 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12416 }
12417
12418 // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12419 // This is called after LastItemData is set, but NextItemData is also still valid.
12420 static void ImGui::NavProcessItem()
12421 {
12422 ImGuiContext& g = *GImGui;
12423 ImGuiWindow* window = g.CurrentWindow;
12424 const ImGuiID id = g.LastItemData.ID;
12425 const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
12426
12427 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12428 if (window->DC.NavIsScrollPushableX == false)
12429 {
12430 g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12431 g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12432 }
12433 const ImRect nav_bb = g.LastItemData.NavRect;
12434
12435 // Process Init Request
12436 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12437 {
12438 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12439 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12440 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12441 {
12442 NavApplyItemToResult(&g.NavInitResult);
12443 }
12444 if (candidate_for_nav_default_focus)
12445 {
12446 g.NavInitRequest = false; // Found a match, clear request
12447 NavUpdateAnyRequestFlag();
12448 }
12449 }
12450
12451 // Process Move Request (scoring for navigation)
12452 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12453 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12454 {
12455 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12456 {
12457 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12458 if (is_tabbing)
12459 {
12460 NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12461 }
12462 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12463 {
12464 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12465 if (NavScoreItem(result))
12466 NavApplyItemToResult(result);
12467
12468 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12469 const float VISIBLE_RATIO = 0.70f;
12470 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12471 if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12472 if (NavScoreItem(&g.NavMoveResultLocalVisible))
12473 NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12474 }
12475 }
12476 }
12477
12478 // Update information for currently focused/navigated item
12479 if (g.NavId == id)
12480 {
12481 if (g.NavWindow != window)
12482 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12483 g.NavLayer = window->DC.NavLayerCurrent;
12484 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12485 g.NavFocusScopeId = g.CurrentFocusScopeId;
12486 g.NavIdIsAlive = true;
12487 if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
12488 {
12489 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12490 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12491 }
12492 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12493 }
12494 }
12495
12496 // Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12497 // Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12498 // - Case 1: no nav/active id: set result to first eligible item, stop storing.
12499 // - Case 2: tab forward: on ref id set counter, on counter elapse store result
12500 // - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12501 // - Case 4: tab backward: store all results, on ref id pick prev, stop storing
12502 // - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12503 void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12504 {
12505 ImGuiContext& g = *GImGui;
12506
12507 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12508 {
12509 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12510 return;
12511 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12512 return;
12513 }
12514
12515 // - Can always land on an item when using API call.
12516 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12517 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12518 bool can_stop;
12519 if (move_flags & ImGuiNavMoveFlags_FocusApi)
12520 can_stop = true;
12521 else
12522 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12523
12524 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12525 ImGuiNavItemData* result = &g.NavMoveResultLocal;
12526 if (g.NavTabbingDir == +1)
12527 {
12528 // Tab Forward or SetKeyboardFocusHere() with >= 0
12529 if (can_stop && g.NavTabbingResultFirst.ID == 0)
12530 NavApplyItemToResult(&g.NavTabbingResultFirst);
12531 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12532 NavMoveRequestResolveWithLastItem(result);
12533 else if (g.NavId == id)
12534 g.NavTabbingCounter = 1;
12535 }
12536 else if (g.NavTabbingDir == -1)
12537 {
12538 // Tab Backward
12539 if (g.NavId == id)
12540 {
12541 if (result->ID)
12542 {
12543 g.NavMoveScoringItems = false;
12544 NavUpdateAnyRequestFlag();
12545 }
12546 }
12547 else if (can_stop)
12548 {
12549 // Keep applying until reaching NavId
12550 NavApplyItemToResult(result);
12551 }
12552 }
12553 else if (g.NavTabbingDir == 0)
12554 {
12555 if (can_stop && g.NavId == id)
12556 NavMoveRequestResolveWithLastItem(result);
12557 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12558 NavApplyItemToResult(&g.NavTabbingResultFirst);
12559 }
12560 }
12561
12562 bool ImGui::NavMoveRequestButNoResultYet()
12563 {
12564 ImGuiContext& g = *GImGui;
12565 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12566 }
12567
12568 // FIXME: ScoringRect is not set
12569 void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12570 {
12571 ImGuiContext& g = *GImGui;
12572 IM_ASSERT(g.NavWindow != NULL);
12573 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
12574
12575 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12576 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12577
12578 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12579 g.NavMoveDir = move_dir;
12580 g.NavMoveDirForDebug = move_dir;
12581 g.NavMoveClipDir = clip_dir;
12582 g.NavMoveFlags = move_flags;
12583 g.NavMoveScrollFlags = scroll_flags;
12584 g.NavMoveForwardToNextFrame = false;
12585 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12586 g.NavMoveResultLocal.Clear();
12587 g.NavMoveResultLocalVisible.Clear();
12588 g.NavMoveResultOther.Clear();
12589 g.NavTabbingCounter = 0;
12590 g.NavTabbingResultFirst.Clear();
12591 NavUpdateAnyRequestFlag();
12592 }
12593
12594 void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12595 {
12596 ImGuiContext& g = *GImGui;
12597 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12598 NavApplyItemToResult(result);
12599 NavUpdateAnyRequestFlag();
12600 }
12601
12602 // Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12603 void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data)
12604 {
12605 ImGuiContext& g = *GImGui;
12606 g.NavMoveScoringItems = false;
12607 g.LastItemData.ID = tree_node_data->ID;
12608 g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12609 g.LastItemData.NavRect = tree_node_data->NavRect;
12610 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12611 NavClearPreferredPosForAxis(ImGuiAxis_Y);
12612 NavUpdateAnyRequestFlag();
12613 }
12614
12615 void ImGui::NavMoveRequestCancel()
12616 {
12617 ImGuiContext& g = *GImGui;
12618 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12619 NavUpdateAnyRequestFlag();
12620 }
12621
12622 // Forward will reuse the move request again on the next frame (generally with modifications done to it)
12623 void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12624 {
12625 ImGuiContext& g = *GImGui;
12626 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12627 NavMoveRequestCancel();
12628 g.NavMoveForwardToNextFrame = true;
12629 g.NavMoveDir = move_dir;
12630 g.NavMoveClipDir = clip_dir;
12631 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12632 g.NavMoveScrollFlags = scroll_flags;
12633 }
12634
12635 // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12636 // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12637 void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12638 {
12639 ImGuiContext& g = *GImGui;
12640 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12641
12642 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12643 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12644 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12645 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12646 }
12647
12648 // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12649 // This way we could find the last focused window among our children. It would be much less confusing this way?
12650 static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12651 {
12652 ImGuiWindow* parent = nav_window;
12653 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12654 parent = parent->ParentWindow;
12655 if (parent && parent != nav_window)
12656 parent->NavLastChildNavWindow = nav_window;
12657 }
12658
12659 // Restore the last focused child.
12660 // Call when we are expected to land on the Main Layer (0) after FocusWindow()
12661 static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12662 {
12663 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12664 return window->NavLastChildNavWindow;
12665 return window;
12666 }
12667
12668 void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12669 {
12670 ImGuiContext& g = *GImGui;
12671 if (layer == ImGuiNavLayer_Main)
12672 {
12673 ImGuiWindow* prev_nav_window = g.NavWindow;
12674 g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
12675 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12676 if (prev_nav_window)
12677 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12678 }
12679 ImGuiWindow* window = g.NavWindow;
12680 if (window->NavLastIds[layer] != 0)
12681 {
12682 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12683 }
12684 else
12685 {
12686 g.NavLayer = layer;
12687 NavInitWindow(window, true);
12688 }
12689 }
12690
12691 static inline void ImGui::NavUpdateAnyRequestFlag()
12692 {
12693 ImGuiContext& g = *GImGui;
12694 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12695 if (g.NavAnyRequest)
12696 IM_ASSERT(g.NavWindow != NULL);
12697 }
12698
12699 // This needs to be called before we submit any widget (aka in or before Begin)
12700 void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12701 {
12702 ImGuiContext& g = *GImGui;
12703 IM_ASSERT(window == g.NavWindow);
12704
12705 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12706 {
12707 g.NavId = 0;
12708 SetNavFocusScope(window->NavRootFocusScopeId);
12709 return;
12710 }
12711
12712 bool init_for_nav = false;
12713 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12714 init_for_nav = true;
12715 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12716 if (init_for_nav)
12717 {
12718 SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12719 g.NavInitRequest = true;
12720 g.NavInitRequestFromMove = false;
12721 g.NavInitResult.ID = 0;
12722 NavUpdateAnyRequestFlag();
12723 }
12724 else
12725 {
12726 g.NavId = window->NavLastIds[0];
12727 SetNavFocusScope(window->NavRootFocusScopeId);
12728 }
12729 }
12730
12731 static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
12732 {
12733 ImGuiContext& g = *GImGui;
12734 ImGuiWindow* window = g.NavWindow;
12735 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12736
12737 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12738 if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut)
12739 return ImGuiInputSource_Mouse;
12740 else
12741 return ImGuiInputSource_Keyboard; // or Nav in general
12742 }
12743
12744 static ImVec2 ImGui::NavCalcPreferredRefPos()
12745 {
12746 ImGuiContext& g = *GImGui;
12747 ImGuiWindow* window = g.NavWindow;
12748 ImGuiInputSource source = NavCalcPreferredRefPosSource();
12749
12750 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12751
12752 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12753 if (source == ImGuiInputSource_Mouse)
12754 {
12755 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12756 // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12757 // In theory we could move that +1.0f offset in OpenPopupEx()
12758 ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12759 return ImVec2(p.x + 1.0f, p.y);
12760 }
12761 else
12762 {
12763 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12764 ImRect ref_rect;
12765 if (activated_shortcut)
12766 ref_rect = g.LastItemData.NavRect;
12767 else
12768 ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12769
12770 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12771 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12772 {
12773 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12774 ref_rect.Translate(window->Scroll - next_scroll);
12775 }
12776 ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
12777 ImGuiViewport* viewport = GetMainViewport();
12778 return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12779 }
12780 }
12781
12782 float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12783 {
12784 ImGuiContext& g = *GImGui;
12785 float repeat_delay, repeat_rate;
12786 GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12787
12788 ImGuiKey key_less, key_more;
12789 if (g.NavInputSource == ImGuiInputSource_Gamepad)
12790 {
12791 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12792 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12793 }
12794 else
12795 {
12796 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12797 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12798 }
12799 float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12800 if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12801 amount = 0.0f;
12802 return amount;
12803 }
12804
12805 static void ImGui::NavUpdate()
12806 {
12807 ImGuiContext& g = *GImGui;
12808 ImGuiIO& io = g.IO;
12809
12810 io.WantSetMousePos = false;
12811 //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12812
12813 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12814 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12815 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12816 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12817 if (nav_gamepad_active)
12818 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12819 if (IsKeyDown(key))
12820 g.NavInputSource = ImGuiInputSource_Gamepad;
12821 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12822 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12823 if (nav_keyboard_active)
12824 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12825 if (IsKeyDown(key))
12826 g.NavInputSource = ImGuiInputSource_Keyboard;
12827
12828 // Process navigation init request (select first/default focus)
12829 g.NavJustMovedToId = 0;
12830 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
12831 if (g.NavInitResult.ID != 0)
12832 NavInitRequestApplyResult();
12833 g.NavInitRequest = false;
12834 g.NavInitRequestFromMove = false;
12835 g.NavInitResult.ID = 0;
12836
12837 // Process navigation move request
12838 if (g.NavMoveSubmitted)
12839 NavMoveRequestApplyResult();
12840 g.NavTabbingCounter = 0;
12841 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12842 if (g.NavCursorHideFrames > 0)
12843 if (--g.NavCursorHideFrames == 0)
12844 g.NavCursorVisible = true;
12845
12846 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12847 bool set_mouse_pos = false;
12848 if (g.NavMousePosDirty && g.NavIdIsAlive)
12849 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
12850 set_mouse_pos = true;
12851 g.NavMousePosDirty = false;
12852 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12853
12854 // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12855 if (g.NavWindow)
12856 NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12857 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12858 g.NavWindow->NavLastChildNavWindow = NULL;
12859
12860 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12861 NavUpdateWindowing();
12862
12863 // Set output flags for user application
12864 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12865 io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
12866
12867 // Process NavCancel input (to close a popup, get back to parent, clear focus)
12868 NavUpdateCancelRequest();
12869
12870 // Process manual activation request
12871 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12872 g.NavActivateFlags = ImGuiActivateFlags_None;
12873 if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12874 {
12875 const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
12876 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
12877 const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
12878 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
12879 if (g.ActiveId == 0 && activate_pressed)
12880 {
12881 g.NavActivateId = g.NavId;
12882 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12883 }
12884 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12885 {
12886 g.NavActivateId = g.NavId;
12887 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12888 }
12889 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12890 g.NavActivateDownId = g.NavId;
12891 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12892 {
12893 g.NavActivatePressedId = g.NavId;
12894 NavHighlightActivated(g.NavId);
12895 }
12896 }
12897 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12898 g.NavCursorVisible = false;
12899 else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
12900 g.NavCursorVisible = true;
12901 if (g.NavActivateId != 0)
12902 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12903
12904 // Highlight
12905 if (g.NavHighlightActivatedTimer > 0.0f)
12906 g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
12907 if (g.NavHighlightActivatedTimer == 0.0f)
12908 g.NavHighlightActivatedId = 0;
12909
12910 // Process programmatic activation request
12911 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12912 if (g.NavNextActivateId != 0)
12913 {
12914 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12915 g.NavActivateFlags = g.NavNextActivateFlags;
12916 }
12917 g.NavNextActivateId = 0;
12918
12919 // Process move requests
12920 NavUpdateCreateMoveRequest();
12921 if (g.NavMoveDir == ImGuiDir_None)
12922 NavUpdateCreateTabbingRequest();
12923 NavUpdateAnyRequestFlag();
12924 g.NavIdIsAlive = false;
12925
12926 // Scrolling
12927 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12928 {
12929 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12930 ImGuiWindow* window = g.NavWindow;
12931 const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12932 const ImGuiDir move_dir = g.NavMoveDir;
12933 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12934 {
12935 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12936 SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12937 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12938 SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12939 }
12940
12941 // *Normal* Manual scroll with LStick
12942 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12943 if (nav_gamepad_active)
12944 {
12945 const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12946 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12947 if (scroll_dir.x != 0.0f && window->ScrollbarX)
12948 SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12949 if (scroll_dir.y != 0.0f)
12950 SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12951 }
12952 }
12953
12954 // Always prioritize mouse highlight if navigation is disabled
12955 if (!nav_keyboard_active && !nav_gamepad_active)
12956 {
12957 g.NavCursorVisible = false;
12958 g.NavHighlightItemUnderNav = set_mouse_pos = false;
12959 }
12960
12961 // Update mouse position if requested
12962 // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12963 if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12964 TeleportMousePos(NavCalcPreferredRefPos());
12965
12966 // [DEBUG]
12967 g.NavScoringDebugCount = 0;
12968 #if IMGUI_DEBUG_NAV_RECTS
12969 if (ImGuiWindow* debug_window = g.NavWindow)
12970 {
12971 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12972 int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12973 //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12974 }
12975 #endif
12976 }
12977
12978 void ImGui::NavInitRequestApplyResult()
12979 {
12980 // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12981 ImGuiContext& g = *GImGui;
12982 if (!g.NavWindow)
12983 return;
12984
12985 ImGuiNavItemData* result = &g.NavInitResult;
12986 if (g.NavId != result->ID)
12987 {
12988 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
12989 g.NavJustMovedToId = result->ID;
12990 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12991 g.NavJustMovedToKeyMods = 0;
12992 g.NavJustMovedToIsTabbing = false;
12993 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
12994 }
12995
12996 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12997 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12998 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12999 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13000 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
13001 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13002 g.NavLastValidSelectionUserData = result->SelectionUserData;
13003 if (g.NavInitRequestFromMove)
13004 SetNavCursorVisibleAfterMove();
13005 }
13006
13007 // Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
13008 static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
13009 {
13010 // Bias initial rect
13011 ImGuiContext& g = *GImGui;
13012 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
13013
13014 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
13015 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
13016 // - But each successful move sets new bias on one axis, only cleared when using mouse.
13017 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
13018 {
13019 if (preferred_pos_rel.x == FLT_MAX)
13020 preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
13021 if (preferred_pos_rel.y == FLT_MAX)
13022 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
13023 }
13024
13025 // Apply general bias on the other axis
13026 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
13027 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
13028 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
13029 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
13030 }
13031
13032 void ImGui::NavUpdateCreateMoveRequest()
13033 {
13034 ImGuiContext& g = *GImGui;
13035 ImGuiIO& io = g.IO;
13036 ImGuiWindow* window = g.NavWindow;
13037 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13038 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13039
13040 if (g.NavMoveForwardToNextFrame && window != NULL)
13041 {
13042 // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
13043 // (preserve most state, which were already set by the NavMoveRequestForward() function)
13044 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
13045 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
13046 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
13047 }
13048 else
13049 {
13050 // Initiate directional inputs request
13051 g.NavMoveDir = ImGuiDir_None;
13052 g.NavMoveFlags = ImGuiNavMoveFlags_None;
13053 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
13054 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
13055 {
13056 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
13057 if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
13058 if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
13059 if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
13060 if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
13061 }
13062 g.NavMoveClipDir = g.NavMoveDir;
13063 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
13064 }
13065
13066 // Update PageUp/PageDown/Home/End scroll
13067 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
13068 float scoring_rect_offset_y = 0.0f;
13069 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
13070 scoring_rect_offset_y = NavUpdatePageUpPageDown();
13071 if (scoring_rect_offset_y != 0.0f)
13072 {
13073 g.NavScoringNoClipRect = window->InnerRect;
13074 g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
13075 }
13076
13077 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
13078 #if IMGUI_DEBUG_NAV_SCORING
13079 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
13080 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
13081 if (io.KeyCtrl)
13082 {
13083 if (g.NavMoveDir == ImGuiDir_None)
13084 g.NavMoveDir = g.NavMoveDirForDebug;
13085 g.NavMoveClipDir = g.NavMoveDir;
13086 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
13087 }
13088 #endif
13089
13090 // Submit
13091 g.NavMoveForwardToNextFrame = false;
13092 if (g.NavMoveDir != ImGuiDir_None)
13093 NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
13094
13095 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
13096 if (g.NavMoveSubmitted && g.NavId == 0)
13097 {
13098 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
13099 g.NavInitRequest = g.NavInitRequestFromMove = true;
13100 g.NavInitResult.ID = 0;
13101 if (g.IO.ConfigNavCursorVisibleAuto)
13102 g.NavCursorVisible = true;
13103 }
13104
13105 // When using gamepad, we project the reference nav bounding box into window visible area.
13106 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
13107 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
13108 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
13109 {
13110 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
13111 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
13112 ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
13113
13114 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
13115 // Otherwise 'inner_rect_rel' would be off on the move result frame.
13116 inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
13117
13118 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
13119 {
13120 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
13121 float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
13122 float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
13123 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
13124 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
13125 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
13126 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
13127 window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
13128 g.NavId = 0;
13129 }
13130 }
13131
13132 // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
13133 ImRect scoring_rect;
13134 if (window != NULL)
13135 {
13136 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
13137 scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
13138 scoring_rect.TranslateY(scoring_rect_offset_y);
13139 if (g.NavMoveSubmitted)
13140 NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
13141 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
13142 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
13143 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
13144 }
13145 g.NavScoringRect = scoring_rect;
13146 g.NavScoringNoClipRect.Add(scoring_rect);
13147 }
13148
13149 void ImGui::NavUpdateCreateTabbingRequest()
13150 {
13151 ImGuiContext& g = *GImGui;
13152 ImGuiWindow* window = g.NavWindow;
13153 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
13154 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
13155 return;
13156
13157 const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
13158 if (!tab_pressed)
13159 return;
13160
13161 // Initiate tabbing request
13162 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
13163 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
13164 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13165 if (nav_keyboard_active)
13166 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
13167 else
13168 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
13169 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
13170 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
13171 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
13172 NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
13173 g.NavTabbingCounter = -1;
13174 }
13175
13176 // Apply result from previous frame navigation directional move request. Always called from NavUpdate()
13177 void ImGui::NavMoveRequestApplyResult()
13178 {
13179 ImGuiContext& g = *GImGui;
13180 #if IMGUI_DEBUG_NAV_SCORING
13181 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
13182 return;
13183 #endif
13184
13185 // Select which result to use
13186 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
13187
13188 // Tabbing forward wrap
13189 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
13190 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
13191 result = &g.NavTabbingResultFirst;
13192
13193 // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
13194 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13195 if (result == NULL)
13196 {
13197 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13198 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
13199 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
13200 SetNavCursorVisibleAfterMove();
13201 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
13202 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
13203 return;
13204 }
13205
13206 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13207 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13208 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13209 result = &g.NavMoveResultLocalVisible;
13210
13211 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13212 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13213 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13214 result = &g.NavMoveResultOther;
13215 IM_ASSERT(g.NavWindow && result->Window);
13216
13217 // Scroll to keep newly navigated item fully into view.
13218 if (g.NavLayer == ImGuiNavLayer_Main)
13219 {
13220 ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13221 ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13222
13223 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13224 {
13225 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13226 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13227 SetScrollY(result->Window, scroll_target);
13228 }
13229 }
13230
13231 if (g.NavWindow != result->Window)
13232 {
13233 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13234 g.NavWindow = result->Window;
13235 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13236 }
13237
13238 // Clear active id unless requested not to
13239 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13240 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13241 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13242 ClearActiveID();
13243
13244 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13245 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13246 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13247 {
13248 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13249 g.NavJustMovedToId = result->ID;
13250 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13251 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13252 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13253 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13254 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
13255 }
13256
13257 // Apply new NavID/Focus
13258 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13259 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13260 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13261 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13262 g.NavLastValidSelectionUserData = result->SelectionUserData;
13263
13264 // Restore last preferred position for current axis
13265 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13266 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13267 {
13268 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13269 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13270 }
13271
13272 // Tabbing: Activates Inputable, otherwise only Focus
13273 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
13274 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13275
13276 // Activate
13277 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13278 {
13279 g.NavNextActivateId = result->ID;
13280 g.NavNextActivateFlags = ImGuiActivateFlags_None;
13281 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13282 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13283 }
13284
13285 // Make nav cursor visible
13286 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
13287 SetNavCursorVisibleAfterMove();
13288 }
13289
13290 // Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
13291 // FIXME: In order to support e.g. Escape to clear a selection we'll need:
13292 // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13293 // - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13294 static void ImGui::NavUpdateCancelRequest()
13295 {
13296 ImGuiContext& g = *GImGui;
13297 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13298 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13299 if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
13300 return;
13301
13302 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13303 if (g.ActiveId != 0)
13304 {
13305 ClearActiveID();
13306 }
13307 else if (g.NavLayer != ImGuiNavLayer_Main)
13308 {
13309 // Leave the "menu" layer
13310 NavRestoreLayer(ImGuiNavLayer_Main);
13311 SetNavCursorVisibleAfterMove();
13312 }
13313 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13314 {
13315 // Exit child window
13316 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13317 ImGuiWindow* parent_window = child_window->ParentWindow;
13318 IM_ASSERT(child_window->ChildId != 0);
13319 FocusWindow(parent_window);
13320 SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13321 SetNavCursorVisibleAfterMove();
13322 }
13323 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13324 {
13325 // Close open popup/menu
13326 ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13327 }
13328 else
13329 {
13330 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13331 // FIXME-NAV: This should happen on window appearing.
13332 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
13333 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13334 g.NavWindow->NavLastIds[0] = 0;
13335
13336 // Clear nav focus
13337 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
13338 g.NavId = 0;
13339 if (g.IO.ConfigNavEscapeClearFocusWindow)
13340 FocusWindow(NULL);
13341 }
13342 }
13343
13344 // Handle PageUp/PageDown/Home/End keys
13345 // Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13346 // FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13347 // FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13348 static float ImGui::NavUpdatePageUpPageDown()
13349 {
13350 ImGuiContext& g = *GImGui;
13351 ImGuiWindow* window = g.NavWindow;
13352 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13353 return 0.0f;
13354
13355 const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
13356 const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
13357 const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13358 const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13359 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13360 return 0.0f;
13361
13362 if (g.NavLayer != ImGuiNavLayer_Main)
13363 NavRestoreLayer(ImGuiNavLayer_Main);
13364
13365 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13366 {
13367 // Fallback manual-scroll when window has no navigable item
13368 if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13369 SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13370 else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13371 SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13372 else if (home_pressed)
13373 SetScrollY(window, 0.0f);
13374 else if (end_pressed)
13375 SetScrollY(window, window->ScrollMax.y);
13376 }
13377 else
13378 {
13379 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13380 const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13381 float nav_scoring_rect_offset_y = 0.0f;
13382 if (IsKeyPressed(ImGuiKey_PageUp, true))
13383 {
13384 nav_scoring_rect_offset_y = -page_offset_y;
13385 g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13386 g.NavMoveClipDir = ImGuiDir_Up;
13387 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13388 }
13389 else if (IsKeyPressed(ImGuiKey_PageDown, true))
13390 {
13391 nav_scoring_rect_offset_y = +page_offset_y;
13392 g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13393 g.NavMoveClipDir = ImGuiDir_Down;
13394 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13395 }
13396 else if (home_pressed)
13397 {
13398 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13399 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13400 // Preserve current horizontal position if we have any.
13401 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13402 if (nav_rect_rel.IsInverted())
13403 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13404 g.NavMoveDir = ImGuiDir_Down;
13405 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13406 // FIXME-NAV: MoveClipDir left to _None, intentional?
13407 }
13408 else if (end_pressed)
13409 {
13410 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13411 if (nav_rect_rel.IsInverted())
13412 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13413 g.NavMoveDir = ImGuiDir_Up;
13414 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13415 // FIXME-NAV: MoveClipDir left to _None, intentional?
13416 }
13417 return nav_scoring_rect_offset_y;
13418 }
13419 return 0.0f;
13420 }
13421
13422 static void ImGui::NavEndFrame()
13423 {
13424 ImGuiContext& g = *GImGui;
13425
13426 // Show CTRL+TAB list window
13427 if (g.NavWindowingTarget != NULL)
13428 NavUpdateWindowingOverlay();
13429
13430 // Perform wrap-around in menus
13431 // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13432 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13433 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13434 NavUpdateCreateWrappingRequest();
13435 }
13436
13437 static void ImGui::NavUpdateCreateWrappingRequest()
13438 {
13439 ImGuiContext& g = *GImGui;
13440 ImGuiWindow* window = g.NavWindow;
13441
13442 bool do_forward = false;
13443 ImRect bb_rel = window->NavRectRel[g.NavLayer];
13444 ImGuiDir clip_dir = g.NavMoveDir;
13445
13446 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13447 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13448 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13449 {
13450 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13451 if (move_flags & ImGuiNavMoveFlags_WrapX)
13452 {
13453 bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13454 clip_dir = ImGuiDir_Up;
13455 }
13456 do_forward = true;
13457 }
13458 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13459 {
13460 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13461 if (move_flags & ImGuiNavMoveFlags_WrapX)
13462 {
13463 bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13464 clip_dir = ImGuiDir_Down;
13465 }
13466 do_forward = true;
13467 }
13468 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13469 {
13470 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13471 if (move_flags & ImGuiNavMoveFlags_WrapY)
13472 {
13473 bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13474 clip_dir = ImGuiDir_Left;
13475 }
13476 do_forward = true;
13477 }
13478 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13479 {
13480 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13481 if (move_flags & ImGuiNavMoveFlags_WrapY)
13482 {
13483 bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13484 clip_dir = ImGuiDir_Right;
13485 }
13486 do_forward = true;
13487 }
13488 if (!do_forward)
13489 return;
13490 window->NavRectRel[g.NavLayer] = bb_rel;
13491 NavClearPreferredPosForAxis(ImGuiAxis_X);
13492 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13493 NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13494 }
13495
13496 static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13497 {
13498 ImGuiContext& g = *GImGui;
13499 IM_UNUSED(g);
13500 int order = window->FocusOrder;
13501 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13502 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13503 return order;
13504 }
13505
13506 static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13507 {
13508 ImGuiContext& g = *GImGui;
13509 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13510 if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13511 return g.WindowsFocusOrder[i];
13512 return NULL;
13513 }
13514
13515 static void NavUpdateWindowingTarget(int focus_change_dir)
13516 {
13517 ImGuiContext& g = *GImGui;
13518 IM_ASSERT(g.NavWindowingTarget);
13519 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13520 return;
13521
13522 const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13523 ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13524 if (!window_target)
13525 window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13526 if (window_target) // Don't reset windowing target if there's a single window in the list
13527 {
13528 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13529 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13530 }
13531 g.NavWindowingToggleLayer = false;
13532 }
13533
13534 // Windowing management mode
13535 // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13536 // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13537 static void ImGui::NavUpdateWindowing()
13538 {
13539 ImGuiContext& g = *GImGui;
13540 ImGuiIO& io = g.IO;
13541
13542 ImGuiWindow* apply_focus_window = NULL;
13543 bool apply_toggle_layer = false;
13544
13545 ImGuiWindow* modal_window = GetTopMostPopupModal();
13546 bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13547 if (!allow_windowing)
13548 g.NavWindowingTarget = NULL;
13549
13550 // Fade out
13551 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13552 {
13553 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13554 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13555 g.NavWindowingTargetAnim = NULL;
13556 }
13557
13558 // Start CTRL+Tab or Square+L/R window selection
13559 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13560 const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13561 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13562 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13563 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13564 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13565 const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
13566 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13567 bool just_started_windowing_from_null_focus = false;
13568 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13569 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13570 {
13571 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
13572 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13573 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13574 g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13575 g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13576 if (g.NavWindow == NULL)
13577 just_started_windowing_from_null_focus = true;
13578
13579 // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13580 if (keyboard_next_window || keyboard_prev_window)
13581 SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13582 }
13583
13584 // Gamepad update
13585 g.NavWindowingTimer += io.DeltaTime;
13586 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13587 {
13588 // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13589 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13590
13591 // Select window to focus
13592 const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13593 if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
13594 {
13595 NavUpdateWindowingTarget(focus_change_dir);
13596 g.NavWindowingHighlightAlpha = 1.0f;
13597 }
13598
13599 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13600 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13601 {
13602 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13603 if (g.NavWindowingToggleLayer && g.NavWindow)
13604 apply_toggle_layer = true;
13605 else if (!g.NavWindowingToggleLayer)
13606 apply_focus_window = g.NavWindowingTarget;
13607 g.NavWindowingTarget = NULL;
13608 }
13609 }
13610
13611 // Keyboard: Focus
13612 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13613 {
13614 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13615 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13616 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13617 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13618 if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
13619 NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1);
13620 else if ((io.KeyMods & shared_mods) != shared_mods)
13621 apply_focus_window = g.NavWindowingTarget;
13622 }
13623
13624 // Keyboard: Press and Release ALT to toggle menu layer
13625 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13626 bool windowing_toggle_layer_start = false;
13627 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13628 if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
13629 {
13630 windowing_toggle_layer_start = true;
13631 g.NavWindowingToggleLayer = true;
13632 g.NavWindowingToggleKey = windowing_toggle_key;
13633 g.NavInputSource = ImGuiInputSource_Keyboard;
13634 break;
13635 }
13636 if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13637 {
13638 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13639 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13640 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13641 // We cancel toggling nav layer if an owner has claimed the key.
13642 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13643 g.NavWindowingToggleLayer = false;
13644 else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time)
13645 g.NavWindowingToggleLayer = false;
13646 else if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13647 g.NavWindowingToggleLayer = false;
13648
13649 // Apply layer toggle on Alt release
13650 // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13651 if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13652 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13653 if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13654 apply_toggle_layer = true;
13655 if (!IsKeyDown(g.NavWindowingToggleKey))
13656 g.NavWindowingToggleLayer = false;
13657 }
13658
13659 // Move window
13660 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13661 {
13662 ImVec2 nav_move_dir;
13663 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13664 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13665 if (g.NavInputSource == ImGuiInputSource_Gamepad)
13666 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13667 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13668 {
13669 const float NAV_MOVE_SPEED = 800.0f;
13670 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13671 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13672 g.NavHighlightItemUnderNav = true;
13673 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13674 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13675 {
13676 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
13677 SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13678 g.NavWindowingAccumDeltaPos -= accum_floored;
13679 }
13680 }
13681 }
13682
13683 // Apply final focus
13684 if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13685 {
13686 ClearActiveID();
13687 SetNavCursorVisibleAfterMove();
13688 ClosePopupsOverWindow(apply_focus_window, false);
13689 FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13690 apply_focus_window = g.NavWindow;
13691 if (apply_focus_window->NavLastIds[0] == 0)
13692 NavInitWindow(apply_focus_window, false);
13693
13694 // If the window has ONLY a menu layer (no main layer), select it directly
13695 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13696 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13697 // the target window as already been previewed once.
13698 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13699 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13700 // won't be valid.
13701 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13702 g.NavLayer = ImGuiNavLayer_Menu;
13703 }
13704 if (apply_focus_window)
13705 g.NavWindowingTarget = NULL;
13706
13707 // Apply menu/layer toggle
13708 if (apply_toggle_layer && g.NavWindow)
13709 {
13710 ClearActiveID();
13711
13712 // Move to parent menu if necessary
13713 ImGuiWindow* new_nav_window = g.NavWindow;
13714 while (new_nav_window->ParentWindow
13715 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13716 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13717 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13718 new_nav_window = new_nav_window->ParentWindow;
13719 if (new_nav_window != g.NavWindow)
13720 {
13721 ImGuiWindow* old_nav_window = g.NavWindow;
13722 FocusWindow(new_nav_window);
13723 new_nav_window->NavLastChildNavWindow = old_nav_window;
13724 }
13725
13726 // Toggle layer
13727 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13728 if (new_nav_layer != g.NavLayer)
13729 {
13730 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13731 if (new_nav_layer == ImGuiNavLayer_Menu)
13732 g.NavWindow->NavLastIds[new_nav_layer] = 0;
13733 NavRestoreLayer(new_nav_layer);
13734 SetNavCursorVisibleAfterMove();
13735 }
13736 }
13737 }
13738
13739 // Window has already passed the IsWindowNavFocusable()
13740 static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13741 {
13742 if (window->Flags & ImGuiWindowFlags_Popup)
13743 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13744 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13745 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13746 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13747 }
13748
13749 // Overlay displayed when using CTRL+TAB. Called by EndFrame().
13750 void ImGui::NavUpdateWindowingOverlay()
13751 {
13752 ImGuiContext& g = *GImGui;
13753 IM_ASSERT(g.NavWindowingTarget != NULL);
13754
13755 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13756 return;
13757
13758 if (g.NavWindowingListWindow == NULL)
13759 g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13760 const ImGuiViewport* viewport = GetMainViewport();
13761 SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13762 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13763 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13764 Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13765 if (g.ContextName[0] != 0)
13766 SeparatorText(g.ContextName);
13767 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13768 {
13769 ImGuiWindow* window = g.WindowsFocusOrder[n];
13770 IM_ASSERT(window != NULL); // Fix static analyzers
13771 if (!IsWindowNavFocusable(window))
13772 continue;
13773 const char* label = window->Name;
13774 if (label == FindRenderedTextEnd(label))
13775 label = GetFallbackWindowNameForWindowingList(window);
13776 Selectable(label, g.NavWindowingTarget == window);
13777 }
13778 End();
13779 PopStyleVar();
13780 }
13781
13782
13783 //-----------------------------------------------------------------------------
13784 // [SECTION] DRAG AND DROP
13785 //-----------------------------------------------------------------------------
13786
13787 bool ImGui::IsDragDropActive()
13788 {
13789 ImGuiContext& g = *GImGui;
13790 return g.DragDropActive;
13791 }
13792
13793 void ImGui::ClearDragDrop()
13794 {
13795 ImGuiContext& g = *GImGui;
13796 if (g.DragDropActive)
13797 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13798 g.DragDropActive = false;
13799 g.DragDropPayload.Clear();
13800 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13801 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13802 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13803 g.DragDropAcceptFrameCount = -1;
13804
13805 g.DragDropPayloadBufHeap.clear();
13806 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13807 }
13808
13809 bool ImGui::BeginTooltipHidden()
13810 {
13811 ImGuiContext& g = *GImGui;
13812 bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13813 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13814 return ret;
13815 }
13816
13817 // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13818 // If the item has an identifier:
13819 // - This assume/require the item to be activated (typically via ButtonBehavior).
13820 // - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13821 // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13822 // If the item has no identifier:
13823 // - Currently always assume left mouse button.
13824 bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13825 {
13826 ImGuiContext& g = *GImGui;
13827 ImGuiWindow* window = g.CurrentWindow;
13828
13829 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13830 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13831 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13832
13833 bool source_drag_active = false;
13834 ImGuiID source_id = 0;
13835 ImGuiID source_parent_id = 0;
13836 if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13837 {
13838 source_id = g.LastItemData.ID;
13839 if (source_id != 0)
13840 {
13841 // Common path: items with ID
13842 if (g.ActiveId != source_id)
13843 return false;
13844 if (g.ActiveIdMouseButton != -1)
13845 mouse_button = g.ActiveIdMouseButton;
13846 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13847 return false;
13848 g.ActiveIdAllowOverlap = false;
13849 }
13850 else
13851 {
13852 // Uncommon path: items without ID
13853 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13854 return false;
13855 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13856 return false;
13857
13858 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13859 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13860 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13861 {
13862 IM_ASSERT(0);
13863 return false;
13864 }
13865
13866 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13867 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13868 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13869 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13870 // Rely on keeping other window->LastItemXXX fields intact.
13871 source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13872 KeepAliveID(source_id);
13873 bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.ItemFlags);
13874 if (is_hovered && g.IO.MouseClicked[mouse_button])
13875 {
13876 SetActiveID(source_id, window);
13877 FocusWindow(window);
13878 }
13879 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13880 g.ActiveIdAllowOverlap = is_hovered;
13881 }
13882 if (g.ActiveId != source_id)
13883 return false;
13884 source_parent_id = window->IDStack.back();
13885 source_drag_active = IsMouseDragging(mouse_button);
13886
13887 // Disable navigation and key inputs while dragging + cancel existing request if any
13888 SetActiveIdUsingAllKeyboardKeys();
13889 }
13890 else
13891 {
13892 // When ImGuiDragDropFlags_SourceExtern is set:
13893 window = NULL;
13894 source_id = ImHashStr("#SourceExtern");
13895 source_drag_active = true;
13896 mouse_button = g.IO.MouseDown[0] ? 0 : -1;
13897 KeepAliveID(source_id);
13898 SetActiveID(source_id, NULL);
13899 }
13900
13901 IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13902 if (!source_drag_active)
13903 return false;
13904
13905 // Activate drag and drop
13906 if (!g.DragDropActive)
13907 {
13908 IM_ASSERT(source_id != 0);
13909 ClearDragDrop();
13910 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
13911 source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
13912 ImGuiPayload& payload = g.DragDropPayload;
13913 payload.SourceId = source_id;
13914 payload.SourceParentId = source_parent_id;
13915 g.DragDropActive = true;
13916 g.DragDropSourceFlags = flags;
13917 g.DragDropMouseButton = mouse_button;
13918 if (payload.SourceId == g.ActiveId)
13919 g.ActiveIdNoClearOnFocusLoss = true;
13920 }
13921 g.DragDropSourceFrameCount = g.FrameCount;
13922 g.DragDropWithinSource = true;
13923
13924 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13925 {
13926 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13927 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13928 bool ret;
13929 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13930 ret = BeginTooltipHidden();
13931 else
13932 ret = BeginTooltip();
13933 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13934 IM_UNUSED(ret);
13935 }
13936
13937 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13938 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13939
13940 return true;
13941 }
13942
13943 void ImGui::EndDragDropSource()
13944 {
13945 ImGuiContext& g = *GImGui;
13946 IM_ASSERT(g.DragDropActive);
13947 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13948
13949 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13950 EndTooltip();
13951
13952 // Discard the drag if have not called SetDragDropPayload()
13953 if (g.DragDropPayload.DataFrameCount == -1)
13954 ClearDragDrop();
13955 g.DragDropWithinSource = false;
13956 }
13957
13958 // Use 'cond' to choose to submit payload on drag start or every frame
13959 bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13960 {
13961 ImGuiContext& g = *GImGui;
13962 ImGuiPayload& payload = g.DragDropPayload;
13963 if (cond == 0)
13964 cond = ImGuiCond_Always;
13965
13966 IM_ASSERT(type != NULL);
13967 IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13968 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13969 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13970 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
13971
13972 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13973 {
13974 // Copy payload
13975 ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13976 g.DragDropPayloadBufHeap.resize(0);
13977 if (data_size > sizeof(g.DragDropPayloadBufLocal))
13978 {
13979 // Store in heap
13980 g.DragDropPayloadBufHeap.resize((int)data_size);
13981 payload.Data = g.DragDropPayloadBufHeap.Data;
13982 memcpy(payload.Data, data, data_size);
13983 }
13984 else if (data_size > 0)
13985 {
13986 // Store locally
13987 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13988 payload.Data = g.DragDropPayloadBufLocal;
13989 memcpy(payload.Data, data, data_size);
13990 }
13991 else
13992 {
13993 payload.Data = NULL;
13994 }
13995 payload.DataSize = (int)data_size;
13996 }
13997 payload.DataFrameCount = g.FrameCount;
13998
13999 // Return whether the payload has been accepted
14000 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
14001 }
14002
14003 bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
14004 {
14005 ImGuiContext& g = *GImGui;
14006 if (!g.DragDropActive)
14007 return false;
14008
14009 ImGuiWindow* window = g.CurrentWindow;
14010 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14011 if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
14012 return false;
14013 IM_ASSERT(id != 0);
14014 if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
14015 return false;
14016 if (window->SkipItems)
14017 return false;
14018
14019 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14020 g.DragDropTargetRect = bb;
14021 g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
14022 g.DragDropTargetId = id;
14023 g.DragDropWithinTarget = true;
14024 return true;
14025 }
14026
14027 // We don't use BeginDragDropTargetCustom() and duplicate its code because:
14028 // 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
14029 // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
14030 // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
14031 bool ImGui::BeginDragDropTarget()
14032 {
14033 ImGuiContext& g = *GImGui;
14034 if (!g.DragDropActive)
14035 return false;
14036
14037 ImGuiWindow* window = g.CurrentWindow;
14038 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
14039 return false;
14040 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14041 if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)
14042 return false;
14043
14044 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
14045 ImGuiID id = g.LastItemData.ID;
14046 if (id == 0)
14047 {
14048 id = window->GetIDFromRectangle(display_rect);
14049 KeepAliveID(id);
14050 }
14051 if (g.DragDropPayload.SourceId == id)
14052 return false;
14053
14054 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14055 g.DragDropTargetRect = display_rect;
14056 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
14057 g.DragDropTargetId = id;
14058 g.DragDropWithinTarget = true;
14059 return true;
14060 }
14061
14062 bool ImGui::IsDragDropPayloadBeingAccepted()
14063 {
14064 ImGuiContext& g = *GImGui;
14065 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
14066 }
14067
14068 const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
14069 {
14070 ImGuiContext& g = *GImGui;
14071 ImGuiPayload& payload = g.DragDropPayload;
14072 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
14073 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
14074 if (type != NULL && !payload.IsDataType(type))
14075 return NULL;
14076
14077 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
14078 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
14079 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
14080 ImRect r = g.DragDropTargetRect;
14081 float r_surface = r.GetWidth() * r.GetHeight();
14082 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
14083 return NULL;
14084
14085 g.DragDropAcceptFlags = flags;
14086 g.DragDropAcceptIdCurr = g.DragDropTargetId;
14087 g.DragDropAcceptIdCurrRectSurface = r_surface;
14088 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
14089
14090 // Render default drop visuals
14091 payload.Preview = was_accepted_previously;
14092 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
14093 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
14094 RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
14095
14096 g.DragDropAcceptFrameCount = g.FrameCount;
14097 if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
14098 payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
14099 else
14100 payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
14101 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
14102 return NULL;
14103
14104 if (payload.Delivery)
14105 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
14106 return &payload;
14107 }
14108
14109 // FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
14110 void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
14111 {
14112 ImGuiContext& g = *GImGui;
14113 ImGuiWindow* window = g.CurrentWindow;
14114 ImRect bb_display = bb;
14115 bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
14116 bb_display.Expand(3.5f);
14117 bool push_clip_rect = !window->ClipRect.Contains(bb_display);
14118 if (push_clip_rect)
14119 window->DrawList->PushClipRectFullScreen();
14120 window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
14121 if (push_clip_rect)
14122 window->DrawList->PopClipRect();
14123 }
14124
14125 const ImGuiPayload* ImGui::GetDragDropPayload()
14126 {
14127 ImGuiContext& g = *GImGui;
14128 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
14129 }
14130
14131 void ImGui::EndDragDropTarget()
14132 {
14133 ImGuiContext& g = *GImGui;
14134 IM_ASSERT(g.DragDropActive);
14135 IM_ASSERT(g.DragDropWithinTarget);
14136 g.DragDropWithinTarget = false;
14137
14138 // Clear drag and drop state payload right after delivery
14139 if (g.DragDropPayload.Delivery)
14140 ClearDragDrop();
14141 }
14142
14143 //-----------------------------------------------------------------------------
14144 // [SECTION] LOGGING/CAPTURING
14145 //-----------------------------------------------------------------------------
14146 // All text output from the interface can be captured into tty/file/clipboard.
14147 // By default, tree nodes are automatically opened during logging.
14148 //-----------------------------------------------------------------------------
14149
14150 // Pass text data straight to log (without being displayed)
14151 static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
14152 {
14153 if (g.LogFile)
14154 {
14155 g.LogBuffer.Buf.resize(0);
14156 g.LogBuffer.appendfv(fmt, args);
14157 ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
14158 }
14159 else
14160 {
14161 g.LogBuffer.appendfv(fmt, args);
14162 }
14163 }
14164
14165 void ImGui::LogText(const char* fmt, ...)
14166 {
14167 ImGuiContext& g = *GImGui;
14168 if (!g.LogEnabled)
14169 return;
14170
14171 va_list args;
14172 va_start(args, fmt);
14173 LogTextV(g, fmt, args);
14174 va_end(args);
14175 }
14176
14177 void ImGui::LogTextV(const char* fmt, va_list args)
14178 {
14179 ImGuiContext& g = *GImGui;
14180 if (!g.LogEnabled)
14181 return;
14182
14183 LogTextV(g, fmt, args);
14184 }
14185
14186 // Internal version that takes a position to decide on newline placement and pad items according to their depth.
14187 // We split text into individual lines to add current tree level padding
14188 // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
14189 void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
14190 {
14191 ImGuiContext& g = *GImGui;
14192 ImGuiWindow* window = g.CurrentWindow;
14193
14194 const char* prefix = g.LogNextPrefix;
14195 const char* suffix = g.LogNextSuffix;
14196 g.LogNextPrefix = g.LogNextSuffix = NULL;
14197
14198 if (!text_end)
14199 text_end = FindRenderedTextEnd(text, text_end);
14200
14201 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
14202 if (ref_pos)
14203 g.LogLinePosY = ref_pos->y;
14204 if (log_new_line)
14205 {
14206 LogText(IM_NEWLINE);
14207 g.LogLineFirstItem = true;
14208 }
14209
14210 if (prefix)
14211 LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
14212
14213 // Re-adjust padding if we have popped out of our starting depth
14214 if (g.LogDepthRef > window->DC.TreeDepth)
14215 g.LogDepthRef = window->DC.TreeDepth;
14216 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
14217
14218 const char* text_remaining = text;
14219 for (;;)
14220 {
14221 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
14222 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
14223 const char* line_start = text_remaining;
14224 const char* line_end = ImStreolRange(line_start, text_end);
14225 const bool is_last_line = (line_end == text_end);
14226 if (line_start != line_end || !is_last_line)
14227 {
14228 const int line_length = (int)(line_end - line_start);
14229 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14230 LogText("%*s%.*s", indentation, "", line_length, line_start);
14231 g.LogLineFirstItem = false;
14232 if (*line_end == '\n')
14233 {
14234 LogText(IM_NEWLINE);
14235 g.LogLineFirstItem = true;
14236 }
14237 }
14238 if (is_last_line)
14239 break;
14240 text_remaining = line_end + 1;
14241 }
14242
14243 if (suffix)
14244 LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14245 }
14246
14247 // Start logging/capturing text output
14248 void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
14249 {
14250 ImGuiContext& g = *GImGui;
14251 ImGuiWindow* window = g.CurrentWindow;
14252 IM_ASSERT(g.LogEnabled == false);
14253 IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
14254 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
14255
14256 g.LogEnabled = g.ItemUnclipByLog = true;
14257 g.LogFlags = flags;
14258 g.LogWindow = window;
14259 g.LogNextPrefix = g.LogNextSuffix = NULL;
14260 g.LogDepthRef = window->DC.TreeDepth;
14261 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14262 g.LogLinePosY = FLT_MAX;
14263 g.LogLineFirstItem = true;
14264 }
14265
14266 // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14267 void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14268 {
14269 ImGuiContext& g = *GImGui;
14270 g.LogNextPrefix = prefix;
14271 g.LogNextSuffix = suffix;
14272 }
14273
14274 void ImGui::LogToTTY(int auto_open_depth)
14275 {
14276 ImGuiContext& g = *GImGui;
14277 if (g.LogEnabled)
14278 return;
14279 IM_UNUSED(auto_open_depth);
14280 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14281 LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth);
14282 g.LogFile = stdout;
14283 #endif
14284 }
14285
14286 // Start logging/capturing text output to given file
14287 void ImGui::LogToFile(int auto_open_depth, const char* filename)
14288 {
14289 ImGuiContext& g = *GImGui;
14290 if (g.LogEnabled)
14291 return;
14292
14293 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14294 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14295 // By opening the file in binary mode "ab" we have consistent output everywhere.
14296 if (!filename)
14297 filename = g.IO.LogFilename;
14298 if (!filename || !filename[0])
14299 return;
14300 ImFileHandle f = ImFileOpen(filename, "ab");
14301 if (!f)
14302 {
14303 IM_ASSERT(0);
14304 return;
14305 }
14306
14307 LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth);
14308 g.LogFile = f;
14309 }
14310
14311 // Start logging/capturing text output to clipboard
14312 void ImGui::LogToClipboard(int auto_open_depth)
14313 {
14314 ImGuiContext& g = *GImGui;
14315 if (g.LogEnabled)
14316 return;
14317 LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth);
14318 }
14319
14320 void ImGui::LogToBuffer(int auto_open_depth)
14321 {
14322 ImGuiContext& g = *GImGui;
14323 if (g.LogEnabled)
14324 return;
14325 LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth);
14326 }
14327
14328 void ImGui::LogFinish()
14329 {
14330 ImGuiContext& g = *GImGui;
14331 if (!g.LogEnabled)
14332 return;
14333
14334 LogText(IM_NEWLINE);
14335 switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
14336 {
14337 case ImGuiLogFlags_OutputTTY:
14338 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14339 fflush(g.LogFile);
14340 #endif
14341 break;
14342 case ImGuiLogFlags_OutputFile:
14343 ImFileClose(g.LogFile);
14344 break;
14345 case ImGuiLogFlags_OutputBuffer:
14346 break;
14347 case ImGuiLogFlags_OutputClipboard:
14348 if (!g.LogBuffer.empty())
14349 SetClipboardText(g.LogBuffer.begin());
14350 break;
14351 default:
14352 IM_ASSERT(0);
14353 break;
14354 }
14355
14356 g.LogEnabled = g.ItemUnclipByLog = false;
14357 g.LogFlags = ImGuiLogFlags_None;
14358 g.LogFile = NULL;
14359 g.LogBuffer.clear();
14360 }
14361
14362 // Helper to display logging buttons
14363 // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14364 void ImGui::LogButtons()
14365 {
14366 ImGuiContext& g = *GImGui;
14367
14368 PushID("LogButtons");
14369 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14370 const bool log_to_tty = Button("Log To TTY"); SameLine();
14371 #else
14372 const bool log_to_tty = false;
14373 #endif
14374 const bool log_to_file = Button("Log To File"); SameLine();
14375 const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14376 PushItemFlag(ImGuiItemFlags_NoTabStop, true);
14377 SetNextItemWidth(80.0f);
14378 SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14379 PopItemFlag();
14380 PopID();
14381
14382 // Start logging at the end of the function so that the buttons don't appear in the log
14383 if (log_to_tty)
14384 LogToTTY();
14385 if (log_to_file)
14386 LogToFile();
14387 if (log_to_clipboard)
14388 LogToClipboard();
14389 }
14390
14391
14392 //-----------------------------------------------------------------------------
14393 // [SECTION] SETTINGS
14394 //-----------------------------------------------------------------------------
14395 // - UpdateSettings() [Internal]
14396 // - MarkIniSettingsDirty() [Internal]
14397 // - FindSettingsHandler() [Internal]
14398 // - ClearIniSettings() [Internal]
14399 // - LoadIniSettingsFromDisk()
14400 // - LoadIniSettingsFromMemory()
14401 // - SaveIniSettingsToDisk()
14402 // - SaveIniSettingsToMemory()
14403 //-----------------------------------------------------------------------------
14404 // - CreateNewWindowSettings() [Internal]
14405 // - FindWindowSettingsByID() [Internal]
14406 // - FindWindowSettingsByWindow() [Internal]
14407 // - ClearWindowSettings() [Internal]
14408 // - WindowSettingsHandler_***() [Internal]
14409 //-----------------------------------------------------------------------------
14410
14411 // Called by NewFrame()
14412 void ImGui::UpdateSettings()
14413 {
14414 // Load settings on first frame (if not explicitly loaded manually before)
14415 ImGuiContext& g = *GImGui;
14416 if (!g.SettingsLoaded)
14417 {
14418 IM_ASSERT(g.SettingsWindows.empty());
14419 if (g.IO.IniFilename)
14420 LoadIniSettingsFromDisk(g.IO.IniFilename);
14421 g.SettingsLoaded = true;
14422 }
14423
14424 // Save settings (with a delay after the last modification, so we don't spam disk too much)
14425 if (g.SettingsDirtyTimer > 0.0f)
14426 {
14427 g.SettingsDirtyTimer -= g.IO.DeltaTime;
14428 if (g.SettingsDirtyTimer <= 0.0f)
14429 {
14430 if (g.IO.IniFilename != NULL)
14431 SaveIniSettingsToDisk(g.IO.IniFilename);
14432 else
14433 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14434 g.SettingsDirtyTimer = 0.0f;
14435 }
14436 }
14437 }
14438
14439 void ImGui::MarkIniSettingsDirty()
14440 {
14441 ImGuiContext& g = *GImGui;
14442 if (g.SettingsDirtyTimer <= 0.0f)
14443 g.SettingsDirtyTimer = g.IO.IniSavingRate;
14444 }
14445
14446 void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14447 {
14448 ImGuiContext& g = *GImGui;
14449 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14450 if (g.SettingsDirtyTimer <= 0.0f)
14451 g.SettingsDirtyTimer = g.IO.IniSavingRate;
14452 }
14453
14454 void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14455 {
14456 ImGuiContext& g = *GImGui;
14457 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14458 g.SettingsHandlers.push_back(*handler);
14459 }
14460
14461 void ImGui::RemoveSettingsHandler(const char* type_name)
14462 {
14463 ImGuiContext& g = *GImGui;
14464 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14465 g.SettingsHandlers.erase(handler);
14466 }
14467
14468 ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14469 {
14470 ImGuiContext& g = *GImGui;
14471 const ImGuiID type_hash = ImHashStr(type_name);
14472 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14473 if (handler.TypeHash == type_hash)
14474 return &handler;
14475 return NULL;
14476 }
14477
14478 // Clear all settings (windows, tables, docking etc.)
14479 void ImGui::ClearIniSettings()
14480 {
14481 ImGuiContext& g = *GImGui;
14482 g.SettingsIniData.clear();
14483 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14484 if (handler.ClearAllFn != NULL)
14485 handler.ClearAllFn(&g, &handler);
14486 }
14487
14488 void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14489 {
14490 size_t file_data_size = 0;
14491 char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14492 if (!file_data)
14493 return;
14494 if (file_data_size > 0)
14495 LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14496 IM_FREE(file_data);
14497 }
14498
14499 // Zero-tolerance, no error reporting, cheap .ini parsing
14500 // Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14501 void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14502 {
14503 ImGuiContext& g = *GImGui;
14504 IM_ASSERT(g.Initialized);
14505 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14506 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14507
14508 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14509 // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14510 if (ini_size == 0)
14511 ini_size = strlen(ini_data);
14512 g.SettingsIniData.Buf.resize((int)ini_size + 1);
14513 char* const buf = g.SettingsIniData.Buf.Data;
14514 char* const buf_end = buf + ini_size;
14515 memcpy(buf, ini_data, ini_size);
14516 buf_end[0] = 0;
14517
14518 // Call pre-read handlers
14519 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14520 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14521 if (handler.ReadInitFn != NULL)
14522 handler.ReadInitFn(&g, &handler);
14523
14524 void* entry_data = NULL;
14525 ImGuiSettingsHandler* entry_handler = NULL;
14526
14527 char* line_end = NULL;
14528 for (char* line = buf; line < buf_end; line = line_end + 1)
14529 {
14530 // Skip new lines markers, then find end of the line
14531 while (*line == '\n' || *line == '\r')
14532 line++;
14533 line_end = line;
14534 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14535 line_end++;
14536 line_end[0] = 0;
14537 if (line[0] == ';')
14538 continue;
14539 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14540 {
14541 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14542 line_end[-1] = 0;
14543 const char* name_end = line_end - 1;
14544 const char* type_start = line + 1;
14545 char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14546 const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14547 if (!type_end || !name_start)
14548 continue;
14549 *type_end = 0; // Overwrite first ']'
14550 name_start++; // Skip second '['
14551 entry_handler = FindSettingsHandler(type_start);
14552 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14553 }
14554 else if (entry_handler != NULL && entry_data != NULL)
14555 {
14556 // Let type handler parse the line
14557 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14558 }
14559 }
14560 g.SettingsLoaded = true;
14561
14562 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14563 memcpy(buf, ini_data, ini_size);
14564
14565 // Call post-read handlers
14566 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14567 if (handler.ApplyAllFn != NULL)
14568 handler.ApplyAllFn(&g, &handler);
14569 }
14570
14571 void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14572 {
14573 ImGuiContext& g = *GImGui;
14574 g.SettingsDirtyTimer = 0.0f;
14575 if (!ini_filename)
14576 return;
14577
14578 size_t ini_data_size = 0;
14579 const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14580 ImFileHandle f = ImFileOpen(ini_filename, "wt");
14581 if (!f)
14582 return;
14583 ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14584 ImFileClose(f);
14585 }
14586
14587 // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14588 const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14589 {
14590 ImGuiContext& g = *GImGui;
14591 g.SettingsDirtyTimer = 0.0f;
14592 g.SettingsIniData.Buf.resize(0);
14593 g.SettingsIniData.Buf.push_back(0);
14594 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14595 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14596 if (out_size)
14597 *out_size = (size_t)g.SettingsIniData.size();
14598 return g.SettingsIniData.c_str();
14599 }
14600
14601 ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14602 {
14603 ImGuiContext& g = *GImGui;
14604
14605 if (g.IO.ConfigDebugIniSettings == false)
14606 {
14607 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14608 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14609 if (const char* p = strstr(name, "###"))
14610 name = p;
14611 }
14612 const size_t name_len = strlen(name);
14613
14614 // Allocate chunk
14615 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14616 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14617 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14618 settings->ID = ImHashStr(name, name_len);
14619 memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
14620
14621 return settings;
14622 }
14623
14624 // We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14625 // This is called once per window .ini entry + once per newly instantiated window.
14626 ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14627 {
14628 ImGuiContext& g = *GImGui;
14629 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14630 if (settings->ID == id && !settings->WantDelete)
14631 return settings;
14632 return NULL;
14633 }
14634
14635 // This is faster if you are holding on a Window already as we don't need to perform a search.
14636 ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14637 {
14638 ImGuiContext& g = *GImGui;
14639 if (window->SettingsOffset != -1)
14640 return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14641 return FindWindowSettingsByID(window->ID);
14642 }
14643
14644 // This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14645 void ImGui::ClearWindowSettings(const char* name)
14646 {
14647 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14648 ImGuiWindow* window = FindWindowByName(name);
14649 if (window != NULL)
14650 {
14651 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14652 InitOrLoadWindowSettings(window, NULL);
14653 }
14654 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14655 settings->WantDelete = true;
14656 }
14657
14658 static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14659 {
14660 ImGuiContext& g = *ctx;
14661 for (ImGuiWindow* window : g.Windows)
14662 window->SettingsOffset = -1;
14663 g.SettingsWindows.clear();
14664 }
14665
14666 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14667 {
14668 ImGuiID id = ImHashStr(name);
14669 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14670 if (settings)
14671 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14672 else
14673 settings = ImGui::CreateNewWindowSettings(name);
14674 settings->ID = id;
14675 settings->WantApply = true;
14676 return (void*)settings;
14677 }
14678
14679 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14680 {
14681 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14682 int x, y;
14683 int i;
14684 if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
14685 else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
14686 else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
14687 else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
14688 }
14689
14690 // Apply to existing windows (if any)
14691 static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14692 {
14693 ImGuiContext& g = *ctx;
14694 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14695 if (settings->WantApply)
14696 {
14697 if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14698 ApplyWindowSettings(window, settings);
14699 settings->WantApply = false;
14700 }
14701 }
14702
14703 static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14704 {
14705 // Gather data from windows that were active during this session
14706 // (if a window wasn't opened in this session we preserve its settings)
14707 ImGuiContext& g = *ctx;
14708 for (ImGuiWindow* window : g.Windows)
14709 {
14710 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14711 continue;
14712
14713 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14714 if (!settings)
14715 {
14716 settings = ImGui::CreateNewWindowSettings(window->Name);
14717 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14718 }
14719 IM_ASSERT(settings->ID == window->ID);
14720 settings->Pos = ImVec2ih(window->Pos);
14721 settings->Size = ImVec2ih(window->SizeFull);
14722 settings->IsChild = (window->Flags & ImGuiWindowFlags_ChildWindow) != 0;
14723 settings->Collapsed = window->Collapsed;
14724 settings->WantDelete = false;
14725 }
14726
14727 // Write to text buffer
14728 buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14729 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14730 {
14731 if (settings->WantDelete)
14732 continue;
14733 const char* settings_name = settings->GetName();
14734 buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14735 if (settings->IsChild)
14736 {
14737 buf->appendf("IsChild=1\n");
14738 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14739 }
14740 else
14741 {
14742 buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14743 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14744 if (settings->Collapsed)
14745 buf->appendf("Collapsed=1\n");
14746 }
14747 buf->append("\n");
14748 }
14749 }
14750
14751
14752 //-----------------------------------------------------------------------------
14753 // [SECTION] LOCALIZATION
14754 //-----------------------------------------------------------------------------
14755
14756 void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14757 {
14758 ImGuiContext& g = *GImGui;
14759 for (int n = 0; n < count; n++)
14760 g.LocalizationTable[entries[n].Key] = entries[n].Text;
14761 }
14762
14763
14764 //-----------------------------------------------------------------------------
14765 // [SECTION] VIEWPORTS, PLATFORM WINDOWS
14766 //-----------------------------------------------------------------------------
14767 // - GetMainViewport()
14768 // - SetWindowViewport() [Internal]
14769 // - UpdateViewportsNewFrame() [Internal]
14770 // (this section is more complete in the 'docking' branch)
14771 //-----------------------------------------------------------------------------
14772
14773 ImGuiViewport* ImGui::GetMainViewport()
14774 {
14775 ImGuiContext& g = *GImGui;
14776 return g.Viewports[0];
14777 }
14778
14779 void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14780 {
14781 window->Viewport = viewport;
14782 }
14783
14784 // Update viewports and monitor infos
14785 static void ImGui::UpdateViewportsNewFrame()
14786 {
14787 ImGuiContext& g = *GImGui;
14788 IM_ASSERT(g.Viewports.Size == 1);
14789
14790 // Update main viewport with current platform position.
14791 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14792 ImGuiViewportP* main_viewport = g.Viewports[0];
14793 main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
14794 main_viewport->Pos = ImVec2(0.0f, 0.0f);
14795 main_viewport->Size = g.IO.DisplaySize;
14796
14797 for (ImGuiViewportP* viewport : g.Viewports)
14798 {
14799 // Lock down space taken by menu bars and status bars
14800 // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
14801 viewport->WorkInsetMin = viewport->BuildWorkInsetMin;
14802 viewport->WorkInsetMax = viewport->BuildWorkInsetMax;
14803 viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f);
14804 viewport->UpdateWorkRect();
14805 }
14806 }
14807
14808 //-----------------------------------------------------------------------------
14809 // [SECTION] DOCKING
14810 //-----------------------------------------------------------------------------
14811
14812 // (this section is filled in the 'docking' branch)
14813
14814
14815 //-----------------------------------------------------------------------------
14816 // [SECTION] PLATFORM DEPENDENT HELPERS
14817 //-----------------------------------------------------------------------------
14818 // - Default clipboard handlers
14819 // - Default shell function handlers
14820 // - Default IME handlers
14821 //-----------------------------------------------------------------------------
14822
14823 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
14824
14825 #ifdef _MSC_VER
14826 #pragma comment(lib, "user32")
14827 #pragma comment(lib, "kernel32")
14828 #endif
14829
14830 // Win32 clipboard implementation
14831 // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
14832 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
14833 {
14834 ImGuiContext& g = *ctx;
14835 g.ClipboardHandlerData.clear();
14836 if (!::OpenClipboard(NULL))
14837 return NULL;
14838 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
14839 if (wbuf_handle == NULL)
14840 {
14841 ::CloseClipboard();
14842 return NULL;
14843 }
14844 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
14845 {
14846 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
14847 g.ClipboardHandlerData.resize(buf_len);
14848 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
14849 }
14850 ::GlobalUnlock(wbuf_handle);
14851 ::CloseClipboard();
14852 return g.ClipboardHandlerData.Data;
14853 }
14854
14855 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
14856 {
14857 if (!::OpenClipboard(NULL))
14858 return;
14859 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
14860 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
14861 if (wbuf_handle == NULL)
14862 {
14863 ::CloseClipboard();
14864 return;
14865 }
14866 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
14867 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
14868 ::GlobalUnlock(wbuf_handle);
14869 ::EmptyClipboard();
14870 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
14871 ::GlobalFree(wbuf_handle);
14872 ::CloseClipboard();
14873 }
14874
14875 #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
14876
14877 #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
14878 static PasteboardRef main_clipboard = 0;
14879
14880 // OSX clipboard implementation
14881 // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
14882 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
14883 {
14884 if (!main_clipboard)
14885 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
14886 PasteboardClear(main_clipboard);
14887 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
14888 if (cf_data)
14889 {
14890 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
14891 CFRelease(cf_data);
14892 }
14893 }
14894
14895 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
14896 {
14897 ImGuiContext& g = *ctx;
14898 if (!main_clipboard)
14899 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
14900 PasteboardSynchronize(main_clipboard);
14901
14902 ItemCount item_count = 0;
14903 PasteboardGetItemCount(main_clipboard, &item_count);
14904 for (ItemCount i = 0; i < item_count; i++)
14905 {
14906 PasteboardItemID item_id = 0;
14907 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
14908 CFArrayRef flavor_type_array = 0;
14909 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
14910 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
14911 {
14912 CFDataRef cf_data;
14913 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
14914 {
14915 g.ClipboardHandlerData.clear();
14916 int length = (int)CFDataGetLength(cf_data);
14917 g.ClipboardHandlerData.resize(length + 1);
14918 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
14919 g.ClipboardHandlerData[length] = 0;
14920 CFRelease(cf_data);
14921 return g.ClipboardHandlerData.Data;
14922 }
14923 }
14924 }
14925 return NULL;
14926 }
14927
14928 #else
14929
14930 // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
14931 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
14932 {
14933 ImGuiContext& g = *ctx;
14934 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
14935 }
14936
14937 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text)
14938 {
14939 ImGuiContext& g = *ctx;
14940 g.ClipboardHandlerData.clear();
14941 const char* text_end = text + strlen(text);
14942 g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
14943 memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
14944 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
14945 }
14946
14947 #endif // Default clipboard handlers
14948
14949 //-----------------------------------------------------------------------------
14950
14951 #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14952 #if defined(__APPLE__) && TARGET_OS_IPHONE
14953 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14954 #endif
14955
14956 #if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
14957 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14958 #endif
14959 #endif
14960
14961 #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14962 #ifdef _WIN32
14963 #include <shellapi.h> // ShellExecuteA()
14964 #ifdef _MSC_VER
14965 #pragma comment(lib, "shell32")
14966 #endif
14967 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
14968 {
14969 return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
14970 }
14971 #else
14972 #include <sys/wait.h>
14973 #include <unistd.h>
14974 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
14975 {
14976 #if defined(__APPLE__)
14977 const char* args[] { "open", "--", path, NULL };
14978 #else
14979 const char* args[] { "xdg-open", path, NULL };
14980 #endif
14981 pid_t pid = fork();
14982 if (pid < 0)
14983 return false;
14984 if (!pid)
14985 {
14986 execvp(args[0], const_cast<char **>(args));
14987 exit(-1);
14988 }
14989 else
14990 {
14991 int status;
14992 waitpid(pid, &status, 0);
14993 return WEXITSTATUS(status) == 0;
14994 }
14995 }
14996 #endif
14997 #else
14998 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
14999 #endif // Default shell handlers
15000
15001 //-----------------------------------------------------------------------------
15002
15003 // Win32 API IME support (for Asian languages, etc.)
15004 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
15005
15006 #include <imm.h>
15007 #ifdef _MSC_VER
15008 #pragma comment(lib, "imm32")
15009 #endif
15010
15011 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
15012 {
15013 // Notify OS Input Method Editor of text input position
15014 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
15015 if (hwnd == 0)
15016 return;
15017
15018 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
15019 if (HIMC himc = ::ImmGetContext(hwnd))
15020 {
15021 COMPOSITIONFORM composition_form = {};
15022 composition_form.ptCurrentPos.x = (LONG)data->InputPos.x;
15023 composition_form.ptCurrentPos.y = (LONG)data->InputPos.y;
15024 composition_form.dwStyle = CFS_FORCE_POSITION;
15025 ::ImmSetCompositionWindow(himc, &composition_form);
15026 CANDIDATEFORM candidate_form = {};
15027 candidate_form.dwStyle = CFS_CANDIDATEPOS;
15028 candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x;
15029 candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y;
15030 ::ImmSetCandidateWindow(himc, &candidate_form);
15031 ::ImmReleaseContext(hwnd, himc);
15032 }
15033 }
15034
15035 #else
15036
15037 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
15038
15039 #endif // Default IME handlers
15040
15041 //-----------------------------------------------------------------------------
15042 // [SECTION] METRICS/DEBUGGER WINDOW
15043 //-----------------------------------------------------------------------------
15044 // - DebugRenderViewportThumbnail() [Internal]
15045 // - RenderViewportsThumbnails() [Internal]
15046 // - DebugTextEncoding()
15047 // - MetricsHelpMarker() [Internal]
15048 // - ShowFontAtlas() [Internal]
15049 // - ShowMetricsWindow()
15050 // - DebugNodeColumns() [Internal]
15051 // - DebugNodeDrawList() [Internal]
15052 // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
15053 // - DebugNodeFont() [Internal]
15054 // - DebugNodeFontGlyph() [Internal]
15055 // - DebugNodeStorage() [Internal]
15056 // - DebugNodeTabBar() [Internal]
15057 // - DebugNodeViewport() [Internal]
15058 // - DebugNodeWindow() [Internal]
15059 // - DebugNodeWindowSettings() [Internal]
15060 // - DebugNodeWindowsList() [Internal]
15061 // - DebugNodeWindowsListByBeginStackParent() [Internal]
15062 //-----------------------------------------------------------------------------
15063
15064 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
15065
15066 void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
15067 {
15068 ImGuiContext& g = *GImGui;
15069 ImGuiWindow* window = g.CurrentWindow;
15070
15071 ImVec2 scale = bb.GetSize() / viewport->Size;
15072 ImVec2 off = bb.Min - viewport->Pos * scale;
15073 float alpha_mul = 1.0f;
15074 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
15075 for (ImGuiWindow* thumb_window : g.Windows)
15076 {
15077 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
15078 continue;
15079
15080 ImRect thumb_r = thumb_window->Rect();
15081 ImRect title_r = thumb_window->TitleBarRect();
15082 thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale));
15083 title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
15084 thumb_r.ClipWithFull(bb);
15085 title_r.ClipWithFull(bb);
15086 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
15087 window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
15088 window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
15089 window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
15090 window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
15091 }
15092 draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
15093 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
15094 window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
15095 }
15096
15097 static void RenderViewportsThumbnails()
15098 {
15099 ImGuiContext& g = *GImGui;
15100 ImGuiWindow* window = g.CurrentWindow;
15101
15102 float SCALE = 1.0f / 8.0f;
15103 ImRect bb_full(g.Viewports[0]->Pos, g.Viewports[0]->Pos + g.Viewports[0]->Size);
15104 ImVec2 p = window->DC.CursorPos;
15105 ImVec2 off = p - bb_full.Min * SCALE;
15106
15107 // Draw viewports
15108 for (ImGuiViewportP* viewport : g.Viewports)
15109 {
15110 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
15111 ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
15112 }
15113 ImGui::Dummy(bb_full.GetSize() * SCALE);
15114 }
15115
15116 // Draw an arbitrary US keyboard layout to visualize translated keys
15117 void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
15118 {
15119 const float scale = ImGui::GetFontSize() / 13.0f;
15120 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
15121 const float key_rounding = 3.0f * scale;
15122 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
15123 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
15124 const float key_face_rounding = 2.0f * scale;
15125 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
15126 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
15127 const float key_row_offset = 9.0f * scale;
15128
15129 ImVec2 board_min = GetCursorScreenPos();
15130 ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
15131 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
15132
15133 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
15134 const KeyLayoutData keys_to_display[] =
15135 {
15136 { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
15137 { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
15138 { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
15139 };
15140
15141 // Elements rendered manually via ImDrawList API are not clipped automatically.
15142 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
15143 Dummy(board_max - board_min);
15144 if (!IsItemVisible())
15145 return;
15146 draw_list->PushClipRect(board_min, board_max, true);
15147 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
15148 {
15149 const KeyLayoutData* key_data = &keys_to_display[n];
15150 ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
15151 ImVec2 key_max = key_min + key_size;
15152 draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
15153 draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
15154 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
15155 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
15156 draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
15157 draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
15158 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
15159 draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
15160 if (IsKeyDown(key_data->Key))
15161 draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
15162 }
15163 draw_list->PopClipRect();
15164 }
15165
15166 // Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
15167 void ImGui::DebugTextEncoding(const char* str)
15168 {
15169 Text("Text: \"%s\"", str);
15170 if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
15171 return;
15172 TableSetupColumn("Offset");
15173 TableSetupColumn("UTF-8");
15174 TableSetupColumn("Glyph");
15175 TableSetupColumn("Codepoint");
15176 TableHeadersRow();
15177 for (const char* p = str; *p != 0; )
15178 {
15179 unsigned int c;
15180 const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
15181 TableNextColumn();
15182 Text("%d", (int)(p - str));
15183 TableNextColumn();
15184 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
15185 {
15186 if (byte_index > 0)
15187 SameLine();
15188 Text("0x%02X", (int)(unsigned char)p[byte_index]);
15189 }
15190 TableNextColumn();
15191 if (GetFont()->FindGlyphNoFallback((ImWchar)c))
15192 TextUnformatted(p, p + c_utf8_len);
15193 else
15194 TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
15195 TableNextColumn();
15196 Text("U+%04X", (int)c);
15197 p += c_utf8_len;
15198 }
15199 EndTable();
15200 }
15201
15202 static void DebugFlashStyleColorStop()
15203 {
15204 ImGuiContext& g = *GImGui;
15205 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
15206 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
15207 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
15208 }
15209
15210 // Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
15211 void ImGui::DebugFlashStyleColor(ImGuiCol idx)
15212 {
15213 ImGuiContext& g = *GImGui;
15214 DebugFlashStyleColorStop();
15215 g.DebugFlashStyleColorTime = 0.5f;
15216 g.DebugFlashStyleColorIdx = idx;
15217 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
15218 }
15219
15220 void ImGui::UpdateDebugToolFlashStyleColor()
15221 {
15222 ImGuiContext& g = *GImGui;
15223 if (g.DebugFlashStyleColorTime <= 0.0f)
15224 return;
15225 ColorConvertHSVtoRGB(ImCos(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
15226 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
15227 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
15228 DebugFlashStyleColorStop();
15229 }
15230
15231 static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
15232 {
15233 union { void* ptr; int integer; } tex_id_opaque;
15234 memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
15235 if (sizeof(tex_id) >= sizeof(void*))
15236 ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
15237 else
15238 ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
15239 return buf;
15240 }
15241
15242 // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
15243 static void MetricsHelpMarker(const char* desc)
15244 {
15245 ImGui::TextDisabled("(?)");
15246 if (ImGui::BeginItemTooltip())
15247 {
15248 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
15249 ImGui::TextUnformatted(desc);
15250 ImGui::PopTextWrapPos();
15251 ImGui::EndTooltip();
15252 }
15253 }
15254
15255 // [DEBUG] List fonts in a font atlas and display its texture
15256 void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
15257 {
15258 for (ImFont* font : atlas->Fonts)
15259 {
15260 PushID(font);
15261 DebugNodeFont(font);
15262 PopID();
15263 }
15264 if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
15265 {
15266 ImGuiContext& g = *GImGui;
15267 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
15268 Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
15269 ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
15270 ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
15271 Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
15272 TreePop();
15273 }
15274 }
15275
15276 void ImGui::ShowMetricsWindow(bool* p_open)
15277 {
15278 ImGuiContext& g = *GImGui;
15279 ImGuiIO& io = g.IO;
15280 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
15281 if (cfg->ShowDebugLog)
15282 ShowDebugLogWindow(&cfg->ShowDebugLog);
15283 if (cfg->ShowIDStackTool)
15284 ShowIDStackToolWindow(&cfg->ShowIDStackTool);
15285
15286 if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
15287 {
15288 End();
15289 return;
15290 }
15291
15292 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
15293 DebugBreakClearData();
15294
15295 // Basic info
15296 Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
15297 if (g.ContextName[0] != 0)
15298 {
15299 SameLine();
15300 Text("(Context Name: \"%s\")", g.ContextName);
15301 }
15302 Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
15303 Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
15304 Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
15305 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
15306
15307 Separator();
15308
15309 // Debugging enums
15310 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
15311 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
15312 enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
15313 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
15314 if (cfg->ShowWindowsRectsType < 0)
15315 cfg->ShowWindowsRectsType = WRT_WorkRect;
15316 if (cfg->ShowTablesRectsType < 0)
15317 cfg->ShowTablesRectsType = TRT_WorkRect;
15318
15319 struct Funcs
15320 {
15321 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
15322 {
15323 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
15324 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
15325 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
15326 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
15327 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
15328 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
15329 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
15330 else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
15331 else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
15332 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
15333 else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
15334 else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
15335 else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
15336 else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
15337 IM_ASSERT(0);
15338 return ImRect();
15339 }
15340
15341 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
15342 {
15343 if (rect_type == WRT_OuterRect) { return window->Rect(); }
15344 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
15345 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
15346 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
15347 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
15348 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
15349 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
15350 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
15351 IM_ASSERT(0);
15352 return ImRect();
15353 }
15354 };
15355
15356 // Tools
15357 if (TreeNode("Tools"))
15358 {
15359 // Debug Break features
15360 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
15361 SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
15362 SameLine();
15363 MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
15364 if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
15365 DebugStartItemPicker();
15366 Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
15367
15368 SeparatorText("Visualize");
15369
15370 Checkbox("Show Debug Log", &cfg->ShowDebugLog);
15371 SameLine();
15372 MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
15373
15374 Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
15375 SameLine();
15376 MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
15377
15378 Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
15379 Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
15380 SameLine();
15381 SetNextItemWidth(GetFontSize() * 12);
15382 cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
15383 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
15384 {
15385 BulletText("'%s':", g.NavWindow->Name);
15386 Indent();
15387 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
15388 {
15389 ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
15390 Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
15391 }
15392 Unindent();
15393 }
15394
15395 Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
15396 SameLine();
15397 SetNextItemWidth(GetFontSize() * 12);
15398 cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
15399 if (cfg->ShowTablesRects && g.NavWindow != NULL)
15400 {
15401 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
15402 {
15403 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
15404 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
15405 continue;
15406
15407 BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
15408 if (IsItemHovered())
15409 GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
15410 Indent();
15411 char buf[128];
15412 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
15413 {
15414 if (rect_n >= TRT_ColumnsRect)
15415 {
15416 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
15417 continue;
15418 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
15419 {
15420 ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
15421 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
15422 Selectable(buf);
15423 if (IsItemHovered())
15424 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
15425 }
15426 }
15427 else
15428 {
15429 ImRect r = Funcs::GetTableRect(table, rect_n, -1);
15430 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
15431 Selectable(buf);
15432 if (IsItemHovered())
15433 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
15434 }
15435 }
15436 Unindent();
15437 }
15438 }
15439 Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
15440
15441 SeparatorText("Validate");
15442
15443 Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
15444 SameLine();
15445 MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
15446
15447 Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
15448 SameLine();
15449 MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
15450 if (cfg->ShowTextEncodingViewer)
15451 {
15452 static char buf[64] = "";
15453 SetNextItemWidth(-FLT_MIN);
15454 InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
15455 if (buf[0] != 0)
15456 DebugTextEncoding(buf);
15457 }
15458
15459 TreePop();
15460 }
15461
15462 // Windows
15463 if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
15464 {
15465 //SetNextItemOpen(true, ImGuiCond_Once);
15466 DebugNodeWindowsList(&g.Windows, "By display order");
15467 DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
15468 if (TreeNode("By submission order (begin stack)"))
15469 {
15470 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
15471 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
15472 temp_buffer.resize(0);
15473 for (ImGuiWindow* window : g.Windows)
15474 if (window->LastFrameActive + 1 >= g.FrameCount)
15475 temp_buffer.push_back(window);
15476 struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
15477 ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
15478 DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
15479 TreePop();
15480 }
15481
15482 TreePop();
15483 }
15484
15485 // DrawLists
15486 int drawlist_count = 0;
15487 for (ImGuiViewportP* viewport : g.Viewports)
15488 drawlist_count += viewport->DrawDataP.CmdLists.Size;
15489 if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
15490 {
15491 Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
15492 Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
15493 for (ImGuiViewportP* viewport : g.Viewports)
15494 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
15495 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
15496 TreePop();
15497 }
15498
15499 // Viewports
15500 if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
15501 {
15502 SetNextItemOpen(true, ImGuiCond_Once);
15503 if (TreeNode("Windows Minimap"))
15504 {
15505 RenderViewportsThumbnails();
15506 TreePop();
15507 }
15508 cfg->HighlightViewportID = 0;
15509
15510 for (ImGuiViewportP* viewport : g.Viewports)
15511 DebugNodeViewport(viewport);
15512 TreePop();
15513 }
15514
15515 // Details for Popups
15516 if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
15517 {
15518 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
15519 {
15520 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
15521 ImGuiWindow* window = popup_data.Window;
15522 BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
15523 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
15524 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
15525 }
15526 TreePop();
15527 }
15528
15529 // Details for TabBars
15530 if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
15531 {
15532 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
15533 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
15534 {
15535 PushID(tab_bar);
15536 DebugNodeTabBar(tab_bar, "TabBar");
15537 PopID();
15538 }
15539 TreePop();
15540 }
15541
15542 // Details for Tables
15543 if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
15544 {
15545 for (int n = 0; n < g.Tables.GetMapSize(); n++)
15546 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
15547 DebugNodeTable(table);
15548 TreePop();
15549 }
15550
15551 // Details for Fonts
15552 ImFontAtlas* atlas = g.IO.Fonts;
15553 if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
15554 {
15555 ShowFontAtlas(atlas);
15556 TreePop();
15557 }
15558
15559 // Details for InputText
15560 if (TreeNode("InputText"))
15561 {
15562 DebugNodeInputTextState(&g.InputTextState);
15563 TreePop();
15564 }
15565
15566 // Details for TypingSelect
15567 if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
15568 {
15569 DebugNodeTypingSelectState(&g.TypingSelectState);
15570 TreePop();
15571 }
15572
15573 // Details for MultiSelect
15574 if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
15575 {
15576 ImGuiBoxSelectState* bs = &g.BoxSelectState;
15577 BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
15578 for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
15579 if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
15580 DebugNodeMultiSelectState(state);
15581 TreePop();
15582 }
15583
15584 // Details for Docking
15585 #ifdef IMGUI_HAS_DOCK
15586 if (TreeNode("Docking"))
15587 {
15588 TreePop();
15589 }
15590 #endif // #ifdef IMGUI_HAS_DOCK
15591
15592 // Settings
15593 if (TreeNode("Settings"))
15594 {
15595 if (SmallButton("Clear"))
15596 ClearIniSettings();
15597 SameLine();
15598 if (SmallButton("Save to memory"))
15599 SaveIniSettingsToMemory();
15600 SameLine();
15601 if (SmallButton("Save to disk"))
15602 SaveIniSettingsToDisk(g.IO.IniFilename);
15603 SameLine();
15604 if (g.IO.IniFilename)
15605 Text("\"%s\"", g.IO.IniFilename);
15606 else
15607 TextUnformatted("<NULL>");
15608 Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
15609 Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
15610 if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
15611 {
15612 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15613 BulletText("\"%s\"", handler.TypeName);
15614 TreePop();
15615 }
15616 if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
15617 {
15618 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15619 DebugNodeWindowSettings(settings);
15620 TreePop();
15621 }
15622
15623 if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
15624 {
15625 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
15626 DebugNodeTableSettings(settings);
15627 TreePop();
15628 }
15629
15630 #ifdef IMGUI_HAS_DOCK
15631 #endif // #ifdef IMGUI_HAS_DOCK
15632
15633 if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
15634 {
15635 InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
15636 TreePop();
15637 }
15638 TreePop();
15639 }
15640
15641 // Settings
15642 if (TreeNode("Memory allocations"))
15643 {
15644 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
15645 Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
15646 if (SmallButton("GC now")) { g.GcCompactAll = true; }
15647 Text("Recent frames with allocations:");
15648 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
15649 for (int n = buf_size - 1; n >= 0; n--)
15650 {
15651 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
15652 BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
15653 if (n == 0)
15654 {
15655 SameLine();
15656 Text("<- %d frames ago", g.FrameCount - entry->FrameCount);
15657 }
15658 }
15659 TreePop();
15660 }
15661
15662 if (TreeNode("Inputs"))
15663 {
15664 Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
15665 {
15666 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
15667 Indent();
15668 Text("Keys down:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
15669 Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
15670 Text("Keys released:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
15671 Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
15672 Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
15673 DebugRenderKeyboardPreview(GetWindowDrawList());
15674 Unindent();
15675 }
15676
15677 Text("MOUSE STATE");
15678 {
15679 Indent();
15680 if (IsMousePosValid())
15681 Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
15682 else
15683 Text("Mouse pos: <INVALID>");
15684 Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
15685 int count = IM_ARRAYSIZE(io.MouseDown);
15686 Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
15687 Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
15688 Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
15689 Text("Mouse wheel: %.1f", io.MouseWheel);
15690 Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
15691 Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
15692 Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
15693 Unindent();
15694 }
15695
15696 Text("MOUSE WHEELING");
15697 {
15698 Indent();
15699 Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
15700 Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
15701 Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
15702 Unindent();
15703 }
15704
15705 Text("KEY OWNERS");
15706 {
15707 Indent();
15708 if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
15709 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
15710 {
15711 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
15712 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
15713 continue;
15714 Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
15715 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
15716 DebugLocateItemOnHover(owner_data->OwnerCurr);
15717 }
15718 EndChild();
15719 Unindent();
15720 }
15721 Text("SHORTCUT ROUTING");
15722 SameLine();
15723 MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
15724 {
15725 Indent();
15726 if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
15727 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
15728 {
15729 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
15730 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
15731 {
15732 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
15733 ImGuiKeyChord key_chord = key | routing_data->Mods;
15734 Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
15735 DebugLocateItemOnHover(routing_data->RoutingCurr);
15736 if (g.IO.ConfigDebugIsDebuggerPresent)
15737 {
15738 SameLine();
15739 if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
15740 g.DebugBreakInShortcutRouting = key_chord;
15741 }
15742 idx = routing_data->NextEntryIndex;
15743 }
15744 }
15745 EndChild();
15746 Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
15747 Unindent();
15748 }
15749 TreePop();
15750 }
15751
15752 if (TreeNode("Internal state"))
15753 {
15754 Text("WINDOWING");
15755 Indent();
15756 Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
15757 Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
15758 Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
15759 Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
15760 Unindent();
15761
15762 Text("ITEMS");
15763 Indent();
15764 Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
15765 DebugLocateItemOnHover(g.ActiveId);
15766 Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
15767 Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
15768 Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
15769 Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
15770 Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
15771 DebugLocateItemOnHover(g.DragDropPayload.SourceId);
15772 Unindent();
15773
15774 Text("NAV,FOCUS");
15775 Indent();
15776 Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
15777 Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
15778 DebugLocateItemOnHover(g.NavId);
15779 Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
15780 Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
15781 Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
15782 Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
15783 Text("NavActivateFlags: %04X", g.NavActivateFlags);
15784 Text("NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav);
15785 Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
15786 Text("NavFocusRoute[] = ");
15787 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
15788 {
15789 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
15790 SameLine(0.0f, 0.0f);
15791 Text("0x%08X/", focus_scope.ID);
15792 SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
15793 }
15794 Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
15795 Unindent();
15796
15797 TreePop();
15798 }
15799
15800 // Overlay: Display windows Rectangles and Begin Order
15801 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
15802 {
15803 for (ImGuiWindow* window : g.Windows)
15804 {
15805 if (!window->WasActive)
15806 continue;
15807 ImDrawList* draw_list = GetForegroundDrawList(window);
15808 if (cfg->ShowWindowsRects)
15809 {
15810 ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
15811 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
15812 }
15813 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
15814 {
15815 char buf[32];
15816 ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
15817 float font_size = GetFontSize();
15818 draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
15819 draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
15820 }
15821 }
15822 }
15823
15824 // Overlay: Display Tables Rectangles
15825 if (cfg->ShowTablesRects)
15826 {
15827 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
15828 {
15829 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
15830 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
15831 continue;
15832 ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
15833 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
15834 {
15835 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
15836 {
15837 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
15838 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
15839 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
15840 draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
15841 }
15842 }
15843 else
15844 {
15845 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
15846 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
15847 }
15848 }
15849 }
15850
15851 #ifdef IMGUI_HAS_DOCK
15852 // Overlay: Display Docking info
15853 if (show_docking_nodes && g.IO.KeyCtrl)
15854 {
15855 }
15856 #endif // #ifdef IMGUI_HAS_DOCK
15857
15858 End();
15859 }
15860
15861 void ImGui::DebugBreakClearData()
15862 {
15863 // Those fields are scattered in their respective subsystem to stay in hot-data locations
15864 ImGuiContext& g = *GImGui;
15865 g.DebugBreakInWindow = 0;
15866 g.DebugBreakInTable = 0;
15867 g.DebugBreakInShortcutRouting = ImGuiKey_None;
15868 }
15869
15870 void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
15871 {
15872 if (!BeginItemTooltip())
15873 return;
15874 Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
15875 Separator();
15876 TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
15877 Separator();
15878 TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
15879 EndTooltip();
15880 }
15881
15882 // Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
15883 // In order to reduce interferences with the contents we are trying to debug into.
15884 bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
15885 {
15886 ImGuiWindow* window = GetCurrentWindow();
15887 if (window->SkipItems)
15888 return false;
15889
15890 ImGuiContext& g = *GImGui;
15891 const ImGuiID id = window->GetID(label);
15892 const ImVec2 label_size = CalcTextSize(label, NULL, true);
15893 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
15894 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
15895
15896 const ImRect bb(pos, pos + size);
15897 ItemSize(size, 0.0f);
15898 if (!ItemAdd(bb, id))
15899 return false;
15900
15901 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
15902 bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
15903 bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
15904 DebugBreakButtonTooltip(false, description_of_location);
15905
15906 ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
15907 ImVec4 hsv;
15908 ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
15909 ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
15910
15911 RenderNavCursor(bb, id);
15912 RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
15913 RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
15914
15915 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
15916 return pressed;
15917 }
15918
15919 // [DEBUG] Display contents of Columns
15920 void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
15921 {
15922 if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
15923 return;
15924 BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
15925 for (ImGuiOldColumnData& column : columns->Columns)
15926 BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
15927 TreePop();
15928 }
15929
15930 // [DEBUG] Display contents of ImDrawList
15931 void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
15932 {
15933 ImGuiContext& g = *GImGui;
15934 IM_UNUSED(viewport); // Used in docking branch
15935 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
15936 int cmd_count = draw_list->CmdBuffer.Size;
15937 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
15938 cmd_count--;
15939 bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
15940 if (draw_list == GetWindowDrawList())
15941 {
15942 SameLine();
15943 TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
15944 if (node_open)
15945 TreePop();
15946 return;
15947 }
15948
15949 ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
15950 if (window && IsItemHovered() && fg_draw_list)
15951 fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
15952 if (!node_open)
15953 return;
15954
15955 if (window && !window->WasActive)
15956 TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
15957
15958 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
15959 {
15960 if (pcmd->UserCallback)
15961 {
15962 BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
15963 continue;
15964 }
15965
15966 char texid_desc[20];
15967 FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
15968 char buf[300];
15969 ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
15970 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
15971 bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
15972 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
15973 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
15974 if (!pcmd_node_open)
15975 continue;
15976
15977 // Calculate approximate coverage area (touched pixel count)
15978 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
15979 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
15980 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
15981 float total_area = 0.0f;
15982 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
15983 {
15984 ImVec2 triangle[3];
15985 for (int n = 0; n < 3; n++, idx_n++)
15986 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
15987 total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
15988 }
15989
15990 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
15991 ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
15992 Selectable(buf);
15993 if (IsItemHovered() && fg_draw_list)
15994 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
15995
15996 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
15997 ImGuiListClipper clipper;
15998 clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
15999 while (clipper.Step())
16000 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
16001 {
16002 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
16003 ImVec2 triangle[3];
16004 for (int n = 0; n < 3; n++, idx_i++)
16005 {
16006 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
16007 triangle[n] = v.pos;
16008 buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
16009 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
16010 }
16011
16012 Selectable(buf, false);
16013 if (fg_draw_list && IsItemHovered())
16014 {
16015 ImDrawListFlags backup_flags = fg_draw_list->Flags;
16016 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
16017 fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
16018 fg_draw_list->Flags = backup_flags;
16019 }
16020 }
16021 TreePop();
16022 }
16023 TreePop();
16024 }
16025
16026 // [DEBUG] Display mesh/aabb of a ImDrawCmd
16027 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
16028 {
16029 IM_ASSERT(show_mesh || show_aabb);
16030
16031 // Draw wire-frame version of all triangles
16032 ImRect clip_rect = draw_cmd->ClipRect;
16033 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
16034 ImDrawListFlags backup_flags = out_draw_list->Flags;
16035 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
16036 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
16037 {
16038 ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
16039 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
16040
16041 ImVec2 triangle[3];
16042 for (int n = 0; n < 3; n++, idx_n++)
16043 vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
16044 if (show_mesh)
16045 out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
16046 }
16047 // Draw bounding boxes
16048 if (show_aabb)
16049 {
16050 out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
16051 out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
16052 }
16053 out_draw_list->Flags = backup_flags;
16054 }
16055
16056 // [DEBUG] Display details for a single font, called by ShowStyleEditor().
16057 void ImGui::DebugNodeFont(ImFont* font)
16058 {
16059 bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
16060 font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
16061 SameLine();
16062 if (SmallButton("Set as default"))
16063 GetIO().FontDefault = font;
16064 if (!opened)
16065 return;
16066
16067 // Display preview text
16068 PushFont(font);
16069 Text("The quick brown fox jumps over the lazy dog");
16070 PopFont();
16071
16072 // Display details
16073 SetNextItemWidth(GetFontSize() * 8);
16074 DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
16075 SameLine(); MetricsHelpMarker(
16076 "Note that the default embedded font is NOT meant to be scaled.\n\n"
16077 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
16078 "You may oversample them to get some flexibility with scaling. "
16079 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
16080 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
16081 Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
16082 char c_str[5];
16083 Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
16084 Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
16085 const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
16086 Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
16087 for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
16088 if (font->ConfigData)
16089 if (const ImFontConfig* cfg = &font->ConfigData[config_i])
16090 BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
16091 config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
16092
16093 // Display all glyphs of the fonts in separate pages of 256 characters
16094 if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
16095 {
16096 ImDrawList* draw_list = GetWindowDrawList();
16097 const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
16098 const float cell_size = font->FontSize * 1;
16099 const float cell_spacing = GetStyle().ItemSpacing.y;
16100 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
16101 {
16102 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
16103 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
16104 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
16105 if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
16106 {
16107 base += 4096 - 256;
16108 continue;
16109 }
16110
16111 int count = 0;
16112 for (unsigned int n = 0; n < 256; n++)
16113 if (font->FindGlyphNoFallback((ImWchar)(base + n)))
16114 count++;
16115 if (count <= 0)
16116 continue;
16117 if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
16118 continue;
16119
16120 // Draw a 16x16 grid of glyphs
16121 ImVec2 base_pos = GetCursorScreenPos();
16122 for (unsigned int n = 0; n < 256; n++)
16123 {
16124 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
16125 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
16126 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
16127 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
16128 const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
16129 draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
16130 if (!glyph)
16131 continue;
16132 font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
16133 if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
16134 {
16135 DebugNodeFontGlyph(font, glyph);
16136 EndTooltip();
16137 }
16138 }
16139 Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
16140 TreePop();
16141 }
16142 TreePop();
16143 }
16144 TreePop();
16145 }
16146
16147 void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
16148 {
16149 Text("Codepoint: U+%04X", glyph->Codepoint);
16150 Separator();
16151 Text("Visible: %d", glyph->Visible);
16152 Text("AdvanceX: %.1f", glyph->AdvanceX);
16153 Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
16154 Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
16155 }
16156
16157 // [DEBUG] Display contents of ImGuiStorage
16158 void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
16159 {
16160 if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
16161 return;
16162 for (const ImGuiStoragePair& p : storage->Data)
16163 {
16164 BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
16165 DebugLocateItemOnHover(p.key);
16166 }
16167 TreePop();
16168 }
16169
16170 // [DEBUG] Display contents of ImGuiTabBar
16171 void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
16172 {
16173 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
16174 char buf[256];
16175 char* p = buf;
16176 const char* buf_end = buf + IM_ARRAYSIZE(buf);
16177 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
16178 p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
16179 for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
16180 {
16181 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16182 p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
16183 }
16184 p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
16185 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
16186 bool open = TreeNode(label, "%s", buf);
16187 if (!is_active) { PopStyleColor(); }
16188 if (is_active && IsItemHovered())
16189 {
16190 ImDrawList* draw_list = GetForegroundDrawList();
16191 draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
16192 draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
16193 draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
16194 }
16195 if (open)
16196 {
16197 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16198 {
16199 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16200 PushID(tab);
16201 if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
16202 if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
16203 Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
16204 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
16205 PopID();
16206 }
16207 TreePop();
16208 }
16209 }
16210
16211 void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
16212 {
16213 ImGuiContext& g = *GImGui;
16214 SetNextItemOpen(true, ImGuiCond_Once);
16215 bool open = TreeNode("viewport0", "Viewport #%d", 0);
16216 if (IsItemHovered())
16217 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
16218 if (open)
16219 {
16220 ImGuiWindowFlags flags = viewport->Flags;
16221 BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
16222 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
16223 viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y);
16224 BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags,
16225 (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "",
16226 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
16227 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "");
16228 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
16229 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
16230 TreePop();
16231 }
16232 }
16233
16234 void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
16235 {
16236 if (window == NULL)
16237 {
16238 BulletText("%s: NULL", label);
16239 return;
16240 }
16241
16242 ImGuiContext& g = *GImGui;
16243 const bool is_active = window->WasActive;
16244 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
16245 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
16246 const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
16247 if (!is_active) { PopStyleColor(); }
16248 if (IsItemHovered() && is_active)
16249 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
16250 if (!open)
16251 return;
16252
16253 if (window->MemoryCompacted)
16254 TextDisabled("Note: some memory buffers have been compacted/freed.");
16255
16256 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
16257 g.DebugBreakInWindow = window->ID;
16258
16259 ImGuiWindowFlags flags = window->Flags;
16260 DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
16261 BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
16262 BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
16263 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
16264 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
16265 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
16266 if (flags & ImGuiWindowFlags_ChildWindow)
16267 BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
16268 (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "",
16269 (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
16270 (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
16271 (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
16272 BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
16273 BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
16274 BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
16275 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
16276 {
16277 ImRect r = window->NavRectRel[layer];
16278 if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
16279 BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
16280 else
16281 BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
16282 DebugLocateItemOnHover(window->NavLastIds[layer]);
16283 }
16284 const ImVec2* pr = window->NavPreferredScoringPosRel;
16285 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
16286 BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
16287 BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
16288 if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
16289 if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
16290 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
16291 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
16292 if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
16293 {
16294 for (ImGuiOldColumns& columns : window->ColumnsStorage)
16295 DebugNodeColumns(&columns);
16296 TreePop();
16297 }
16298 DebugNodeStorage(&window->StateStorage, "Storage");
16299 TreePop();
16300 }
16301
16302 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
16303 {
16304 if (settings->WantDelete)
16305 BeginDisabled();
16306 Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
16307 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
16308 if (settings->WantDelete)
16309 EndDisabled();
16310 }
16311
16312 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
16313 {
16314 if (!TreeNode(label, "%s (%d)", label, windows->Size))
16315 return;
16316 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
16317 {
16318 PushID((*windows)[i]);
16319 DebugNodeWindow((*windows)[i], "Window");
16320 PopID();
16321 }
16322 TreePop();
16323 }
16324
16325 // FIXME-OPT: This is technically suboptimal, but it is simpler this way.
16326 void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
16327 {
16328 for (int i = 0; i < windows_size; i++)
16329 {
16330 ImGuiWindow* window = windows[i];
16331 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
16332 continue;
16333 char buf[20];
16334 ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
16335 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
16336 DebugNodeWindow(window, buf);
16337 Indent();
16338 DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
16339 Unindent();
16340 }
16341 }
16342
16343 //-----------------------------------------------------------------------------
16344 // [SECTION] DEBUG LOG WINDOW
16345 //-----------------------------------------------------------------------------
16346
16347 void ImGui::DebugLog(const char* fmt, ...)
16348 {
16349 va_list args;
16350 va_start(args, fmt);
16351 DebugLogV(fmt, args);
16352 va_end(args);
16353 }
16354
16355 void ImGui::DebugLogV(const char* fmt, va_list args)
16356 {
16357 ImGuiContext& g = *GImGui;
16358 const int old_size = g.DebugLogBuf.size();
16359 if (g.ContextName[0] != 0)
16360 g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
16361 else
16362 g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
16363 g.DebugLogBuf.appendfv(fmt, args);
16364 g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
16365 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
16366 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
16367 #ifdef IMGUI_ENABLE_TEST_ENGINE
16368 // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
16369 const int new_size = g.DebugLogBuf.size();
16370 const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
16371 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
16372 IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
16373 #endif
16374 }
16375
16376 // FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
16377 static void SameLineOrWrap(const ImVec2& size)
16378 {
16379 ImGuiContext& g = *GImGui;
16380 ImGuiWindow* window = g.CurrentWindow;
16381 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
16382 if (window->WorkRect.Contains(ImRect(pos, pos + size)))
16383 ImGui::SameLine();
16384 }
16385
16386 static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
16387 {
16388 ImGuiContext& g = *GImGui;
16389 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
16390 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
16391
16392 bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0);
16393 if (highlight_errors)
16394 ImGui::PushStyleColor(ImGuiCol_Text, ImLerp(g.Style.Colors[ImGuiCol_Text], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.30f));
16395 if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
16396 {
16397 g.DebugLogAutoDisableFrames = 2;
16398 g.DebugLogAutoDisableFlags |= flags;
16399 }
16400 if (highlight_errors)
16401 {
16402 ImGui::PopStyleColor();
16403 ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors);
16404 }
16405 else
16406 {
16407 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
16408 }
16409 }
16410
16411 void ImGui::ShowDebugLogWindow(bool* p_open)
16412 {
16413 ImGuiContext& g = *GImGui;
16414 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0)
16415 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
16416 if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
16417 {
16418 End();
16419 return;
16420 }
16421
16422 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
16423 CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
16424 SetItemTooltip("(except InputRouting which is spammy)");
16425
16426 ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError);
16427 ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
16428 ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
16429 ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
16430 ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
16431 //ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont);
16432 ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
16433 ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
16434 ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
16435 ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
16436
16437 if (SmallButton("Clear"))
16438 {
16439 g.DebugLogBuf.clear();
16440 g.DebugLogIndex.clear();
16441 g.DebugLogSkippedErrors = 0;
16442 }
16443 SameLine();
16444 if (SmallButton("Copy"))
16445 SetClipboardText(g.DebugLogBuf.c_str());
16446 SameLine();
16447 if (SmallButton("Configure Outputs.."))
16448 OpenPopup("Outputs");
16449 if (BeginPopup("Outputs"))
16450 {
16451 CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
16452 #ifndef IMGUI_ENABLE_TEST_ENGINE
16453 BeginDisabled();
16454 #endif
16455 CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
16456 #ifndef IMGUI_ENABLE_TEST_ENGINE
16457 EndDisabled();
16458 #endif
16459 EndPopup();
16460 }
16461
16462 BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
16463
16464 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
16465 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
16466
16467 ImGuiListClipper clipper;
16468 clipper.Begin(g.DebugLogIndex.size());
16469 while (clipper.Step())
16470 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
16471 DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
16472 g.DebugLogFlags = backup_log_flags;
16473 if (GetScrollY() >= GetScrollMaxY())
16474 SetScrollHereY(1.0f);
16475 EndChild();
16476
16477 End();
16478 }
16479
16480 // Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
16481 void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
16482 {
16483 TextUnformatted(line_begin, line_end);
16484 if (!IsItemHovered())
16485 return;
16486 ImGuiContext& g = *GImGui;
16487 ImRect text_rect = g.LastItemData.Rect;
16488 for (const char* p = line_begin; p <= line_end - 10; p++)
16489 {
16490 ImGuiID id = 0;
16491 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10]))
16492 continue;
16493 ImVec2 p0 = CalcTextSize(line_begin, p);
16494 ImVec2 p1 = CalcTextSize(p, p + 10);
16495 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
16496 if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
16497 DebugLocateItemOnHover(id);
16498 p += 10;
16499 }
16500 }
16501
16502 //-----------------------------------------------------------------------------
16503 // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
16504 //-----------------------------------------------------------------------------
16505
16506 // Draw a small cross at current CursorPos in current window's DrawList
16507 void ImGui::DebugDrawCursorPos(ImU32 col)
16508 {
16509 ImGuiContext& g = *GImGui;
16510 ImGuiWindow* window = g.CurrentWindow;
16511 ImVec2 pos = window->DC.CursorPos;
16512 window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
16513 window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
16514 }
16515
16516 // Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
16517 void ImGui::DebugDrawLineExtents(ImU32 col)
16518 {
16519 ImGuiContext& g = *GImGui;
16520 ImGuiWindow* window = g.CurrentWindow;
16521 float curr_x = window->DC.CursorPos.x;
16522 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
16523 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
16524 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
16525 window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
16526 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
16527 }
16528
16529 // Draw last item rect in ForegroundDrawList (so it is always visible)
16530 void ImGui::DebugDrawItemRect(ImU32 col)
16531 {
16532 ImGuiContext& g = *GImGui;
16533 ImGuiWindow* window = g.CurrentWindow;
16534 GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
16535 }
16536
16537 // [DEBUG] Locate item position/rectangle given an ID.
16538 static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
16539
16540 void ImGui::DebugLocateItem(ImGuiID target_id)
16541 {
16542 ImGuiContext& g = *GImGui;
16543 g.DebugLocateId = target_id;
16544 g.DebugLocateFrames = 2;
16545 g.DebugBreakInLocateId = false;
16546 }
16547
16548 // FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
16549 void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
16550 {
16551 if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
16552 return;
16553 ImGuiContext& g = *GImGui;
16554 DebugLocateItem(target_id);
16555 GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
16556
16557 // Can't easily use a context menu here because it will mess with focus, active id etc.
16558 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
16559 {
16560 DebugBreakButtonTooltip(false, "in ItemAdd()");
16561 if (IsKeyChordPressed(g.DebugBreakKeyChord))
16562 g.DebugBreakInLocateId = true;
16563 }
16564 }
16565
16566 void ImGui::DebugLocateItemResolveWithLastItem()
16567 {
16568 ImGuiContext& g = *GImGui;
16569
16570 // [DEBUG] Debug break requested by user
16571 if (g.DebugBreakInLocateId)
16572 IM_DEBUG_BREAK();
16573
16574 ImGuiLastItemData item_data = g.LastItemData;
16575 g.DebugLocateId = 0;
16576 ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
16577 ImRect r = item_data.Rect;
16578 r.Expand(3.0f);
16579 ImVec2 p1 = g.IO.MousePos;
16580 ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
16581 draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
16582 draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
16583 }
16584
16585 void ImGui::DebugStartItemPicker()
16586 {
16587 ImGuiContext& g = *GImGui;
16588 g.DebugItemPickerActive = true;
16589 }
16590
16591 // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
16592 void ImGui::UpdateDebugToolItemPicker()
16593 {
16594 ImGuiContext& g = *GImGui;
16595 g.DebugItemPickerBreakId = 0;
16596 if (!g.DebugItemPickerActive)
16597 return;
16598
16599 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
16600 SetMouseCursor(ImGuiMouseCursor_Hand);
16601 if (IsKeyPressed(ImGuiKey_Escape))
16602 g.DebugItemPickerActive = false;
16603 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
16604 if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
16605 {
16606 g.DebugItemPickerBreakId = hovered_id;
16607 g.DebugItemPickerActive = false;
16608 }
16609 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
16610 if (change_mapping && IsMouseClicked(mouse_button))
16611 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
16612 SetNextWindowBgAlpha(0.70f);
16613 if (!BeginTooltip())
16614 return;
16615 Text("HoveredId: 0x%08X", hovered_id);
16616 Text("Press ESC to abort picking.");
16617 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
16618 if (change_mapping)
16619 Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
16620 else
16621 TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
16622 EndTooltip();
16623 }
16624
16625 // [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
16626 void ImGui::UpdateDebugToolStackQueries()
16627 {
16628 ImGuiContext& g = *GImGui;
16629 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
16630
16631 // Clear hook when id stack tool is not visible
16632 g.DebugHookIdInfo = 0;
16633 if (g.FrameCount != tool->LastActiveFrame + 1)
16634 return;
16635
16636 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
16637 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
16638 const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
16639 if (tool->QueryId != query_id)
16640 {
16641 tool->QueryId = query_id;
16642 tool->StackLevel = -1;
16643 tool->Results.resize(0);
16644 }
16645 if (query_id == 0)
16646 return;
16647
16648 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
16649 int stack_level = tool->StackLevel;
16650 if (stack_level >= 0 && stack_level < tool->Results.Size)
16651 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
16652 tool->StackLevel++;
16653
16654 // Update hook
16655 stack_level = tool->StackLevel;
16656 if (stack_level == -1)
16657 g.DebugHookIdInfo = query_id;
16658 if (stack_level >= 0 && stack_level < tool->Results.Size)
16659 {
16660 g.DebugHookIdInfo = tool->Results[stack_level].ID;
16661 tool->Results[stack_level].QueryFrameCount++;
16662 }
16663 }
16664
16665 // [DEBUG] ID Stack tool: hooks called by GetID() family functions
16666 void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
16667 {
16668 ImGuiContext& g = *GImGui;
16669 ImGuiWindow* window = g.CurrentWindow;
16670 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
16671
16672 // Step 0: stack query
16673 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
16674 if (tool->StackLevel == -1)
16675 {
16676 tool->StackLevel++;
16677 tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
16678 for (int n = 0; n < window->IDStack.Size + 1; n++)
16679 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
16680 return;
16681 }
16682
16683 // Step 1+: query for individual level
16684 IM_ASSERT(tool->StackLevel >= 0);
16685 if (tool->StackLevel != window->IDStack.Size)
16686 return;
16687 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
16688 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
16689
16690 switch (data_type)
16691 {
16692 case ImGuiDataType_S32:
16693 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
16694 break;
16695 case ImGuiDataType_String:
16696 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
16697 break;
16698 case ImGuiDataType_Pointer:
16699 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
16700 break;
16701 case ImGuiDataType_ID:
16702 if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
16703 return;
16704 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
16705 break;
16706 default:
16707 IM_ASSERT(0);
16708 }
16709 info->QuerySuccess = true;
16710 info->DataType = data_type;
16711 }
16712
16713 static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
16714 {
16715 ImGuiStackLevelInfo* info = &tool->Results[n];
16716 ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
16717 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
16718 return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
16719 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
16720 return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
16721 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
16722 return (*buf = 0);
16723 #ifdef IMGUI_ENABLE_TEST_ENGINE
16724 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
16725 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
16726 #endif
16727 return ImFormatString(buf, buf_size, "???");
16728 }
16729
16730 // ID Stack Tool: Display UI
16731 void ImGui::ShowIDStackToolWindow(bool* p_open)
16732 {
16733 ImGuiContext& g = *GImGui;
16734 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0)
16735 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
16736 if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
16737 {
16738 End();
16739 return;
16740 }
16741
16742 // Display hovered/active status
16743 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
16744 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
16745 const ImGuiID active_id = g.ActiveId;
16746 #ifdef IMGUI_ENABLE_TEST_ENGINE
16747 Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
16748 #else
16749 Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
16750 #endif
16751 SameLine();
16752 MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
16753
16754 // CTRL+C to copy path
16755 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
16756 Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
16757 SameLine();
16758 TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
16759 if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
16760 {
16761 tool->CopyToClipboardLastTime = (float)g.Time;
16762 char* p = g.TempBuffer.Data;
16763 char* p_end = p + g.TempBuffer.Size;
16764 for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
16765 {
16766 *p++ = '/';
16767 char level_desc[256];
16768 StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
16769 for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
16770 {
16771 if (level_desc[n] == '/')
16772 *p++ = '\\';
16773 *p++ = level_desc[n];
16774 }
16775 }
16776 *p = '\0';
16777 SetClipboardText(g.TempBuffer.Data);
16778 }
16779
16780 // Display decorated stack
16781 tool->LastActiveFrame = g.FrameCount;
16782 if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
16783 {
16784 const float id_width = CalcTextSize("0xDDDDDDDD").x;
16785 TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
16786 TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
16787 TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
16788 TableHeadersRow();
16789 for (int n = 0; n < tool->Results.Size; n++)
16790 {
16791 ImGuiStackLevelInfo* info = &tool->Results[n];
16792 TableNextColumn();
16793 Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
16794 TableNextColumn();
16795 StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
16796 TextUnformatted(g.TempBuffer.Data);
16797 TableNextColumn();
16798 Text("0x%08X", info->ID);
16799 if (n == tool->Results.Size - 1)
16800 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
16801 }
16802 EndTable();
16803 }
16804 End();
16805 }
16806
16807 #else
16808
16809 void ImGui::ShowMetricsWindow(bool*) {}
16810 void ImGui::ShowFontAtlas(ImFontAtlas*) {}
16811 void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
16812 void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
16813 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
16814 void ImGui::DebugNodeFont(ImFont*) {}
16815 void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
16816 void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
16817 void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
16818 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
16819 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
16820 void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
16821
16822 void ImGui::ShowDebugLogWindow(bool*) {}
16823 void ImGui::ShowIDStackToolWindow(bool*) {}
16824 void ImGui::DebugStartItemPicker() {}
16825 void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
16826
16827 #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
16828
16829 //-----------------------------------------------------------------------------
16830
16831 // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
16832 // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
16833 #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
16834 #include "imgui_user.inl"
16835 #endif
16836
16837 //-----------------------------------------------------------------------------
16838
16839 #endif // #ifndef IMGUI_DISABLE