upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/imgui/imgui.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/imgui/imgui.cpp')
-rw-r--r--src/imgui/imgui.cpp18628
1 files changed, 18628 insertions, 0 deletions
diff --git a/src/imgui/imgui.cpp b/src/imgui/imgui.cpp
new file mode 100644
index 0000000..da2780f
--- /dev/null
+++ b/src/imgui/imgui.cpp
@@ -0,0 +1,18628 @@
1// dear imgui, v1.92.9
2// (main code and documentation)
3
4// Help:
5// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
6// - Read top of imgui.cpp for more details, links and comments.
7// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including imgui.h (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4.
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// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
19// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
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// - Web version of the Demo .... https://pthom.github.io/imgui_explorer (w/ source code browser)
24
25// For FIRST-TIME users having issues compiling/linking/running:
26// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
27// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
28// Since 1.92, we encourage font loading questions to also be posted in 'Issues'.
29
30// Copyright (c) 2014-2026 Omar Cornut
31// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
32// See LICENSE.txt for copyright and licensing details (standard MIT License).
33// This library is free but needs your support to sustain development and maintenance.
34// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
35// PLEASE reach out at omar AT discohello DOT com. See https://github.com/ocornut/imgui/wiki/Funding
36// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
37
38// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
39// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
40// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
41// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
42// to a better solution or official support for them.
43
44/*
45
46Index of this file:
47
48DOCUMENTATION
49
50- MISSION STATEMENT
51- CONTROLS GUIDE
52- PROGRAMMER GUIDE
53 - READ FIRST
54 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
55 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
56 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
57 - USING CUSTOM BACKEND / CUSTOM ENGINE
58- API BREAKING CHANGES (read me when you update!)
59- FREQUENTLY ASKED QUESTIONS (FAQ)
60 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
61
62CODE
63(search for "[SECTION]" in the code to find them)
64
65// [SECTION] INCLUDES
66// [SECTION] FORWARD DECLARATIONS
67// [SECTION] CONTEXT AND MEMORY ALLOCATORS
68// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
69// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
70// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
71// [SECTION] MISC HELPERS/UTILITIES (File functions)
72// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
73// [SECTION] MISC HELPERS/UTILITIES (Color functions)
74// [SECTION] ImGuiStorage
75// [SECTION] ImGuiTextFilter
76// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
77// [SECTION] ImGuiListClipper
78// [SECTION] STYLING
79// [SECTION] RENDER HELPERS
80// [SECTION] INITIALIZATION, SHUTDOWN
81// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
82// [SECTION] FONTS, TEXTURES
83// [SECTION] ID STACK
84// [SECTION] INPUTS
85// [SECTION] ERROR CHECKING, STATE RECOVERY
86// [SECTION] ITEM SUBMISSION
87// [SECTION] LAYOUT
88// [SECTION] SCROLLING
89// [SECTION] TOOLTIPS
90// [SECTION] POPUPS
91// [SECTION] WINDOW FOCUS
92// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
93// [SECTION] DRAG AND DROP
94// [SECTION] LOGGING/CAPTURING
95// [SECTION] SETTINGS
96// [SECTION] LOCALIZATION
97// [SECTION] VIEWPORTS, PLATFORM WINDOWS
98// [SECTION] PLATFORM DEPENDENT HELPERS
99// [SECTION] METRICS/DEBUGGER WINDOW
100// [SECTION] DEBUG LOG WINDOW
101// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
102
103*/
104
105//-----------------------------------------------------------------------------
106// DOCUMENTATION
107//-----------------------------------------------------------------------------
108
109/*
110
111 MISSION STATEMENT
112 =================
113
114 - Easy to use to create code-driven and data-driven tools.
115 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
116 - Easy to hack and improve.
117 - Minimize setup and maintenance.
118 - Minimize state storage on user side.
119 - Minimize state synchronization.
120 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
121 - Efficient runtime and memory consumption.
122
123 Designed primarily for developers and content-creators, not the typical end-user!
124 Some of the current weaknesses (which we aim to address in the future) includes:
125
126 - Doesn't look fancy by default.
127 - Limited layout features, intricate layouts are typically crafted in code.
128
129
130 CONTROLS GUIDE
131 ==============
132
133 - MOUSE CONTROLS
134 - Mouse wheel: Scroll vertically.
135 - Shift+Mouse wheel: Scroll horizontally.
136 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
137 - Click ^, Double-Click title: Collapse window.
138 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
139 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
140 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
141
142 - TEXT EDITOR
143 - Hold Shift or Drag Mouse: Select text.
144 - Ctrl+Left/Right: Word jump.
145 - Ctrl+Shift+Left/Right: Select words.
146 - Ctrl+A or Double-Click: Select All.
147 - Ctrl+X, Ctrl+C, Ctrl+V: Use OS clipboard.
148 - Ctrl+Z Undo.
149 - Ctrl+Y or Ctrl+Shift+Z: Redo.
150 - ESCAPE: Revert text to its original value.
151 - On macOS, controls are automatically adjusted to match standard macOS text editing and behaviors.
152 (for 99% of shortcuts, Ctrl is replaced by Cmd on macOS).
153
154 - KEYBOARD CONTROLS
155 - Basic:
156 - Tab, Shift+Tab Cycle through text editable fields.
157 - Ctrl+Tab, Ctrl+Shift+Tab Cycle through windows.
158 - Ctrl+Click Input text into a Slider or Drag widget.
159 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
160 - Tab, Shift+Tab: Cycle through every items.
161 - Arrow keys Move through items using directional navigation. Tweak value.
162 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
163 - Enter Activate item (prefer text input when possible).
164 - Space Activate item (prefer tweaking with arrows when possible).
165 - Escape Deactivate item, leave child window, close popup.
166 - Page Up, Page Down Previous page, next page.
167 - Home, End Scroll to top, scroll to bottom.
168 - Alt Toggle between scrolling layer and menu layer.
169 - Ctrl+Tab then Ctrl+Arrows Move window. Hold Shift to resize instead of moving.
170 - Menu or Shift+F10 Open context menu.
171 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
172 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
173 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
174 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
175
176 - GAMEPAD CONTROLS
177 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
178 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
179 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
180 - Backend support: backend needs to:
181 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
182 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
183 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.).
184 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
185 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
186
187 - REMOTE INPUTS SHARING & MOUSE EMULATION
188 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
189 - 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)
190 in order to share your PC mouse/keyboard.
191 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
192 - 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.
193 Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
194 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.
195 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.
196 (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!)
197 (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
198 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
199
200
201 PROGRAMMER GUIDE
202 ================
203
204 READ FIRST
205 ----------
206 - Remember to check the wonderful Wiki: https://github.com/ocornut/imgui/wiki
207 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
208 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
209 data retention on your side, less state duplication, less state synchronization, fewer bugs.
210 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
211 Or browse pthom's online imgui_explorer: https://pthom.github.io/imgui_explorer for a web version w/ source code browser.
212 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
213 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
214 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
215 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
216 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,
217 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
218 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
219 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
220 If you get an assert, read the messages and comments around the assert.
221 - This codebase aims to be highly optimized:
222 - A typical idle frame should never call malloc/free.
223 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
224 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
225 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
226 - This codebase aims to be both highly opinionated and highly flexible:
227 - This code works because of the things it choose to solve or not solve.
228 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
229 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
230 This is to increase compatibility, increase maintainability and facilitate use from other languages.
231 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
232 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
233 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
234 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
235 (so don't use ImVector in your code or at our own risk!).
236 - Building: We don't use nor mandate a build system for the main library.
237 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
238 This is also because providing a build system for the main library would be of little-value.
239 The build problems are almost never coming from the main library but from specific backends.
240
241
242 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
243 ----------------------------------------------
244 - Update submodule or copy/overwrite every file.
245 - About imconfig.h:
246 - You may modify your copy of imconfig.h, in this case don't overwrite it.
247 - or you may locally branch to modify imconfig.h and merge/rebase latest.
248 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
249 specify a custom path for your imconfig.h file and instead not have to modify the default one.
250
251 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
252 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
253 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
254 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
255 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
256 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
257 likely be a comment about it. Please report any issue to the GitHub page!
258 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
259 - Try to keep your copy of Dear ImGui reasonably up to date!
260
261
262 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
263 ---------------------------------------------------------------
264 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
265 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
266 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
267 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
268 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
269 - 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.
270 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
271 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
272 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
273 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
274 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
275 - 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.
276
277
278 HOW A SIMPLE APPLICATION MAY LOOK LIKE
279 --------------------------------------
280
281 USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
282 The sub-folders in examples/ contain examples applications following this structure.
283
284 // Application init: create a dear imgui context, setup some options, load fonts
285 ImGui::CreateContext();
286 ImGuiIO& io = ImGui::GetIO();
287 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
288 // TODO: Fill optional fields of the io structure later.
289 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
290
291 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
292 ImGui_ImplWin32_Init(hwnd);
293 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
294
295 // Application main loop
296 while (true)
297 {
298 // Feed inputs to dear imgui, start new frame
299 ImGui_ImplDX11_NewFrame();
300 ImGui_ImplWin32_NewFrame();
301 ImGui::NewFrame();
302
303 // Any application code here
304 ImGui::Text("Hello, world!");
305
306 // Render dear imgui into framebuffer
307 ImGui::Render();
308 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
309 g_pSwapChain->Present(1, 0);
310 }
311
312 // Shutdown
313 ImGui_ImplDX11_Shutdown();
314 ImGui_ImplWin32_Shutdown();
315 ImGui::DestroyContext();
316
317 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
318 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
319 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
320
321
322USING CUSTOM BACKEND / CUSTOM ENGINE
323------------------------------------
324
325IMPLEMENTING YOUR PLATFORM BACKEND:
326 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions.
327 -> the Platform backends in impl_impl_XXX.cpp files contain many implementations.
328
329IMPLEMENTING YOUR RenderDrawData() function:
330 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
331 -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function.
332
333IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures:
334 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
335 -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function.
336
337 Basic application/backend skeleton:
338
339 // Application init: create a Dear ImGui context, setup some options, load fonts
340 ImGui::CreateContext();
341 ImGuiIO& io = ImGui::GetIO();
342 // TODO: set io.ConfigXXX values, e.g.
343 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls
344
345 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
346 io.Fonts->AddFontFromFileTTF("NotoSans.ttf");
347
348 // Application main loop
349 while (true)
350 {
351 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
352 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
353 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
354 io.DisplaySize.x = 1920.0f; // set the current display width
355 io.DisplaySize.y = 1280.0f; // set the current display height here
356 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
357 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
358 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
359
360 // Call NewFrame(), after this point you can use ImGui::* functions anytime
361 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
362 ImGui::NewFrame();
363
364 // Most of your application code here
365 ImGui::Text("Hello, world!");
366 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
367 MyGameRender(); // may use any Dear ImGui functions as well!
368
369 // End the dear imgui frame
370 // (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)
371 ImGui::EndFrame(); // this is automatically called by Render(), but available
372 ImGui::Render();
373
374 // Update textures
375 ImDrawData* draw_data = ImGui::GetDrawData();
376 for (ImTextureData* tex : *draw_data->Textures)
377 if (tex->Status != ImTextureStatus_OK)
378 MyImGuiBackend_UpdateTexture(tex);
379
380 // Render dear imgui contents, swap buffers
381 MyImGuiBackend_RenderDrawData(draw_data);
382 SwapBuffers();
383 }
384
385 // Shutdown
386 ImGui::DestroyContext();
387
388
389
390 API BREAKING CHANGES
391 ====================
392
393 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
394 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.
395 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.
396 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
397
398 - 2026/07/20 (1.92.9) - DragXXX, SliderXXX, InputScalar: with `ImGuiItemFlags_LiveEditOnInputScalar` now defaulting to being disabled:
399 inputting a value with the keyboard doesn't write intermediate values to backing variable. (#9476)
400 - Before: DragFloat() with user typing "123" --> write back 1, then 12, then 123.
401 - After: DragFloat() with user typing "123" --> write back 123 when validated/unfocused.
402 You can enable the flag back for a given scope if needed by specific widget/behavior.
403 - 2026/07/20 (1.92.9) - ImDrawData: marked ImDrawData::CmdListsCount as obsolete (technically was obsoleted in 1.89.8).
404 - Before: draw_data->CmdListsCount
405 - After: draw_data->CmdLists.Size
406 - 2026/07/08 (1.92.9) - Drag and Drop: commented out legacy name `ImGuiDragDropFlags_SourceAutoExpirePayload` which obsoleted in 1.90.9 (July 2024). Use `ImGuiDragDropFlags_PayloadAutoExpire`.
407 - 2026/07/06 (1.92.9) - ColorEdit: obsoleted SetColorEditOptions() function added in 1.51 (June 2017) in favor of directly poking to io.ConfigColorEditFlags. More consistent and easier to discover.
408 - 2026/06/02 (1.92.9) - TreeNode: commented out legacy name ImGuiTreeNodeFlags_SpanTextWidth which was obsoleted in 1.90.7 (May 2024). Use ImGuiTreeNodeFlags_SpanLabelWidth instead.
409 - 2026/05/07 (1.92.8) - DrawList: swapped the last two arguments of AddRect(), AddPolyline(), PathStroke().
410 - Before: void ImDrawList::AddRect(ImVec2 p_min, ImVec2 p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f);
411 - After: void ImDrawList::AddRect(ImVec2 p_min, ImVec2 p_max, ImU32 col, float rounding = 0.0f, float thickness = 1.0f, ImDrawFlags flags = 0);
412 - Before: void ImDrawList::AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness);
413 - After: void ImDrawList::AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0);
414 - Before: void ImDrawList::PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f);
415 - After: void ImDrawList::PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0);
416 Added inline redirection functions when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is off.
417 Marked the old functions are =delete when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is on, to allow for better type-checking.
418 Effectively the typical call site is changing from:
419 - Before: window->DrawList->AddRect(p_min, p_max, color, rounding, ImDrawFlags_None, border_size);
420 - After: window->DrawList->AddRect(p_min, p_max, color, rounding, border_size);
421 Notes:
422 - Users of C++ and other languages with type-checking will be notified at compile-time of any mistakes.
423 - Users of high-level bindings or languages with no type-checking will be notified at runtime via an assert for invalid flags value.
424 If you are a binding maintainer consider doing something to facilitate transition or error detection.
425 - This is perhaps the worst breaking change in our history :( but it makes ImDrawList function signatures consistent.
426 As we are aiming to add flags and features to variety of ImDrawList functions, that consistency becomes more important.
427 The new order is also more convenient as `flags` are less frequently used than `thickness` in real code.
428 - As a general policy in Dear ImGui, all our flags default to 0 so ImDrawFlags_None was likely written 0 in some call sites.
429 - Consider adding `#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS` in your imconfig.h, even temporarily, to clean up legacy code.
430 - 2026/05/07 (1.92.8) - DrawList: changed value of `ImDrawFlags_Closed`. It was previously advertised as "always == 1" when introduced in 1.82 (2021/02), in order to facilitate backward compatibility with the legacy `bool closed` flag.
431 This guarantee has been removed. The bit is reserved and `AddPolyline()`, `PathStroke()` will assert when it is used.
432 - 2026/04/23 (1.92.8) - DrawList: obsoleted `ImDrawCallback_ResetRenderState` in favor of using `ImGui::GetPlatformIO().DrawCallback_ResetRenderState`, which is part of our new standard draw callbacks. (#9378)
433 - 2026/04/22 (1.92.8) - Backends: Vulkan: redesigned to use separate ImageView + Sampler instead of Combined Image Sampler.
434 - When registering custom textures: changed ImGui_ImplVulkan_AddTexture() signature to remove Sampler.
435 - When creating your own descriptor pool (instead of letting backend creates its own): need at least IMGUI_IMPL_VULKAN_MINIMUM_SAMPLED_IMAGE_POOL_SIZE descriptors of type VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE + IMGUI_IMPL_VULKAN_MINIMUM_SAMPLER_POOL_SIZE descriptors of type VK_DESCRIPTOR_TYPE_SAMPLER.
436 - 2026/03/19 (1.92.7) - MultiSelect: renamed ImGuiMultiSelectFlags_SelectOnClick to ImGuiMultiSelectFlags_SelectOnAuto.
437 - 2026/02/26 (1.92.7) - Separator: fixed a legacy quirk where Separator() was submitting a zero-height item for layout purpose, even though it draws a 1-pixel separator.
438 The fix could affect code e.g. computing height from multiple widgets in order to allocate vertical space for a footer or multi-line status bar. (#2657, #9263)
439 The "Console" example had such a bug:
440 float footer_height = style.ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
441 BeginChild("ScrollingRegion", { 0, -footer_height });
442 Should be:
443 float footer_height = style.ItemSpacing.y + style.SeparatorSize + ImGui::GetFrameHeightWithSpacing();
444 BeginChild("ScrollingRegion", { 0, -footer_height });
445 When such idiom was used and assuming zero-height Separator, it is likely that in 1.92.7 the resulting window will have unexpected 1 pixel scrolling range.
446 - 2026/02/23 (1.92.7) - Commented out legacy signature for Combo(), ListBox(), signatures which were obsoleted in 1.90 (Nov 2023), when the getter callback type was changed.
447 - Old getter type: bool (*getter)(void* user_data, int idx, const char** out_text) // Set label + return bool. False replaced label with placeholder.
448 - New getter type: const char* (*getter)(void* user_data, int idx) // Return label or NULL/empty label if missing
449 - 2026/01/08 (1.92.6) - Commented out legacy names obsoleted in 1.90 (Sept 2023): 'BeginChildFrame()' --> 'BeginChild()' with 'ImGuiChildFlags_FrameStyle'. 'EndChildFrame()' --> 'EndChild()'. 'ShowStackToolWindow()' --> 'ShowIDStackToolWindow()'. 'IM_OFFSETOF()' --> 'offsetof()'.
450 - 2026/01/07 (1.92.6) - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). Default value has same meaning before and after.
451 - Refer to GitHub topic #9157 if you have any question.
452 - Before this version, those functions had a 'ImGuiPopupFlags popup_flags = 1' default value in their function signature.
453 Explicitly passing a literal 0 meant ImGuiPopupFlags_MouseButtonLeft. The default literal 1 meant ImGuiPopupFlags_MouseButtonRight.
454 This was introduced by a change on 2020/06/23 (1.77) while changing the signature from 'int mouse_button' to 'ImGuiPopupFlags popup_flags' and trying to preserve then-legacy behavior.
455 We have now changed this behavior to cleanup a very old API quirk, facilitate use by bindings, and to remove the last and error-prone non-zero default value.
456 Also because we deemed it extremely rare to use those helper functions with the Left mouse button! As using the LMB would generally be triggered via another widget, e.g. a Button() + a OpenPopup()/BeginPopup() call.
457 - Before: The default = 1 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 0 means ImGuiPopupFlags_MouseButtonLeft.
458 - After: The default = 0 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 1 also means ImGuiPopupFlags_MouseButtonRight (if legacy behavior are enabled) or will assert (if legacy behavior are disabled).
459 - TL;DR: if you don't want to use right mouse button for popups, always specify it explicitly using a named ImGuiPopupFlags_MouseButtonXXXX value.
460 Recap:
461 - BeginPopupContextItem("foo"); // Behavior unchanged (use Right button)
462 - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft); // Behavior unchanged (use Left button)
463 - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft | xxx); // Behavior unchanged (use Left button + flags)
464 - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonRight | xxx); // Behavior unchanged (use Right button + flags)
465 - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors.
466 - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft.
467 - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx.
468 - 2025/12/23 (1.92.6) - Fonts: AddFontDefault() now automatically selects an embedded font between the new scalable AddFontDefaultVector() and the classic pixel-clean AddFontDefaultBitmap().
469 The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold, but old codebases may not set any of them properly. As as a result, it is likely that old codebase may still default to AddFontDefaultBitmap().
470 Prefer calling either based on your own logic. You can call AddFontDefaultBitmap() to ensure legacy behavior.
471 - 2025/12/23 (1.92.6) - Fonts: removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded.
472 - 2025/12/17 (1.92.6) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name for now.
473 - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore.
474 - Before: GetID("Hello###World") == GetID("###World") != GetID("World")
475 - After: GetID("Hello###World") == GetID("###World") == GetID("World")
476 - This has the property of facilitating concatenating and manipulating identifiers using "###", and will allow fixing other dangling issues.
477 - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698)
478 - 2025/11/24 (1.92.6) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory.
479 (trivia: undetected since July 2015, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature, see #9086)
480 HOWEVER, fixing this bug is likely to surface bugs in user code using `FontDataOwnedByAtlas = false`.
481 - Prior to 1.92, font data only needed to be available during the atlas->AddFontXXX() call.
482 - Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically until a shutdown of the owning context or font atlas.
483 - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed the issue altogether.
484 - 2025/11/06 (1.92.5) - BeginChild: commented out some legacy names which were obsoleted in 1.90.0 (Nov 2023), 1.90.9 (July 2024), 1.91.1 (August 2024):
485 - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders
486 - ImGuiWindowFlags_NavFlattened --> ImGuiChildFlags_NavFlattened (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0)
487 - ImGuiWindowFlags_AlwaysUseWindowPadding --> ImGuiChildFlags_AlwaysUseWindowPadding (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0)
488 - 2025/11/06 (1.92.5) - Keys: commented out legacy names which were obsoleted in 1.89.0 (August 2022):
489 - ImGuiKey_ModCtrl --> ImGuiMod_Ctrl
490 - ImGuiKey_ModShift --> ImGuiMod_Shift
491 - ImGuiKey_ModAlt --> ImGuiMod_Alt
492 - ImGuiKey_ModSuper --> ImGuiMod_Super
493 - 2025/11/06 (1.92.5) - IO: commented out legacy io.ClearInputCharacters() obsoleted in 1.89.8 (Aug 2023). Calling io.ClearInputKeys() is enough.
494 - 2025/11/06 (1.92.5) - Commented out legacy SetItemAllowOverlap() obsoleted in 1.89.7: this never worked right. Use SetNextItemAllowOverlap() _before_ item instead.
495 - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023);
496 - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap
497 - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap
498 - ImGuiListClipper::IncludeRangeByIndices() --> ImGuiListClipper::IncludeItemsByIndex()
499 - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988)
500 - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete).
501 - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM
502 to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150)
503 - Incorrect way to make a window content size 200x200:
504 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
505 - Correct ways to make a window content size 200x200:
506 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
507 Begin(...) + Dummy(ImVec2(200,200)) + End();
508 - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries.
509 - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED.
510 IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/
511 As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+).
512 If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes.
513 - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this!
514 - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f):
515 This WILL NOT map correctly to the new system! Because font will rasterize as requested size.
516 - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required.
517 - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch.
518 - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized.
519 - PushFont() API now has a REQUIRED size parameter.
520 - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize).
521 - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value.
522 - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site.
523 - Kept inline single parameter function. Will obsolete.
524 - Fonts: **IMPORTANT** on Font Merging:
525 - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph.
526 Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font.
527 - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before!
528 - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1.
529 After the update and when using a new backend, those glyphs may now loaded from Font Source 1!
530 - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source:
531 // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
532 static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
533 ImFontConfig cfg1;
534 cfg1.GlyphExcludeRanges = exclude_ranges;
535 io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
536 // Add Font Source 2, which expects to use the range above
537 ImFontConfig cfg2;
538 cfg2.MergeMode = true;
539 io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
540 - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph.
541 - Fonts: **IMPORTANT** on Thread Safety:
542 - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even though we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded.
543 - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont().
544 - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font".
545 - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'.
546 - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded().
547 - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete).
548 - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling.
549 - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese().
550 - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327)
551 - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one), you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't.
552 - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors.
553 - Fonts: obsoleted ImFont::Scale which is not useful anymore.
554 - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things:
555 - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef.
556 - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef.
557 - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]
558 - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount.
559 - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size.
560 - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance().
561 - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels().
562 - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.)
563 - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags.
564 If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader().
565 - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()
566 - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader()
567 - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1]
568 - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV().
569 - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h.
570 - old:
571 const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id);
572 ImVec2 uv0, uv1;
573 atlas->GetCustomRectUV(r, &uv0, &uv1);
574 ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1);
575 - new;
576 ImFontAtlasRect r;
577 atlas->GetCustomRect(custom_rect_id, &r);
578 ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
579 - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple.
580 - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code.
581 - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
582 - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture().
583 - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more.
584 - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition()
585 - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....);
586 - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....);
587 The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function.
588 - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete).
589 - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092)
590 - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead.
591 - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name.
592 - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387)
593 - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238)
594 - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0));
595 - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1));
596 - new: void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1));
597 - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton().
598 - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize.
599 - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable.
600 - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified.
601 - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg().
602 - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount.
603 - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX.
604 - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior.
605 prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior.
606 the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls:
607 - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937)
608 - 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.
609 As a result, old .ini data may be partially lost (docking and tables information particularly).
610 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.
611 - 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)
612 - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
613 - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
614 - GetKeyIndex() is removed (obsoleted March 2022). The indirection is now unnecessary.
615 - pre-1.87 backends are not supported:
616 - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
617 - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
618 - for more reference:
619 - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
620 - read https://github.com/ocornut/imgui/issues/4921
621 - 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.
622 - 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?
623 - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
624 - 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).
625 - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
626 moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
627 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!
628 - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
629 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.
630 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().
631 in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
632 - May warn: ImGui::Image((void*)MyTextureData, ...);
633 - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
634 - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData, ...);
635 - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
636 - 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)
637 - 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).
638 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)
639 - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
640 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()
641 - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
642 - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
643 - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
644 - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line.
645 - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660)
646 - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
647 - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278)
648 - access those via GetPlatformIO() instead of GetIO().
649 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.
650 - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder:
651 - 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)
652 - new ImageButton() since 1.89 requires an explicit 'const char* str_id'
653 - old ImageButton() before 1.89 had frame_padding' override argument.
654 - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar().
655 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
656 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
657 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
658 - you can use: GetContentRegionAvail().x
659 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
660 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
661 - instead of: GetContentRegionMax()
662 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
663 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
664 - you can use: GetContentRegionAvail() // when called from left edge of window
665 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
666 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
667 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
668 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
669 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
670 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
671 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
672 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
673 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
674 - 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.
675 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
676 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
677 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
678 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
679 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
680 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
681 - 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.
682 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
683 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
684 - old: CaptureKeyboardFromApp(bool)
685 - new: SetNextFrameWantCaptureKeyboard(bool)
686 - old: CaptureMouseFromApp(bool)
687 - new: SetNextFrameWantCaptureMouse(bool)
688 - 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).
689 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
690 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
691 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
692 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
693 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
694 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
695 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
696 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
697 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
698 for various reasons those changes makes sense. They are being made because making some of those API public.
699 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.
700 - 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.
701 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
702 - 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)
703 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
704 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
705 - 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).
706 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
707 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
708 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.
709 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
710 - 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)
711 - 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)
712 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
713 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
714 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
715 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
716 - 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.
717 - 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.
718 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
719 - 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).
720 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.
721 - 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.
722 - old: BeginChild("Name", size, true)
723 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
724 - old: BeginChild("Name", size, false)
725 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
726 **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'**
727 - 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.
728 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
729 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
730 - 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).
731 - 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)
732 - 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).
733 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
734 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
735 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
736 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
737 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
738 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
739 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
740 - 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
741 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
742 - 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. (#6406, #4879, #1878)
743 - use `draw_data->CmdLists.Size` instead of `draw_list->CmdListsCount`.
744 - use `draw_data->AddDrawList()` to add to a ImDrawData.
745 - 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).
746 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
747 - 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.
748 - 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)
749 - 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.
750 - 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.
751 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
752 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
753 - ListBoxFooter() -> use EndListBox()
754 - 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().
755 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
756 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
757 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
758 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
759 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
760 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
761 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
762 - 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.
763 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
764 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
765 it has been frequently requested by people to use our own. We had an opt-in define which was
766 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
767 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
768 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
769 - 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.
770 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
771 - 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.
772 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
773 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
774 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
775 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
776 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
777 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
778 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
779 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.
780 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
781 this will require uses of legacy backend-dependent indices to be casted, e.g.
782 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
783 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
784 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
785 - 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);
786 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
787 - 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.
788 - 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.
789 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
790 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
791 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
792 - previously this would make the window content size ~200x200:
793 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
794 - instead, please submit an item:
795 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
796 - alternative:
797 Begin(...) + Dummy(ImVec2(200,200)) + End();
798 - content size is now only extended when submitting an item!
799 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
800 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
801 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
802 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
803 - 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));
804 - 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.
805 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
806 - 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));
807 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
808 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
809 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
810 - Official backends from 1.87+ -> no issue.
811 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
812 - Custom backends not writing to io.NavInputs[] -> no issue.
813 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
814 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
815 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
816 - 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.
817 - 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.
818 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
819 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
820 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputting text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
821 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
822 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
823 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
824 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
825 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
826 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
827 read https://github.com/ocornut/imgui/issues/4921 for details.
828 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). 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.
829 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
830 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
831 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes).
832 - 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.*
833 - 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.
834 - 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.
835 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
836 - 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'.
837 - 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)
838 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
839 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
840 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
841 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
842 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
843 - 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
844 - 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.
845 - 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.
846 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
847 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
848 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
849 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
850 - if you are using official backends from the source tree: you have nothing to do.
851 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
852 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
853 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
854 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
855 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
856 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
857 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
858 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
859 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
860 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
861 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
862 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
863 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.
864 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).
865 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
866 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
867 - 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.
868 - 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.
869 - 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'.
870 - 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.
871 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
872 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
873 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
874 - 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.
875 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
876 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
877 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
878 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
879 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
880 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
881 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
882 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
883 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
884 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
885 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
886 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
887 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
888 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
889 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
890 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
891 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
892 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
893 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
894 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
895 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
896 - 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).
897 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
898 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
899 - 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.
900 - 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.
901 - 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!
902 - 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().
903 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
904 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
905 - if you omitted the 'power' parameter (likely!), you are not affected.
906 - 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.
907 - 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.
908 see https://github.com/ocornut/imgui/issues/3361 for all details.
909 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.
910 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
911 - 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.
912 - 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.
913 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
914 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
915 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
916 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
917 - 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.
918 - 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.
919 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
920 - ShowTestWindow() -> use ShowDemoWindow()
921 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
922 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
923 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f))
924 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
925 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
926 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
927 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
928 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
929 - 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.
930 - 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).
931 - 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.
932 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
933 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
934 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
935 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
936 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
937 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
938 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
939 - ImFont::Glyph -> use ImFontGlyph
940 - 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.
941 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.
942 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).
943 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
944 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
945 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
946 - 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.
947 - 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
948 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.
949 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.
950 Please reach out if you are affected.
951 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
952 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
953 - 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.
954 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
955 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
956 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
957 - 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!
958 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
959 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
960 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
961 - 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.
962 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
963 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
964 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
965 - 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.
966 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
967 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
968 - 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.
969 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
970 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
971 - 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).
972 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
973 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
974 - 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.
975 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
976 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
977 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
978 - 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.).
979 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
980 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
981 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
982 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
983 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
984 - 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.
985 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
986 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.
987 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.
988 - 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",
989 consistent with other functions. Kept redirection functions (will obsolete).
990 - 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.
991 - 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).
992 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
993 - 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.
994 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
995 - 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.
996 - 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.
997 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
998 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
999 - removed Shutdown() function, as DestroyContext() serve this purpose.
1000 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
1001 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
1002 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
1003 - 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.
1004 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
1005 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
1006 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
1007 - 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.
1008 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
1009 - 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
1010 - 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.
1011 - 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.
1012 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
1013 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
1014 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
1015 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
1016 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
1017 - 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.
1018 - 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.
1019 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.
1020 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
1021 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
1022 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
1023 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
1024 - 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.
1025 - 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.
1026 - 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.
1027 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
1028 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
1029 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
1030 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
1031 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
1032 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
1033 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
1034 - 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).
1035 - 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)".
1036 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
1037 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
1038 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
1039 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
1040 - 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 explicitly to fix.
1041 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
1042 - 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.
1043 - 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).
1044 - 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).
1045 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
1046 - 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.
1047 - 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.
1048 - 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))'
1049 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
1050 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
1051 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
1052 - 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().
1053 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
1054 - 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.
1055 - 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.
1056 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
1057 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.
1058 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:
1059 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); }
1060 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.
1061 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
1062 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
1063 - 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).
1064 - 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.
1065 - 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).
1066 - 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)
1067 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
1068 - 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.
1069 - 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.
1070 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
1071 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
1072 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
1073 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.
1074 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!
1075 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
1076 - 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.
1077 - 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
1078 - 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.
1079 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
1080 - 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.
1081 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
1082 - 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.
1083 - the signature of the io.RenderDrawListsFn handler has changed!
1084 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
1085 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
1086 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
1087 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
1088 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
1089 - 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.
1090 - 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!
1091 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
1092 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
1093 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
1094 - 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.
1095 - 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
1096 - 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!
1097 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
1098 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
1099 - 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.
1100 - 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.
1101 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
1102 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
1103 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
1104 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
1105 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
1106 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
1107 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
1108 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
1109 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
1110 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
1111 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
1112 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
1113 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
1114 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
1115 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
1116 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
1117 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
1118 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
1119 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
1120 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
1121 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.
1122 - 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()
1123 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
1124 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
1125 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
1126 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
1127 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
1128 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
1129 - 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)
1130 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
1131 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
1132 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
1133 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
1134 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
1135 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
1136
1137
1138 FREQUENTLY ASKED QUESTIONS (FAQ)
1139 ================================
1140
1141 Read all answers online:
1142 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
1143 Read all answers locally (with a text editor or ideally a Markdown viewer):
1144 docs/FAQ.md
1145 Some answers are copied down here to facilitate searching in code.
1146
1147 Q&A: Basics
1148 ===========
1149
1150 Q: Where is the documentation?
1151 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
1152 - Run the examples/ applications and explore them.
1153 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
1154 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
1155 - See pthom's online imgui_explorer (https://pthom.github.io/imgui_explorer) which is a web
1156 version of the demo with a source code browser.
1157 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
1158 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
1159 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
1160 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
1161 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
1162 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
1163 - Your programming IDE is your friend, find the type or function declaration to find comments
1164 associated with it.
1165
1166 Q: What is this library called?
1167 Q: What is the difference between Dear ImGui and traditional UI toolkits?
1168 Q: Which version should I get?
1169 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
1170 >> See https://www.dearimgui.com/faq for details.
1171
1172 Q&A: Integration
1173 ================
1174
1175 Q: How to get started?
1176 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
1177
1178 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
1179 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
1180 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
1181
1182 Q. How can I enable keyboard or gamepad controls?
1183 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
1184 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
1185 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
1186 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
1187 >> See https://www.dearimgui.com/faq
1188
1189 Q&A: Usage
1190 ----------
1191
1192 Q: About the ID Stack system..
1193 - How can I have multiple widgets with the same label? (using ## or PushID)
1194 - How can I have widgets with an empty label? (using ##)
1195 - How can I make a label dynamic? (using ###)
1196 - General description of the label and ID Stack system.
1197 Q: How can I display an image? What is ImTextureID, how does it work?
1198 Q: How can I use my own math types instead of ImVec2?
1199 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
1200 Q: How can I display custom shapes? (using low-level ImDrawList API)
1201 Q: About Multi-Threading
1202 >> See https://www.dearimgui.com/faq
1203
1204 Q&A: Fonts, Text
1205 ================
1206
1207 Q: How should I handle DPI in my application?
1208 Q: How can I load a different font than the default?
1209 Q: How can I easily use icons in my application?
1210 Q: How can I load multiple fonts?
1211 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
1212 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
1213
1214 Q&A: Concerns
1215 =============
1216
1217 Q: Who uses Dear ImGui?
1218 Q: Can you create elaborate/serious tools with Dear ImGui?
1219 Q: Can you reskin the look of Dear ImGui?
1220 Q: Why using C++ (as opposed to C)?
1221 >> See https://www.dearimgui.com/faq
1222
1223 Q&A: Community
1224 ==============
1225
1226 Q: How can I help?
1227 A: - Businesses: please reach out to "omar AT discohello DOT com" if you work in a place using Dear ImGui!
1228 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1229 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1230 >>> See https://github.com/ocornut/imgui/wiki/Funding
1231 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1232 - 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!
1233 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1234 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1235 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1236 - 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).
1237
1238*/
1239
1240//-------------------------------------------------------------------------
1241// [SECTION] INCLUDES
1242//-------------------------------------------------------------------------
1243
1244#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1245#define _CRT_SECURE_NO_WARNINGS
1246#endif
1247
1248#ifndef IMGUI_DEFINE_MATH_OPERATORS
1249#define IMGUI_DEFINE_MATH_OPERATORS
1250#endif
1251
1252#include "imgui.h"
1253#ifndef IMGUI_DISABLE
1254#include "imgui_internal.h"
1255
1256// System includes
1257#include <stdio.h> // vsnprintf, sscanf, printf
1258#include <stdint.h> // intptr_t
1259#ifndef IMGUI_DISABLE_TIME_FUNCTIONS
1260#include <time.h> // time(), localtime_r()/localtime_s()
1261#if defined(_WIN32)
1262static tm* localtime_r(const time_t* timep, tm* result) { return localtime_s(result, timep) == 0 ? result : NULL; }
1263#endif
1264#endif
1265
1266// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1267#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1268#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1269#endif
1270
1271// [Windows] OS specific includes (optional)
1272#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)
1273#define IMGUI_DISABLE_WIN32_FUNCTIONS
1274#endif
1275#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1276#ifndef WIN32_LEAN_AND_MEAN
1277#define WIN32_LEAN_AND_MEAN
1278#endif
1279#ifndef NOMINMAX
1280#define NOMINMAX
1281#endif
1282#ifndef __MINGW32__
1283#include <Windows.h> // _wfopen, OpenClipboard
1284#else
1285#include <windows.h>
1286#endif
1287#if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
1288// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1289#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1290#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1291#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1292#endif
1293#endif
1294
1295// [Apple] OS specific includes
1296#if defined(__APPLE__)
1297#include <TargetConditionals.h>
1298#endif
1299
1300// Visual Studio warnings
1301#ifdef _MSC_VER
1302#pragma warning (disable: 4127) // condition expression is constant
1303#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1304#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1305#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1306#endif
1307#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).
1308#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1309#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1310#endif
1311
1312// Clang/GCC warnings with -Weverything
1313#if defined(__clang__)
1314#if __has_warning("-Wunknown-warning-option")
1315#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!
1316#endif
1317#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1318#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1319#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.
1320#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int'
1321#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.
1322#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.
1323#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.
1324#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1325#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1326#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1327#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1328#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.
1329#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1330#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1331#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
1332#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
1333#elif defined(__GNUC__)
1334// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1335#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1336#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1337#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1338#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
1339#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
1340#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1341#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1342#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1343#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1344#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
1345#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
1346#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result
1347#endif
1348
1349// Debug options
1350#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.
1351#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1352
1353// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls.
1354static const float FONT_DEFAULT_SIZE_BASE = 20.0f;
1355
1356// 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.
1357static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1358static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1359static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1360static const float NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60f; // Time to hold activation button (e.g. FaceDown) to turn the activation into a text input.
1361static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1362static 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.
1363
1364// Tooltip offset
1365static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1366static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale
1367static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale
1368
1369//-------------------------------------------------------------------------
1370// [SECTION] FORWARD DECLARATIONS
1371//-------------------------------------------------------------------------
1372
1373static void SetCurrentWindow(ImGuiWindow* window);
1374static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1375static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1376
1377static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1378
1379// Settings
1380static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1381static void WindowSettingsHandler_Cleanup(ImGuiContext*, ImGuiSettingsHandler*, ImGuiSettingsCleanupArgs* args);
1382static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1383static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1384static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1385static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1386
1387// Platform Dependents default implementation for ImGuiPlatformIO functions
1388static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx);
1389static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text);
1390static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1391static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1392
1393namespace ImGui
1394{
1395// Item
1396static void ItemHandleShortcut(ImGuiID id);
1397
1398// Window Focus
1399static int FindWindowFocusIndex(ImGuiWindow* window);
1400static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags);
1401
1402// Navigation
1403static void NavUpdate();
1404static void NavUpdateWindowing();
1405static void NavUpdateWindowingApplyFocus(ImGuiWindow* window);
1406static void NavUpdateWindowingOverlay();
1407static void NavUpdateCancelRequest();
1408static void NavUpdateContextMenuRequest();
1409static void NavUpdateCreateMoveRequest();
1410static void NavUpdateCreateTabbingRequest();
1411static float NavUpdatePageUpPageDown();
1412static inline void NavUpdateAnyRequestFlag();
1413static void NavUpdateCreateWrappingRequest();
1414static void NavEndFrame();
1415static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb);
1416static void NavApplyItemToResult(ImGuiNavItemData* result);
1417static void NavProcessItem();
1418static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1419static ImGuiInputSource NavCalcPreferredRefPosSource(ImGuiWindowFlags window_type);
1420static ImVec2 NavCalcPreferredRefPos(ImGuiWindowFlags window_type);
1421static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1422static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1423static void NavRestoreLayer(ImGuiNavLayer layer);
1424
1425// Error Checking and Debug Tools
1426static void ErrorCheckNewFrameSanityChecks();
1427static void ErrorCheckEndFrameSanityChecks();
1428#ifndef IMGUI_DISABLE_DEBUG_TOOLS
1429static void UpdateDebugToolItemPicker();
1430static void UpdateDebugToolItemPathQuery();
1431static void UpdateDebugToolFlashStyleColor();
1432#endif
1433
1434// Inputs
1435static void UpdateKeyboardInputs();
1436static void UpdateMouseInputs();
1437static void UpdateMouseWheel();
1438static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1439
1440// Misc
1441static void UpdateFontsNewFrame();
1442static void UpdateFontsEndFrame();
1443static void UpdateTexturesNewFrame();
1444static void UpdateTexturesEndFrame();
1445static void UpdateSettings();
1446static int UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1447static void RenderWindowOuterBorders(ImGuiWindow* window);
1448static 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);
1449static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1450static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1451static void RenderDimmedBackgrounds();
1452static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1453static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect);
1454
1455// Viewports
1456const 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.
1457static void UpdateViewportsNewFrame();
1458
1459}
1460
1461//-----------------------------------------------------------------------------
1462// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1463//-----------------------------------------------------------------------------
1464
1465// DLL users:
1466// - Heaps and globals are not shared across DLL boundaries!
1467// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1468// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1469// - 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.
1470// - 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).
1471
1472// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1473// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1474// Change to a different context by calling ImGui::SetCurrentContext().
1475// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1476// If you want thread-safety to allow N threads to access N different contexts:
1477// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1478// struct ImGuiContext;
1479// extern thread_local ImGuiContext* MyImGuiTLS;
1480// #define GImGui MyImGuiTLS
1481// 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.
1482// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1483// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1484// - DLL users: read comments above.
1485#ifndef GImGui
1486ImGuiContext* GImGui = NULL;
1487#endif
1488
1489// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1490// - 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.
1491// - DLL users: read comments above.
1492#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1493static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1494static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1495#else
1496static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1497static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1498#endif
1499static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1500static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1501static void* GImAllocatorUserData = NULL;
1502
1503//-----------------------------------------------------------------------------
1504// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
1505//-----------------------------------------------------------------------------
1506
1507ImGuiStyle::ImGuiStyle()
1508{
1509 FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame.
1510 FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user.
1511 FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
1512
1513 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1514 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1515 WindowPadding = ImVec2(8,8); // Padding within a window
1516 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.
1517 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1518 WindowBorderHoverPadding = 4.0f; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders.
1519 WindowMinSize = ImVec2(32,32); // Minimum window size
1520 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1521 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1522 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1523 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1524 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1525 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1526 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1527 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1528 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1529 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1530 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1531 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1532 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!
1533 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1534 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1535 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1536 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1537 ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axes)
1538 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1539 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1540 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1541 ImageRounding = 0.0f; // Rounding of Image() calls.
1542 ImageBorderSize = 0.0f; // Thickness of border around Image() calls.
1543 TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1544 TabBorderSize = 0.0f; // Thickness of border around tabs.
1545 TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
1546 TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy. FLT_MAX: never shrink, will behave like ImGuiTabBarFlags_FittingPolicyScroll.
1547 TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
1548 TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected.
1549 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1550 TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1551 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1552 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1553 TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone;
1554 TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
1555 TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line.
1556 MenuItemRounding = 0.0f; // Radius of MenuItem, BeginMenu rounding.
1557 SelectableRounding = 0.0f; // Radius of selectable rounding. MODIFYING THIS IS DISCOURAGED. CONTIGUOUS SELECTIONS WILL NOT LOOK RIGHT. (#7589)
1558 DragDropTargetRounding = 0.0f; // Radius of the drag and drop target frame.
1559 DragDropTargetBorderSize = 2.0f; // Thickness of the drag and drop target border.
1560 DragDropTargetPadding = 3.0f; // Size to expand the drag and drop target from actual target item size.
1561 ColorMarkerSize = 3.0f; // Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags_ColorMarkers.
1562 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1563 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1564 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.
1565 InputTextCursorSize = 1.0f; // Thickness of cursor/caret in InputText().
1566 SeparatorSize = 1.0f; // Thickness of border in Separator().
1567 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText().
1568 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1569 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.
1570 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.
1571 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.
1572 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1573 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1574 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1575 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1576 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.
1577 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.
1578
1579 // Behaviors
1580 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1581 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1582 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1583 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1584 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1585
1586 // [Internal]
1587 _MainScale = 1.0f;
1588 _NextFrameFontSizeBase = 0.0f;
1589
1590 // Default theme
1591 ImGui::StyleColorsDark(this);
1592}
1593
1594
1595// Scale all spacing/padding/thickness values. Do not scale fonts.
1596// Consider not calling this if your initial scale factor if <1.0.
1597// 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.
1598void ImGuiStyle::ScaleAllSizes(float scale_factor)
1599{
1600 _MainScale *= scale_factor;
1601 WindowPadding = ImTrunc(WindowPadding * scale_factor);
1602 WindowRounding = ImTrunc(WindowRounding * scale_factor);
1603 WindowBorderSize = ImTrunc(WindowBorderSize * scale_factor);
1604 WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1605 WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor);
1606 ChildRounding = ImTrunc(ChildRounding * scale_factor);
1607 ChildBorderSize = ImTrunc(ChildBorderSize * scale_factor);
1608 PopupRounding = ImTrunc(PopupRounding * scale_factor);
1609 PopupBorderSize = ImTrunc(PopupBorderSize * scale_factor);
1610 FramePadding = ImTrunc(FramePadding * scale_factor);
1611 FrameBorderSize = ImTrunc(FrameBorderSize * scale_factor);
1612 FrameRounding = ImTrunc(FrameRounding * scale_factor);
1613 ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1614 ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1615 CellPadding = ImTrunc(CellPadding * scale_factor);
1616 TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1617 IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1618 ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1619 ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1620 ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1621 ScrollbarPadding = ImTrunc(ScrollbarPadding * scale_factor);
1622 GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1623 GrabRounding = ImTrunc(GrabRounding * scale_factor);
1624 LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1625 ImageRounding = ImTrunc(ImageRounding * scale_factor);
1626 ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor);
1627 TabRounding = ImTrunc(TabRounding * scale_factor);
1628 TabBorderSize = ImTrunc(TabBorderSize * scale_factor);
1629 TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor);
1630 TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor);
1631 TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected;
1632 TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected;
1633 TabBarBorderSize = ImTrunc(TabBarBorderSize * scale_factor);
1634 TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
1635 TreeLinesSize = ImTrunc(TreeLinesSize * scale_factor);
1636 TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor);
1637 MenuItemRounding = ImTrunc(MenuItemRounding * scale_factor);
1638 SelectableRounding = ImTrunc(SelectableRounding * scale_factor);
1639 DragDropTargetRounding = ImTrunc(DragDropTargetRounding * scale_factor);
1640 DragDropTargetBorderSize = ImTrunc(DragDropTargetBorderSize * scale_factor);
1641 DragDropTargetPadding = ImTrunc(DragDropTargetPadding * scale_factor);
1642 ColorMarkerSize = ImTrunc(ColorMarkerSize * scale_factor);
1643 InputTextCursorSize = ImTrunc(InputTextCursorSize * scale_factor);
1644 SeparatorSize = ImTrunc(SeparatorSize * scale_factor);
1645 SeparatorTextBorderSize = ImTrunc(SeparatorTextBorderSize * scale_factor);
1646 SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1647 DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1648 DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1649 MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1650}
1651
1652ImGuiIO::ImGuiIO()
1653{
1654 // Most fields are initialized with zero
1655 memset((void*)this, 0, sizeof(*this));
1656 IM_STATIC_ASSERT(IM_COUNTOF(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_COUNTOF(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1657
1658 // Settings
1659 ConfigFlags = ImGuiConfigFlags_None;
1660 BackendFlags = ImGuiBackendFlags_None;
1661 DisplaySize = ImVec2(-1.0f, -1.0f);
1662 DeltaTime = 1.0f / 60.0f;
1663 IniSavingRate = 5.0f;
1664 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).
1665 LogFilename = "imgui_log.txt";
1666 UserData = NULL;
1667
1668 Fonts = NULL;
1669 FontDefault = NULL;
1670 FontAllowUserScaling = false;
1671#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1672 FontGlobalScale = 1.0f; // Use style.FontScaleMain instead!
1673#endif
1674 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1675
1676 // Keyboard/Gamepad Navigation options
1677 ConfigNavSwapGamepadButtons = false;
1678 ConfigNavMoveSetMousePos = false;
1679 ConfigNavCaptureKeyboard = true;
1680 ConfigNavEscapeClearFocusItem = true;
1681 ConfigNavEscapeClearFocusWindow = false;
1682 ConfigNavCursorVisibleAuto = true;
1683 ConfigNavCursorVisibleAlways = false;
1684
1685 // Widget options
1686
1687#ifdef __APPLE__
1688 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1689#else
1690 ConfigMacOSXBehaviors = false;
1691#endif
1692 ConfigInputTrickleEventQueue = true;
1693 ConfigInputTextCursorBlink = true;
1694 ConfigInputTextEnterKeepActive = false;
1695 ConfigDragClickToInputText = false;
1696 ConfigColorEditFlags = ImGuiColorEditFlags_DefaultOptions_; // Current settings for ColorEdit/ColorPicker widgets. May be further edited by users, unless you also set ImGuiColorEditFlags_NoOptions.
1697 ConfigWindowsResizeFromEdges = true;
1698 ConfigWindowsMoveFromTitleBarOnly = false;
1699 ConfigWindowsCopyContentsWithCtrlC = false;
1700 ConfigScrollbarScrollByPage = true;
1701
1702 // Ini Settings options
1703 ConfigIniSettingsSaveLastUsedDate = true;
1704 ConfigIniSettingsAutoDiscardMonths = 0;
1705 ConfigDebugIniSettings = false;
1706
1707 // Miscellaneous options
1708 MouseDrawCursor = false;
1709 ConfigMemoryCompactTimer = 60.0f;
1710
1711 ConfigDebugIsDebuggerPresent = false;
1712 ConfigDebugHighlightIdConflicts = true;
1713 ConfigDebugHighlightIdConflictsShowItemPicker = true;
1714 ConfigDebugBeginReturnValueOnce = false;
1715 ConfigDebugBeginReturnValueLoop = false;
1716
1717 ConfigErrorRecovery = true;
1718 ConfigErrorRecoveryEnableAssert = true;
1719 ConfigErrorRecoveryEnableDebugLog = true;
1720 ConfigErrorRecoveryEnableTooltip = true;
1721
1722 // Inputs Behaviors
1723 MouseDoubleClickTime = 0.30f;
1724 MouseDoubleClickMaxDist = 6.0f;
1725 MouseSingleClickDelay = 0.50f;
1726 MouseDragThreshold = 6.0f;
1727 KeyRepeatDelay = 0.275f;
1728 KeyRepeatRate = 0.050f;
1729
1730 // Platform Functions
1731 // Note: Initialize() will setup default clipboard/ime handlers.
1732 BackendPlatformName = BackendRendererName = NULL;
1733 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1734
1735 // Input (NB: we already have memset zero the entire structure!)
1736 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1737 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1738 MouseSource = ImGuiMouseSource_Mouse;
1739 for (int i = 0; i < IM_COUNTOF(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1740 for (int i = 0; i < IM_COUNTOF(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1741 AppAcceptingEvents = true;
1742}
1743
1744// Pass in translated ASCII characters for text input.
1745// - with glfw you can get those from the callback set in glfwSetCharCallback()
1746// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1747// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1748void ImGuiIO::AddInputCharacter(unsigned int c)
1749{
1750 IM_ASSERT(Ctx != NULL);
1751 ImGuiContext& g = *Ctx;
1752 if (c == 0 || !AppAcceptingEvents)
1753 return;
1754
1755 ImGuiInputEvent e;
1756 e.Type = ImGuiInputEventType_Text;
1757 e.Source = ImGuiInputSource_Keyboard;
1758 e.EventId = g.InputEventsNextEventId++;
1759 e.Text.Char = c;
1760 g.InputEventsQueue.push_back(e);
1761}
1762
1763// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1764// we should save the high surrogate.
1765void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1766{
1767 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1768 return;
1769
1770 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1771 {
1772 if (InputQueueSurrogate != 0)
1773 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1774 InputQueueSurrogate = c;
1775 return;
1776 }
1777
1778 ImWchar cp = c;
1779 if (InputQueueSurrogate != 0)
1780 {
1781 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1782 {
1783 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1784 }
1785 else
1786 {
1787#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1788 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1789#else
1790 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1791#endif
1792 }
1793
1794 InputQueueSurrogate = 0;
1795 }
1796 AddInputCharacter((unsigned)cp);
1797}
1798
1799void ImGuiIO::AddInputCharactersUTF8(const char* str)
1800{
1801 if (!AppAcceptingEvents)
1802 return;
1803 const char* str_end = str + strlen(str);
1804 while (*str != 0)
1805 {
1806 unsigned int c = 0;
1807 str += ImTextCharFromUtf8(&c, str, str_end);
1808 AddInputCharacter(c);
1809 }
1810}
1811
1812// Clear all incoming events.
1813void ImGuiIO::ClearEventsQueue()
1814{
1815 IM_ASSERT(Ctx != NULL);
1816 ImGuiContext& g = *Ctx;
1817 g.InputEventsQueue.clear();
1818}
1819
1820// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1821void ImGuiIO::ClearInputKeys()
1822{
1823 ImGuiContext& g = *Ctx;
1824 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
1825 {
1826 if (ImGui::IsMouseKey((ImGuiKey)key))
1827 continue;
1828 ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
1829 key_data->Down = false;
1830 key_data->DownDuration = -1.0f;
1831 key_data->DownDurationPrev = -1.0f;
1832 }
1833 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1834 KeyMods = ImGuiMod_None;
1835 InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1836}
1837
1838void ImGuiIO::ClearInputMouse()
1839{
1840 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1841 {
1842 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
1843 key_data->Down = false;
1844 key_data->DownDuration = -1.0f;
1845 key_data->DownDurationPrev = -1.0f;
1846 }
1847 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1848 for (int n = 0; n < IM_COUNTOF(MouseDown); n++)
1849 {
1850 MouseDown[n] = false;
1851 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1852 }
1853 MouseWheel = MouseWheelH = 0.0f;
1854}
1855
1856static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1857{
1858 ImGuiContext& g = *ctx;
1859 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1860 {
1861 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1862 if (e->Type != type)
1863 continue;
1864 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1865 continue;
1866 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1867 continue;
1868 return e;
1869 }
1870 return NULL;
1871}
1872
1873// Queue a new key down/up event.
1874// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1875// - bool down: Is the key down? use false to signify a key release.
1876// - float analog_value: 0.0f..1.0f
1877// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1878// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1879void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1880{
1881 //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); }
1882 IM_ASSERT(Ctx != NULL);
1883 if (key == ImGuiKey_None || !AppAcceptingEvents)
1884 return;
1885 ImGuiContext& g = *Ctx;
1886 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.
1887 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1888
1889 // MacOS: swap Cmd(Super) and Ctrl
1890 if (g.IO.ConfigMacOSXBehaviors)
1891 {
1892 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1893 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1894 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1895 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1896 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1897 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1898 }
1899
1900 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1901 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1902 const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1903 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1904 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1905 if (latest_key_down == down && latest_key_analog == analog_value)
1906 return;
1907
1908 // Add event
1909 ImGuiInputEvent e;
1910 e.Type = ImGuiInputEventType_Key;
1911 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1912 e.EventId = g.InputEventsNextEventId++;
1913 e.Key.Key = key;
1914 e.Key.Down = down;
1915 e.Key.AnalogValue = analog_value;
1916 g.InputEventsQueue.push_back(e);
1917}
1918
1919void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1920{
1921 if (!AppAcceptingEvents)
1922 return;
1923 AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1924}
1925
1926// [Optional] Call after AddKeyEvent().
1927// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1928// 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.
1929void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1930{
1931 if (key == ImGuiKey_None)
1932 return;
1933 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1934 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1935 IM_UNUSED(key); // Yet unused
1936 IM_UNUSED(native_keycode); // Yet unused
1937 IM_UNUSED(native_scancode); // Yet unused
1938 IM_UNUSED(native_legacy_index); // Yet unused
1939}
1940
1941// 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.
1942void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1943{
1944 AppAcceptingEvents = accepting_events;
1945}
1946
1947// Queue a mouse move event
1948void ImGuiIO::AddMousePosEvent(float x, float y)
1949{
1950 IM_ASSERT(Ctx != NULL);
1951 ImGuiContext& g = *Ctx;
1952 if (!AppAcceptingEvents)
1953 return;
1954
1955 // Apply same flooring as UpdateMouseInputs()
1956 ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1957
1958 // Filter duplicate
1959 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1960 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1961 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1962 return;
1963
1964 ImGuiInputEvent e;
1965 e.Type = ImGuiInputEventType_MousePos;
1966 e.Source = ImGuiInputSource_Mouse;
1967 e.EventId = g.InputEventsNextEventId++;
1968 e.MousePos.PosX = pos.x;
1969 e.MousePos.PosY = pos.y;
1970 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1971 g.InputEventsQueue.push_back(e);
1972}
1973
1974void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1975{
1976 IM_ASSERT(Ctx != NULL);
1977 ImGuiContext& g = *Ctx;
1978 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1979 if (!AppAcceptingEvents)
1980 return;
1981
1982 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1983 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1984 {
1985 // Order of both statements matters: this event will still release mouse button 1
1986 mouse_button = 1;
1987 if (!down)
1988 MouseCtrlLeftAsRightClick = false;
1989 }
1990
1991 // Filter duplicate
1992 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1993 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1994 if (latest_button_down == down)
1995 return;
1996
1997 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1998 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1999 // - At this point we want from !down to down, so this is handling the initial press.
2000 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
2001 {
2002 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
2003 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
2004 {
2005 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
2006 MouseCtrlLeftAsRightClick = true;
2007 AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
2008 return;
2009 }
2010 }
2011
2012 ImGuiInputEvent e;
2013 e.Type = ImGuiInputEventType_MouseButton;
2014 e.Source = ImGuiInputSource_Mouse;
2015 e.EventId = g.InputEventsNextEventId++;
2016 e.MouseButton.Button = mouse_button;
2017 e.MouseButton.Down = down;
2018 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
2019 g.InputEventsQueue.push_back(e);
2020}
2021
2022// Queue a mouse wheel event (some mouse/API may only have a Y component)
2023void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
2024{
2025 IM_ASSERT(Ctx != NULL);
2026 ImGuiContext& g = *Ctx;
2027
2028 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
2029 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
2030 return;
2031
2032 ImGuiInputEvent e;
2033 e.Type = ImGuiInputEventType_MouseWheel;
2034 e.Source = ImGuiInputSource_Mouse;
2035 e.EventId = g.InputEventsNextEventId++;
2036 e.MouseWheel.WheelX = wheel_x;
2037 e.MouseWheel.WheelY = wheel_y;
2038 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
2039 g.InputEventsQueue.push_back(e);
2040}
2041
2042// This is not a real event, the data is latched in order to be stored in actual Mouse events.
2043// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
2044void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
2045{
2046 IM_ASSERT(Ctx != NULL);
2047 ImGuiContext& g = *Ctx;
2048 g.InputEventsNextMouseSource = source;
2049}
2050
2051void ImGuiIO::AddFocusEvent(bool focused)
2052{
2053 IM_ASSERT(Ctx != NULL);
2054 ImGuiContext& g = *Ctx;
2055
2056 // Filter duplicate
2057 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
2058 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
2059 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
2060 return;
2061
2062 ImGuiInputEvent e;
2063 e.Type = ImGuiInputEventType_Focus;
2064 e.EventId = g.InputEventsNextEventId++;
2065 e.AppFocused.Focused = focused;
2066 g.InputEventsQueue.push_back(e);
2067}
2068
2069ImGuiPlatformIO::ImGuiPlatformIO()
2070{
2071 // Most fields are initialized with zero
2072 memset((void*)this, 0, sizeof(*this));
2073 Platform_LocaleDecimalPoint = '.';
2074}
2075
2076//-----------------------------------------------------------------------------
2077// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
2078//-----------------------------------------------------------------------------
2079
2080ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
2081{
2082 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
2083 ImVec2 p_last = p1;
2084 ImVec2 p_closest;
2085 float p_closest_dist2 = FLT_MAX;
2086 float t_step = 1.0f / (float)num_segments;
2087 for (int i_step = 1; i_step <= num_segments; i_step++)
2088 {
2089 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
2090 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
2091 float dist2 = ImLengthSqr(p - p_line);
2092 if (dist2 < p_closest_dist2)
2093 {
2094 p_closest = p_line;
2095 p_closest_dist2 = dist2;
2096 }
2097 p_last = p_current;
2098 }
2099 return p_closest;
2100}
2101
2102// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
2103static 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)
2104{
2105 float dx = x4 - x1;
2106 float dy = y4 - y1;
2107 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
2108 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
2109 d2 = (d2 >= 0) ? d2 : -d2;
2110 d3 = (d3 >= 0) ? d3 : -d3;
2111 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
2112 {
2113 ImVec2 p_current(x4, y4);
2114 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
2115 float dist2 = ImLengthSqr(p - p_line);
2116 if (dist2 < p_closest_dist2)
2117 {
2118 p_closest = p_line;
2119 p_closest_dist2 = dist2;
2120 }
2121 p_last = p_current;
2122 }
2123 else if (level < 10)
2124 {
2125 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
2126 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
2127 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
2128 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
2129 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
2130 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
2131 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
2132 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
2133 }
2134}
2135
2136// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
2137// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
2138ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
2139{
2140 IM_ASSERT(tess_tol > 0.0f);
2141 ImVec2 p_last = p1;
2142 ImVec2 p_closest;
2143 float p_closest_dist2 = FLT_MAX;
2144 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);
2145 return p_closest;
2146}
2147
2148ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
2149{
2150 ImVec2 ap = p - a;
2151 ImVec2 ab_dir = b - a;
2152 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
2153 if (dot < 0.0f)
2154 return a;
2155 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
2156 if (dot > ab_len_sqr)
2157 return b;
2158 return a + ab_dir * dot / ab_len_sqr;
2159}
2160
2161bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2162{
2163 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
2164 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
2165 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
2166 return (b1 == b2) && (b2 == b3);
2167}
2168
2169void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
2170{
2171 ImVec2 v0 = b - a;
2172 ImVec2 v1 = c - a;
2173 ImVec2 v2 = p - a;
2174 const float denom = v0.x * v1.y - v1.x * v0.y;
2175 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
2176 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
2177 out_u = 1.0f - out_v - out_w;
2178}
2179
2180ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2181{
2182 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
2183 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
2184 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
2185 float dist2_ab = ImLengthSqr(p - proj_ab);
2186 float dist2_bc = ImLengthSqr(p - proj_bc);
2187 float dist2_ca = ImLengthSqr(p - proj_ca);
2188 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
2189 if (m == dist2_ab)
2190 return proj_ab;
2191 if (m == dist2_bc)
2192 return proj_bc;
2193 return proj_ca;
2194}
2195
2196//-----------------------------------------------------------------------------
2197// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
2198//-----------------------------------------------------------------------------
2199
2200// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
2201int ImStricmp(const char* str1, const char* str2)
2202{
2203 int d;
2204 while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
2205 return d;
2206}
2207
2208int ImStrnicmp(const char* str1, const char* str2, size_t count)
2209{
2210 int d = 0;
2211 while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
2212 return d;
2213}
2214
2215void ImStrncpy(char* dst, const char* src, size_t count)
2216{
2217 if (count < 1)
2218 return;
2219 if (count > 1)
2220 strncpy(dst, src, count - 1); // FIXME-OPT: strncpy not only doesn't guarantee 0-termination, it also always writes the whole array
2221 dst[count - 1] = 0;
2222}
2223
2224char* ImStrdup(const char* str)
2225{
2226 size_t len = ImStrlen(str);
2227 void* buf = IM_ALLOC(len + 1);
2228 return (char*)memcpy(buf, (const void*)str, len + 1);
2229}
2230
2231void* ImMemdup(const void* src, size_t size)
2232{
2233 void* dst = IM_ALLOC(size);
2234 return memcpy(dst, src, size);
2235}
2236
2237char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
2238{
2239 size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1;
2240 size_t src_size = ImStrlen(src) + 1;
2241 if (dst_buf_size < src_size)
2242 {
2243 IM_FREE(dst);
2244 dst = (char*)IM_ALLOC(src_size);
2245 if (p_dst_size)
2246 *p_dst_size = src_size;
2247 }
2248 return (char*)memcpy(dst, (const void*)src, src_size);
2249}
2250
2251const char* ImStrchrRange(const char* str, const char* str_end, char c)
2252{
2253 const char* p = (const char*)ImMemchr(str, (int)c, str_end - str);
2254 return p;
2255}
2256
2257int ImStrlenW(const ImWchar* str)
2258{
2259 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
2260 int n = 0;
2261 while (*str++) n++;
2262 return n;
2263}
2264
2265// Find end-of-line. Return pointer will point to either first \n, either str_end.
2266const char* ImStreolRange(const char* str, const char* str_end)
2267{
2268 const char* p = (const char*)ImMemchr(str, '\n', str_end - str);
2269 return p ? p : str_end;
2270}
2271
2272const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
2273{
2274 IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin));
2275 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2276 buf_mid_line--;
2277 return buf_mid_line;
2278}
2279
2280const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2281{
2282 if (!needle_end)
2283 needle_end = needle + ImStrlen(needle);
2284
2285 const char un0 = (char)ImToUpper(*needle);
2286 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2287 {
2288 if (ImToUpper(*haystack) == un0)
2289 {
2290 const char* b = needle + 1;
2291 for (const char* a = haystack + 1; b < needle_end; a++, b++)
2292 if (ImToUpper(*a) != ImToUpper(*b))
2293 break;
2294 if (b == needle_end)
2295 return haystack;
2296 }
2297 haystack++;
2298 }
2299 return NULL;
2300}
2301
2302// 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.
2303void ImStrTrimBlanks(char* buf)
2304{
2305 char* p = buf;
2306 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
2307 p++;
2308 char* p_start = p;
2309 while (*p != 0) // Find end of string
2310 p++;
2311 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
2312 p--;
2313 if (p_start != buf) // Copy memory if we had leading blanks
2314 memmove(buf, p_start, p - p_start);
2315 buf[p - p_start] = 0; // Zero terminate
2316}
2317
2318const char* ImStrSkipBlank(const char* str)
2319{
2320 while (str[0] == ' ' || str[0] == '\t')
2321 str++;
2322 return str;
2323}
2324
2325// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2326// 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.
2327// B) When buf==NULL vsnprintf() will return the output size.
2328#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2329
2330// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2331// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2332// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2333// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2334#ifdef IMGUI_USE_STB_SPRINTF
2335#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2336#define STB_SPRINTF_IMPLEMENTATION
2337#endif
2338#ifdef IMGUI_STB_SPRINTF_FILENAME
2339#include IMGUI_STB_SPRINTF_FILENAME
2340#else
2341#include "stb_sprintf.h"
2342#endif
2343#endif // #ifdef IMGUI_USE_STB_SPRINTF
2344
2345#if defined(_MSC_VER) && !defined(vsnprintf)
2346#define vsnprintf _vsnprintf
2347#endif
2348
2349int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2350{
2351 va_list args;
2352 va_start(args, fmt);
2353#ifdef IMGUI_USE_STB_SPRINTF
2354 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2355#else
2356 int w = vsnprintf(buf, buf_size, fmt, args);
2357#endif
2358 va_end(args);
2359 if (buf == NULL)
2360 return w;
2361 if (w == -1 || w >= (int)buf_size)
2362 w = (int)buf_size - 1;
2363 buf[w] = 0;
2364 return w;
2365}
2366
2367int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2368{
2369#ifdef IMGUI_USE_STB_SPRINTF
2370 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2371#else
2372 int w = vsnprintf(buf, buf_size, fmt, args);
2373#endif
2374 if (buf == NULL)
2375 return w;
2376 if (w == -1 || w >= (int)buf_size)
2377 w = (int)buf_size - 1;
2378 buf[w] = 0;
2379 return w;
2380}
2381#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2382
2383void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2384{
2385 va_list args;
2386 va_start(args, fmt);
2387 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2388 va_end(args);
2389}
2390
2391// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2392// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2393// ImGuiTempBufferToken token;
2394// ImFormatStringToTempBuffer(token, ...);
2395void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2396{
2397 ImGuiContext& g = *GImGui;
2398 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2399 {
2400 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2401 if (buf == NULL)
2402 buf = "(null)";
2403 *out_buf = buf;
2404 if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); }
2405 }
2406 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2407 {
2408 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2409 const char* buf = va_arg(args, const char*);
2410 if (buf == NULL)
2411 {
2412 buf = "(null)";
2413 buf_len = ImMin(buf_len, 6);
2414 }
2415 *out_buf = buf;
2416 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2417 }
2418 else
2419 {
2420 int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2421 *out_buf = g.TempBuffer.Data;
2422 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2423 }
2424}
2425
2426#ifndef IMGUI_ENABLE_SSE4_2_CRC
2427// CRC32 needs a 1KB lookup table (not cache friendly)
2428// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2429// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2430static const ImU32 GCrc32LookupTable[256] =
2431{
2432#ifdef IMGUI_USE_LEGACY_CRC32_ADLER
2433 // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
2434 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2435 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2436 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2437 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2438 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2439 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2440 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2441 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2442 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2443 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2444 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2445 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2446 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2447 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2448 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2449 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2450#else
2451 // CRC32c table compatible with SSE 4.2 instructions
2452 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
2453 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
2454 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
2455 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
2456 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
2457 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
2458 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
2459 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
2460 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
2461 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
2462 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
2463 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
2464 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
2465 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
2466 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
2467 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
2468#endif
2469};
2470#endif
2471
2472// Known size hash
2473// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2474// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2475ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2476{
2477 ImU32 crc = ~seed;
2478 const unsigned char* data = (const unsigned char*)data_p;
2479 const unsigned char *data_end = (const unsigned char*)data_p + data_size;
2480#ifndef IMGUI_ENABLE_SSE4_2_CRC
2481 const ImU32* crc32_lut = GCrc32LookupTable;
2482 while (data < data_end)
2483 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2484 return ~crc;
2485#else
2486 while (data + 4 <= data_end)
2487 {
2488 crc = _mm_crc32_u32(crc, *(ImU32*)data);
2489 data += 4;
2490 }
2491 while (data < data_end)
2492 crc = _mm_crc32_u8(crc, *data++);
2493 return ~crc;
2494#endif
2495}
2496
2497// Zero-terminated string hash, with support for ### to reset back to seed value.
2498// e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions)
2499// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2500ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2501{
2502 seed = ~seed;
2503 ImU32 crc = seed;
2504 const unsigned char* data = (const unsigned char*)data_p;
2505#ifndef IMGUI_ENABLE_SSE4_2_CRC
2506 const ImU32* crc32_lut = GCrc32LookupTable;
2507#endif
2508 if (data_size != 0)
2509 {
2510 while (data_size-- > 0)
2511 {
2512 unsigned char c = *data++;
2513 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2514 {
2515 crc = seed;
2516 data += 2;
2517 data_size -= 2;
2518 continue;
2519 }
2520#ifndef IMGUI_ENABLE_SSE4_2_CRC
2521 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2522#else
2523 crc = _mm_crc32_u8(crc, c);
2524#endif
2525 }
2526 }
2527 else
2528 {
2529 while (unsigned char c = *data++)
2530 {
2531 if (c == '#' && data[0] == '#' && data[1] == '#')
2532 {
2533 crc = seed;
2534 data += 2;
2535 continue;
2536 }
2537#ifndef IMGUI_ENABLE_SSE4_2_CRC
2538 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2539#else
2540 crc = _mm_crc32_u8(crc, c);
2541#endif
2542 }
2543 }
2544 return ~crc;
2545}
2546
2547// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
2548// FIXME-OPT: This is not designed to be optimal. Use with care.
2549const char* ImHashSkipUncontributingPrefix(const char* label)
2550{
2551 const char* result = label;
2552 while (unsigned char c = *label++)
2553 if (c == '#' && label[0] == '#' && label[1] == '#')
2554 result = label + 2;
2555 return result;
2556}
2557
2558//-----------------------------------------------------------------------------
2559// [SECTION] MISC HELPERS/UTILITIES (File functions)
2560//-----------------------------------------------------------------------------
2561
2562// Default file functions
2563#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2564
2565ImFileHandle ImFileOpen(const char* filename, const char* mode)
2566{
2567#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__)))
2568 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2569 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2570 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2571 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2572
2573 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2574 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2575 wchar_t local_temp_stack[FILENAME_MAX];
2576 ImVector<wchar_t> local_temp_heap;
2577 if (filename_wsize + mode_wsize > IM_COUNTOF(local_temp_stack))
2578 local_temp_heap.resize(filename_wsize + mode_wsize);
2579 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2580 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2581 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2582 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2583 return ::_wfopen(filename_wbuf, mode_wbuf);
2584#else
2585 return fopen(filename, mode);
2586#endif
2587}
2588
2589// 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.
2590bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
2591ImU64 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; }
2592ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
2593ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
2594#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2595
2596// Helper: Load file content into memory
2597// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2598// This can't really be used with "rt" because fseek size won't match read size.
2599void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2600{
2601 IM_ASSERT(filename && mode);
2602 if (out_file_size)
2603 *out_file_size = 0;
2604
2605 ImFileHandle f;
2606 if ((f = ImFileOpen(filename, mode)) == NULL)
2607 return NULL;
2608
2609 size_t file_size = (size_t)ImFileGetSize(f);
2610 if (file_size == (size_t)-1)
2611 {
2612 ImFileClose(f);
2613 return NULL;
2614 }
2615
2616 void* file_data = IM_ALLOC(file_size + padding_bytes);
2617 if (file_data == NULL)
2618 {
2619 ImFileClose(f);
2620 return NULL;
2621 }
2622 if (ImFileRead(file_data, 1, file_size, f) != file_size)
2623 {
2624 ImFileClose(f);
2625 IM_FREE(file_data);
2626 return NULL;
2627 }
2628 if (padding_bytes > 0)
2629 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2630
2631 ImFileClose(f);
2632 if (out_file_size)
2633 *out_file_size = file_size;
2634
2635 return file_data;
2636}
2637
2638//-----------------------------------------------------------------------------
2639// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2640//-----------------------------------------------------------------------------
2641
2642IM_MSVC_RUNTIME_CHECKS_OFF
2643
2644// Convert UTF-8 to 32-bit character, process single character input.
2645// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2646// We handle UTF-8 decoding error by skipping forward.
2647int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2648{
2649 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 };
2650 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2651 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2652 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2653 static const int shifte[] = { 0, 6, 4, 2, 0 };
2654 int len = lengths[*(const unsigned char*)in_text >> 3];
2655 int wanted = len + (len ? 0 : 1);
2656
2657 // IMPORTANT: if in_text_end == NULL it assume we have enough space!
2658 if (in_text_end == NULL)
2659 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2660
2661 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2662 // so it is fast even with excessive branching.
2663 unsigned char s[4];
2664 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2665 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2666 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2667 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2668
2669 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2670 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2671 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2672 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2673 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2674 *out_char >>= shiftc[len];
2675
2676 // Accumulate the various error conditions.
2677 int e = 0;
2678 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2679 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2680 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve)
2681 e |= (s[1] & 0xc0) >> 2;
2682 e |= (s[2] & 0xc0) >> 4;
2683 e |= (s[3] ) >> 6;
2684 e ^= 0x2a; // top two bits of each tail byte correct?
2685 e >>= shifte[len];
2686
2687 if (e)
2688 {
2689 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2690 // One byte is consumed in case of invalid first byte of in_text.
2691 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2692 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2693 wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2694 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2695 }
2696
2697 return wanted;
2698}
2699
2700int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2701{
2702 ImWchar* buf_out = buf;
2703 ImWchar* buf_end = buf + buf_size;
2704 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2705 {
2706 unsigned int c;
2707 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2708 *buf_out++ = (ImWchar)c;
2709 }
2710 *buf_out = 0;
2711 if (in_text_remaining)
2712 *in_text_remaining = in_text;
2713 return (int)(buf_out - buf);
2714}
2715
2716int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2717{
2718 int char_count = 0;
2719 while ((!in_text_end || in_text < in_text_end) && *in_text)
2720 {
2721 unsigned int c;
2722 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2723 char_count++;
2724 }
2725 return char_count;
2726}
2727
2728// Based on stb_to_utf8() from github.com/nothings/stb/
2729static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2730{
2731 if (c < 0x80)
2732 {
2733 buf[0] = (char)c;
2734 return 1;
2735 }
2736 if (c < 0x800)
2737 {
2738 if (buf_size < 2) return 0;
2739 buf[0] = (char)(0xc0 + (c >> 6));
2740 buf[1] = (char)(0x80 + (c & 0x3f));
2741 return 2;
2742 }
2743 if (c < 0x10000)
2744 {
2745 if (buf_size < 3) return 0;
2746 buf[0] = (char)(0xe0 + (c >> 12));
2747 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2748 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2749 return 3;
2750 }
2751 if (c <= 0x10FFFF)
2752 {
2753 if (buf_size < 4) return 0;
2754 buf[0] = (char)(0xf0 + (c >> 18));
2755 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2756 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2757 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2758 return 4;
2759 }
2760 // Invalid code point, the max unicode is 0x10FFFF
2761 return 0;
2762}
2763
2764int ImTextCharToUtf8(char out_buf[5], unsigned int c)
2765{
2766 int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2767 out_buf[count] = 0;
2768 return count;
2769}
2770
2771// Not optimal but we very rarely use this function.
2772int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2773{
2774 unsigned int unused = 0;
2775 return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2776}
2777
2778static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2779{
2780 if (c < 0x80) return 1;
2781 if (c < 0x800) return 2;
2782 if (c < 0x10000) return 3;
2783 if (c <= 0x10FFFF) return 4;
2784 return 3;
2785}
2786
2787int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2788{
2789 char* buf_p = out_buf;
2790 const char* buf_end = out_buf + out_buf_size;
2791 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2792 {
2793 unsigned int c = (unsigned int)(*in_text++);
2794 if (c < 0x80)
2795 *buf_p++ = (char)c;
2796 else
2797 buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2798 }
2799 *buf_p = 0;
2800 return (int)(buf_p - out_buf);
2801}
2802
2803int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2804{
2805 int bytes_count = 0;
2806 while ((!in_text_end || in_text < in_text_end) && *in_text)
2807 {
2808 unsigned int c = (unsigned int)(*in_text++);
2809 if (c < 0x80)
2810 bytes_count++;
2811 else
2812 bytes_count += ImTextCountUtf8BytesFromChar(c);
2813 }
2814 return bytes_count;
2815}
2816
2817const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_p)
2818{
2819 while (in_p > in_text_start)
2820 {
2821 in_p--;
2822 if ((*in_p & 0xC0) != 0x80)
2823 return in_p;
2824 }
2825 return in_text_start;
2826}
2827
2828const char* ImTextFindValidUtf8CodepointEnd(const char* in_text_start, const char* in_text_end, const char* in_p)
2829{
2830 if (in_text_start == in_p)
2831 return in_text_start;
2832 const char* prev = ImTextFindPreviousUtf8Codepoint(in_text_start, in_p);
2833 unsigned int prev_c;
2834 int prev_c_len = ImTextCharFromUtf8(&prev_c, prev, in_text_end);
2835 if (prev_c != IM_UNICODE_CODEPOINT_INVALID && prev_c_len <= (int)(in_p - prev))
2836 return in_p;
2837 return prev;
2838}
2839
2840int ImTextCountLines(const char* in_text, const char* in_text_end)
2841{
2842 if (in_text_end == NULL)
2843 in_text_end = in_text + ImStrlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2844 int count = 0;
2845 while (in_text < in_text_end)
2846 {
2847 const char* line_end = (const char*)ImMemchr(in_text, '\n', in_text_end - in_text);
2848 in_text = line_end ? line_end + 1 : in_text_end;
2849 count++;
2850 }
2851 return count;
2852}
2853
2854IM_MSVC_RUNTIME_CHECKS_RESTORE
2855
2856//-----------------------------------------------------------------------------
2857// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2858// Note: The Convert functions are early design which are not consistent with other API.
2859//-----------------------------------------------------------------------------
2860
2861IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2862{
2863 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2864 int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2865 int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2866 int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2867 return IM_COL32(r, g, b, 0xFF);
2868}
2869
2870ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2871{
2872 float s = 1.0f / 255.0f;
2873 return ImVec4(
2874 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2875 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2876 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2877 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2878}
2879
2880ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2881{
2882 ImU32 out;
2883 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2884 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2885 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2886 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2887 return out;
2888}
2889
2890// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2891// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2892void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2893{
2894 float K = 0.f;
2895 if (g < b)
2896 {
2897 ImSwap(g, b);
2898 K = -1.f;
2899 }
2900 if (r < g)
2901 {
2902 ImSwap(r, g);
2903 K = -2.f / 6.f - K;
2904 }
2905
2906 const float chroma = r - (g < b ? g : b);
2907 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2908 out_s = chroma / (r + 1e-20f);
2909 out_v = r;
2910}
2911
2912// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2913// also http://en.wikipedia.org/wiki/HSL_and_HSV
2914void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2915{
2916 if (s == 0.0f)
2917 {
2918 // gray
2919 out_r = out_g = out_b = v;
2920 return;
2921 }
2922
2923 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2924 int i = (int)h;
2925 float f = h - (float)i;
2926 float p = v * (1.0f - s);
2927 float q = v * (1.0f - s * f);
2928 float t = v * (1.0f - s * (1.0f - f));
2929
2930 switch (i)
2931 {
2932 case 0: out_r = v; out_g = t; out_b = p; break;
2933 case 1: out_r = q; out_g = v; out_b = p; break;
2934 case 2: out_r = p; out_g = v; out_b = t; break;
2935 case 3: out_r = p; out_g = q; out_b = v; break;
2936 case 4: out_r = t; out_g = p; out_b = v; break;
2937 case 5: default: out_r = v; out_g = p; out_b = q; break;
2938 }
2939}
2940
2941//-----------------------------------------------------------------------------
2942// [SECTION] ImGuiStorage
2943// Helper: Key->value storage
2944//-----------------------------------------------------------------------------
2945
2946// std::lower_bound but without the bullshit
2947ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2948{
2949 ImGuiStoragePair* in_p = in_begin;
2950 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2951 {
2952 size_t count2 = count >> 1;
2953 ImGuiStoragePair* mid = in_p + count2;
2954 if (mid->key < key)
2955 {
2956 in_p = ++mid;
2957 count -= count2 + 1;
2958 }
2959 else
2960 {
2961 count = count2;
2962 }
2963 }
2964 return in_p;
2965}
2966
2967IM_MSVC_RUNTIME_CHECKS_OFF
2968static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2969{
2970 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2971 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2972 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2973 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2974}
2975
2976// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2977void ImGuiStorage::BuildSortByKey()
2978{
2979 ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2980}
2981
2982int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2983{
2984 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2985 if (it == Data.Data + Data.Size || it->key != key)
2986 return default_val;
2987 return it->val_i;
2988}
2989
2990bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2991{
2992 return GetInt(key, default_val ? 1 : 0) != 0;
2993}
2994
2995float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2996{
2997 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2998 if (it == Data.Data + Data.Size || it->key != key)
2999 return default_val;
3000 return it->val_f;
3001}
3002
3003void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
3004{
3005 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
3006 if (it == Data.Data + Data.Size || it->key != key)
3007 return NULL;
3008 return it->val_p;
3009}
3010
3011// 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.
3012int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
3013{
3014 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
3015 if (it == Data.Data + Data.Size || it->key != key)
3016 it = Data.insert(it, ImGuiStoragePair(key, default_val));
3017 return &it->val_i;
3018}
3019
3020bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
3021{
3022 return (bool*)GetIntRef(key, default_val ? 1 : 0);
3023}
3024
3025float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
3026{
3027 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
3028 if (it == Data.Data + Data.Size || it->key != key)
3029 it = Data.insert(it, ImGuiStoragePair(key, default_val));
3030 return &it->val_f;
3031}
3032
3033void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
3034{
3035 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
3036 if (it == Data.Data + Data.Size || it->key != key)
3037 it = Data.insert(it, ImGuiStoragePair(key, default_val));
3038 return &it->val_p;
3039}
3040
3041// 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)
3042void ImGuiStorage::SetInt(ImGuiID key, int val)
3043{
3044 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
3045 if (it == Data.Data + Data.Size || it->key != key)
3046 Data.insert(it, ImGuiStoragePair(key, val));
3047 else
3048 it->val_i = val;
3049}
3050
3051void ImGuiStorage::SetBool(ImGuiID key, bool val)
3052{
3053 SetInt(key, val ? 1 : 0);
3054}
3055
3056void ImGuiStorage::SetFloat(ImGuiID key, float val)
3057{
3058 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
3059 if (it == Data.Data + Data.Size || it->key != key)
3060 Data.insert(it, ImGuiStoragePair(key, val));
3061 else
3062 it->val_f = val;
3063}
3064
3065void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
3066{
3067 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
3068 if (it == Data.Data + Data.Size || it->key != key)
3069 Data.insert(it, ImGuiStoragePair(key, val));
3070 else
3071 it->val_p = val;
3072}
3073
3074void ImGuiStorage::SetAllInt(int v)
3075{
3076 for (int i = 0; i < Data.Size; i++)
3077 Data[i].val_i = v;
3078}
3079IM_MSVC_RUNTIME_CHECKS_RESTORE
3080
3081//-----------------------------------------------------------------------------
3082// [SECTION] ImGuiTextFilter
3083//-----------------------------------------------------------------------------
3084
3085// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
3086ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
3087{
3088 InputBuf[0] = 0;
3089 CountGrep = 0;
3090 if (default_filter)
3091 {
3092 ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf));
3093 Build();
3094 }
3095}
3096
3097bool ImGuiTextFilter::Draw(const char* label, float width)
3098{
3099 if (width != 0.0f)
3100 ImGui::SetNextItemWidth(width);
3101 bool value_changed = ImGui::InputText(label, InputBuf, IM_COUNTOF(InputBuf));
3102 if (value_changed)
3103 Build();
3104 return value_changed;
3105}
3106
3107void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
3108{
3109 out->resize(0);
3110 const char* wb = b;
3111 const char* we = wb;
3112 while (we < e)
3113 {
3114 if (*we == separator)
3115 {
3116 out->push_back(ImGuiTextRange(wb, we));
3117 wb = we + 1;
3118 }
3119 we++;
3120 }
3121 if (wb != we)
3122 out->push_back(ImGuiTextRange(wb, we));
3123}
3124
3125void ImGuiTextFilter::Build()
3126{
3127 Filters.resize(0);
3128 ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf));
3129 input_range.split(',', &Filters);
3130
3131 CountGrep = 0;
3132 for (ImGuiTextRange& f : Filters)
3133 {
3134 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
3135 f.b++;
3136 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
3137 f.e--;
3138 if (f.empty())
3139 continue;
3140 if (f.b[0] != '-')
3141 CountGrep += 1;
3142 }
3143}
3144
3145bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
3146{
3147 if (Filters.Size == 0)
3148 return true;
3149
3150 if (text == NULL)
3151 text = text_end = "";
3152
3153 for (const ImGuiTextRange& f : Filters)
3154 {
3155 if (f.b == f.e)
3156 continue;
3157 if (f.b[0] == '-')
3158 {
3159 // Subtract
3160 if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
3161 return false;
3162 }
3163 else
3164 {
3165 // Grep
3166 if (ImStristr(text, text_end, f.b, f.e) != NULL)
3167 return true;
3168 }
3169 }
3170
3171 // Implicit * grep
3172 if (CountGrep == 0)
3173 return true;
3174
3175 return false;
3176}
3177
3178//-----------------------------------------------------------------------------
3179// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
3180//-----------------------------------------------------------------------------
3181
3182// On some platform vsnprintf() takes va_list by reference and modifies it.
3183// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
3184#ifndef va_copy
3185#if defined(__GNUC__) || defined(__clang__)
3186#define va_copy(dest, src) __builtin_va_copy(dest, src)
3187#else
3188#define va_copy(dest, src) (dest = src)
3189#endif
3190#endif
3191
3192char ImGuiTextBuffer::EmptyString[1] = { 0 };
3193
3194void ImGuiTextBuffer::append(const char* str, const char* str_end)
3195{
3196 int len = str_end ? (int)(str_end - str) : (int)ImStrlen(str);
3197
3198 // Add zero-terminator the first time
3199 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3200 const int needed_sz = write_off + len;
3201 if (write_off + len >= Buf.Capacity)
3202 {
3203 int new_capacity = Buf.Capacity * 2;
3204 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
3205 }
3206
3207 Buf.resize(needed_sz);
3208 memcpy(&Buf[write_off - 1], str, (size_t)len);
3209 Buf[write_off - 1 + len] = 0;
3210}
3211
3212void ImGuiTextBuffer::appendf(const char* fmt, ...)
3213{
3214 va_list args;
3215 va_start(args, fmt);
3216 appendfv(fmt, args);
3217 va_end(args);
3218}
3219
3220// Helper: Text buffer for logging/accumulating text
3221void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
3222{
3223 va_list args_copy;
3224 va_copy(args_copy, args);
3225
3226 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
3227 if (len <= 0)
3228 {
3229 va_end(args_copy);
3230 return;
3231 }
3232
3233 // Add zero-terminator the first time
3234 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3235 const int needed_sz = write_off + len;
3236 if (write_off + len >= Buf.Capacity)
3237 {
3238 int new_capacity = Buf.Capacity * 2;
3239 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
3240 }
3241
3242 Buf.resize(needed_sz);
3243 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
3244 va_end(args_copy);
3245}
3246
3247IM_MSVC_RUNTIME_CHECKS_OFF
3248void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
3249{
3250 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
3251 if (old_size == new_size)
3252 return;
3253 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
3254 Offsets.push_back(EndOffset);
3255 const char* base_end = base + new_size;
3256 for (const char* p = base + old_size; (p = (const char*)ImMemchr(p, '\n', base_end - p)) != 0; )
3257 if (++p < base_end) // Don't push a trailing offset on last \n
3258 Offsets.push_back((int)(intptr_t)(p - base));
3259 EndOffset = ImMax(EndOffset, new_size);
3260}
3261IM_MSVC_RUNTIME_CHECKS_RESTORE
3262
3263//-----------------------------------------------------------------------------
3264// [SECTION] ImGuiListClipper
3265//-----------------------------------------------------------------------------
3266
3267// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
3268// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
3269static bool GetSkipItemForListClipping()
3270{
3271 ImGuiContext& g = *GImGui;
3272 return g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems;
3273}
3274
3275static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
3276{
3277 if (ranges.Size - offset <= 1)
3278 return;
3279
3280 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
3281 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
3282 for (int i = offset; i < sort_end + offset; ++i)
3283 if (ranges[i].Min > ranges[i + 1].Min)
3284 ImSwap(ranges[i], ranges[i + 1]);
3285
3286 // Now fuse ranges together as much as possible.
3287 for (int i = 1 + offset; i < ranges.Size; i++)
3288 {
3289 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
3290 if (ranges[i - 1].Max < ranges[i].Min)
3291 continue;
3292 ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
3293 ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
3294 ranges.erase(ranges.Data + i);
3295 i--;
3296 }
3297}
3298
3299static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clipper, float pos_y, float line_height)
3300{
3301 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
3302 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
3303 // 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?
3304 ImGuiContext& g = *GImGui;
3305 ImGuiWindow* window = g.CurrentWindow;
3306 float off_y = pos_y - window->DC.CursorPos.y;
3307 window->DC.CursorPos.y = pos_y;
3308 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
3309 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.
3310 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.
3311 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
3312 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
3313 if (ImGuiTable* table = g.CurrentTable)
3314 {
3315 if (table->IsInsideRow)
3316 ImGui::TableEndRow(table);
3317 const int row_increase = (int)((off_y / line_height) + 0.5f);
3318 if (row_increase > 0 && (clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886.
3319 {
3320 table->CurrentRow += row_increase;
3321 table->RowBgColorCounter += row_increase;
3322 }
3323 table->RowPosY2 = window->DC.CursorPos.y;
3324 }
3325}
3326
3327ImGuiListClipper::ImGuiListClipper()
3328{
3329 memset((void*)this, 0, sizeof(*this));
3330}
3331
3332ImGuiListClipper::~ImGuiListClipper()
3333{
3334 End();
3335}
3336
3337void ImGuiListClipper::Begin(int items_count, float items_height)
3338{
3339 Ctx = ImGui::GetCurrentContext();
3340
3341 ImGuiContext& g = *Ctx;
3342 ImGuiWindow* window = g.CurrentWindow;
3343 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3344
3345 if (ImGuiTable* table = g.CurrentTable)
3346 if (table->IsInsideRow)
3347 ImGui::TableEndRow(table);
3348
3349 StartPosY = window->DC.CursorPos.y;
3350 ItemsHeight = items_height;
3351 ItemsCount = items_count;
3352 DisplayStart = -1;
3353 DisplayEnd = 0;
3354
3355 // Acquire temporary buffer
3356 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3357 g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3358 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3359 data->Reset(this);
3360 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3361 TempData = data;
3362 StartSeekOffsetY = data->LossynessOffset;
3363}
3364
3365void ImGuiListClipper::End()
3366{
3367 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3368 {
3369 // 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.
3370 ImGuiContext& g = *Ctx;
3371 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3372 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3373 SeekCursorForItem(ItemsCount);
3374
3375 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3376 IM_ASSERT(data->ListClipper == this);
3377 data->StepNo = data->Ranges.Size;
3378 if (--g.ClipperTempDataStacked > 0)
3379 {
3380 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3381 data->ListClipper->TempData = data;
3382 }
3383 TempData = NULL;
3384 }
3385 DisplayStart = DisplayEnd = ItemsCount; // Clear this so code which may be reused past last Step() won't trip on a non-empty range.
3386 ItemsCount = -1;
3387}
3388
3389void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3390{
3391 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3392 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3393 IM_ASSERT(item_begin <= item_end);
3394 if (item_begin < item_end)
3395 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3396}
3397
3398// This is already called while stepping.
3399// 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.
3400void ImGuiListClipper::SeekCursorForItem(int item_n)
3401{
3402 // - Perform the add and multiply with double to allow seeking through larger ranges.
3403 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3404 // - 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.
3405 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3406 ImGuiListClipper_SeekCursorAndSetupPrevLine(this, pos_y, ItemsHeight);
3407}
3408
3409static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3410{
3411 ImGuiContext& g = *clipper->Ctx;
3412 ImGuiWindow* window = g.CurrentWindow;
3413 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3414 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3415
3416 ImGuiTable* table = g.CurrentTable;
3417 if (table && table->IsInsideRow)
3418 ImGui::TableEndRow(table);
3419
3420 // No items
3421 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3422 return false;
3423
3424 // While we are in frozen row state, keep displaying items one by one, unclipped
3425 // FIXME: Could be stored as a table-agnostic state.
3426 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3427 {
3428 clipper->DisplayStart = data->ItemsFrozen;
3429 clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3430 if (clipper->DisplayStart < clipper->DisplayEnd)
3431 data->ItemsFrozen++;
3432 return true;
3433 }
3434
3435 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3436 bool calc_clipping = false;
3437 if (data->StepNo == 0)
3438 {
3439 clipper->StartPosY = window->DC.CursorPos.y;
3440 if (clipper->ItemsHeight <= 0.0f)
3441 {
3442 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3443 data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3444 clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3445 clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3446 data->StepNo = 1;
3447 return true;
3448 }
3449 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3450 }
3451
3452 // Step 1: Let the clipper infer height from first range
3453 if (clipper->ItemsHeight <= 0.0f)
3454 {
3455 IM_ASSERT(data->StepNo == 1);
3456 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3457 if (affected_by_floating_point_precision)
3458 {
3459 // Mitigation/hack for very large range: assume last time height constitute line height.
3460 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3461 window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight);
3462 }
3463 else
3464 {
3465 clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3466 }
3467 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3468 return false;
3469 if (clipper->ItemsHeight <= 0.0f)
3470 {
3471 IM_ASSERT_USER_ERROR(clipper->ItemsHeight > 0.0f, "ImGuiListClipper: Failed to calculate item height! First item hasn't been submitted by user code, or has not moved the cursor vertically!");
3472 return false;
3473 }
3474 if (table)
3475 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3476
3477 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3478 }
3479
3480 // Step 0 or 1: Calculate the actual ranges of visible elements.
3481 const int already_submitted = clipper->DisplayEnd;
3482 if (calc_clipping)
3483 {
3484 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3485 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3486
3487 if (g.LogEnabled)
3488 {
3489 // If logging is active, do not perform any clipping
3490 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3491 }
3492 else
3493 {
3494 // Add range selected to be included for navigation
3495 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3496 const int nav_off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3497 const int nav_off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3498 if (is_nav_request)
3499 {
3500 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, nav_off_min, nav_off_max));
3501 if (!g.NavScoringNoClipRect.IsInverted())
3502 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, nav_off_min, nav_off_max));
3503 }
3504 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3505 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3506
3507 // Add focused/active item
3508 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3509 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3510 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3511
3512 float min_y = window->ClipRect.Min.y;
3513 float max_y = window->ClipRect.Max.y;
3514
3515 // Add box selection range
3516 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3517 if (bs->IsActive && bs->Window == window)
3518 {
3519 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3520 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3521 // As a workaround we currently half ItemSpacing worth on each side.
3522 float pad_y = g.Style.ItemSpacing.y;
3523 min_y -= pad_y;
3524 max_y += pad_y;
3525
3526 // Box-select on 2D area requires different clipping.
3527 // (best adding pad_y here than in BeginBoxSelect() as we are closer to current state)
3528 if (bs->UnclipMode)
3529 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y - pad_y, bs->UnclipRect.Max.y + pad_y, 0, 0));
3530 }
3531
3532 // Add main visible range
3533 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, nav_off_min, nav_off_max));
3534 }
3535
3536 // Convert position ranges to item index ranges
3537 // - 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.
3538 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3539 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3540 for (ImGuiListClipperRange& range : data->Ranges)
3541 if (range.PosToIndexConvert)
3542 {
3543 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3544 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3545 range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3546 range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3547 range.PosToIndexConvert = false;
3548 }
3549 ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3550 }
3551
3552 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3553 while (data->StepNo < data->Ranges.Size)
3554 {
3555 clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3556 clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3557 data->StepNo++;
3558 if (clipper->DisplayStart >= clipper->DisplayEnd)
3559 continue;
3560 if (clipper->DisplayStart > already_submitted)
3561 clipper->SeekCursorForItem(clipper->DisplayStart);
3562 return true;
3563 }
3564
3565 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3566 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3567 if (clipper->ItemsCount < INT_MAX)
3568 clipper->SeekCursorForItem(clipper->ItemsCount);
3569
3570 return false;
3571}
3572
3573bool ImGuiListClipper::Step()
3574{
3575 ImGuiContext& g = *Ctx;
3576 bool need_items_height = (ItemsHeight <= 0.0f);
3577 bool ret = ImGuiListClipper_StepInternal(this);
3578 if (ret && (DisplayStart >= DisplayEnd))
3579 ret = false;
3580 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3581 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3582 if (need_items_height && ItemsHeight > 0.0f)
3583 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3584 if (ret)
3585 {
3586 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3587 }
3588 else
3589 {
3590 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3591 End();
3592 }
3593 return ret;
3594}
3595
3596// Generic helper, equivalent to old ImGui::CalcListClipping() but stateless
3597void ImGui::CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end)
3598{
3599 *out_visible_start = ImMax((int)((clip_rect.Min.y - pos.y) / items_height), 0);
3600 *out_visible_end = ImMax((int)ImCeil((clip_rect.Max.y - pos.y) / items_height), *out_visible_start);
3601}
3602
3603//-----------------------------------------------------------------------------
3604// [SECTION] STYLING
3605//-----------------------------------------------------------------------------
3606
3607ImGuiStyle& ImGui::GetStyle()
3608{
3609 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3610 return GImGui->Style;
3611}
3612
3613ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3614{
3615 ImGuiStyle& style = GImGui->Style;
3616 ImVec4 c = style.Colors[idx];
3617 c.w *= style.Alpha * alpha_mul;
3618 return ColorConvertFloat4ToU32(c);
3619}
3620
3621ImU32 ImGui::GetColorU32(const ImVec4& col)
3622{
3623 ImGuiStyle& style = GImGui->Style;
3624 ImVec4 c = col;
3625 c.w *= style.Alpha;
3626 return ColorConvertFloat4ToU32(c);
3627}
3628
3629const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3630{
3631 ImGuiStyle& style = GImGui->Style;
3632 return style.Colors[idx];
3633}
3634
3635ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3636{
3637 ImGuiStyle& style = GImGui->Style;
3638 alpha_mul *= style.Alpha;
3639 if (alpha_mul >= 1.0f)
3640 return col;
3641 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3642 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3643 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3644}
3645
3646// 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
3647void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3648{
3649 ImGuiContext& g = *GImGui;
3650 ImGuiColorMod backup;
3651 backup.Col = idx;
3652 backup.BackupValue = g.Style.Colors[idx];
3653 g.ColorStack.push_back(backup);
3654 if (g.DebugFlashStyleColorIdx != idx)
3655 g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3656}
3657
3658void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3659{
3660 ImGuiContext& g = *GImGui;
3661 ImGuiColorMod backup;
3662 backup.Col = idx;
3663 backup.BackupValue = g.Style.Colors[idx];
3664 g.ColorStack.push_back(backup);
3665 if (g.DebugFlashStyleColorIdx != idx)
3666 g.Style.Colors[idx] = col;
3667}
3668
3669void ImGui::PopStyleColor(int count)
3670{
3671 ImGuiContext& g = *GImGui;
3672 if (g.ColorStack.Size < count)
3673 {
3674 IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
3675 count = g.ColorStack.Size;
3676 }
3677 while (count > 0)
3678 {
3679 ImGuiColorMod& backup = g.ColorStack.back();
3680 g.Style.Colors[backup.Col] = backup.BackupValue;
3681 g.ColorStack.pop_back();
3682 count--;
3683 }
3684}
3685
3686static const ImGuiStyleVarInfo GStyleVarsInfo[] =
3687{
3688 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3689 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3690 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3691 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3692 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3693 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3694 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3695 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3696 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3697 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3698 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3699 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3700 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3701 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3702 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3703 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3704 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3705 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3706 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3707 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3708 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarPadding) }, // ImGuiStyleVar_ScrollbarPadding
3709 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3710 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3711 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageRounding) }, // ImGuiStyleVar_ImageRounding
3712 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize
3713 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3714 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3715 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase
3716 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink
3717 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3718 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3719 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3720 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3721 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize
3722 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding
3723 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, MenuItemRounding)}, // ImGuiStyleVar_MenuItemRounding
3724 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableRounding)}, // ImGuiStyleVar_SelectableRounding
3725 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DragDropTargetRounding)}, // ImGuiStyleVar_DragDropTargetRounding
3726 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3727 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3728 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorSize)}, // ImGuiStyleVar_SeparatorSize
3729 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3730 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3731 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3732};
3733
3734const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3735{
3736 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3737 IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT);
3738 return &GStyleVarsInfo[idx];
3739}
3740
3741void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3742{
3743 ImGuiContext& g = *GImGui;
3744 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3745 IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 1, "Calling PushStyleVar() variant with wrong type!");
3746 float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3747 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3748 *pvar = val;
3749}
3750
3751void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
3752{
3753 ImGuiContext& g = *GImGui;
3754 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3755 IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!");
3756 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3757 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3758 pvar->x = val_x;
3759}
3760
3761void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
3762{
3763 ImGuiContext& g = *GImGui;
3764 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3765 IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!");
3766 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3767 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3768 pvar->y = val_y;
3769}
3770
3771void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3772{
3773 ImGuiContext& g = *GImGui;
3774 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3775 IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!");
3776 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3777 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3778 *pvar = val;
3779}
3780
3781void ImGui::PopStyleVar(int count)
3782{
3783 ImGuiContext& g = *GImGui;
3784 if (g.StyleVarStack.Size < count)
3785 {
3786 IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
3787 count = g.StyleVarStack.Size;
3788 }
3789 while (count > 0)
3790 {
3791 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3792 ImGuiStyleMod& backup = g.StyleVarStack.back();
3793 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(backup.VarIdx);
3794 void* data = var_info->GetVarPtr(&g.Style);
3795 if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3796 else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3797 g.StyleVarStack.pop_back();
3798 count--;
3799 }
3800}
3801
3802const char* ImGui::GetStyleColorName(ImGuiCol idx)
3803{
3804 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3805 switch (idx)
3806 {
3807 case ImGuiCol_Text: return "Text";
3808 case ImGuiCol_TextDisabled: return "TextDisabled";
3809 case ImGuiCol_WindowBg: return "WindowBg";
3810 case ImGuiCol_ChildBg: return "ChildBg";
3811 case ImGuiCol_PopupBg: return "PopupBg";
3812 case ImGuiCol_Border: return "Border";
3813 case ImGuiCol_BorderShadow: return "BorderShadow";
3814 case ImGuiCol_FrameBg: return "FrameBg";
3815 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3816 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3817 case ImGuiCol_TitleBg: return "TitleBg";
3818 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3819 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3820 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3821 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3822 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3823 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3824 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3825 case ImGuiCol_CheckMark: return "CheckMark";
3826 case ImGuiCol_CheckboxSelectedBg: return "CheckboxSelectedBg";
3827 case ImGuiCol_SliderGrab: return "SliderGrab";
3828 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3829 case ImGuiCol_Button: return "Button";
3830 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3831 case ImGuiCol_ButtonActive: return "ButtonActive";
3832 case ImGuiCol_Header: return "Header";
3833 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3834 case ImGuiCol_HeaderActive: return "HeaderActive";
3835 case ImGuiCol_Separator: return "Separator";
3836 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3837 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3838 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3839 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3840 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3841 case ImGuiCol_InputTextCursor: return "InputTextCursor";
3842 case ImGuiCol_TabHovered: return "TabHovered";
3843 case ImGuiCol_Tab: return "Tab";
3844 case ImGuiCol_TabSelected: return "TabSelected";
3845 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3846 case ImGuiCol_TabDimmed: return "TabDimmed";
3847 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3848 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3849 case ImGuiCol_PlotLines: return "PlotLines";
3850 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3851 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3852 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3853 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3854 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3855 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3856 case ImGuiCol_TableRowBg: return "TableRowBg";
3857 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3858 case ImGuiCol_TextLink: return "TextLink";
3859 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3860 case ImGuiCol_TreeLines: return "TreeLines";
3861 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3862 case ImGuiCol_DragDropTargetBg: return "DragDropTargetBg";
3863 case ImGuiCol_UnsavedMarker: return "UnsavedMarker";
3864 case ImGuiCol_NavCursor: return "NavCursor";
3865 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3866 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3867 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3868 }
3869 IM_ASSERT(0);
3870 return "Unknown";
3871}
3872
3873//-----------------------------------------------------------------------------
3874// [SECTION] RENDER HELPERS
3875// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3876// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3877// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3878//-----------------------------------------------------------------------------
3879
3880const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3881{
3882 const char* text_display_end = text;
3883 if (!text_end)
3884 text_end = (const char*)-1;
3885
3886 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3887 text_display_end++;
3888 return text_display_end;
3889}
3890
3891// Internal ImGui functions to render text
3892// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3893void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3894{
3895 ImGuiContext& g = *GImGui;
3896 ImGuiWindow* window = g.CurrentWindow;
3897
3898 // Hide anything after a '##' string
3899 const char* text_display_end;
3900 if (hide_text_after_hash)
3901 {
3902 text_display_end = FindRenderedTextEnd(text, text_end);
3903 }
3904 else
3905 {
3906 if (!text_end)
3907 text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls)
3908 text_display_end = text_end;
3909 }
3910
3911 if (text != text_display_end)
3912 {
3913 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3914 if (g.LogEnabled)
3915 LogRenderedText(&pos, text, text_display_end);
3916 }
3917}
3918
3919void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3920{
3921 ImGuiContext& g = *GImGui;
3922 ImGuiWindow* window = g.CurrentWindow;
3923
3924 if (!text_end)
3925 text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls)
3926
3927 if (text != text_end)
3928 {
3929 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3930 if (g.LogEnabled)
3931 LogRenderedText(&pos, text, text_end);
3932 }
3933}
3934
3935// Default clip_rect uses (pos_min,pos_max)
3936// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3937// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList.
3938// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3939// better advantage of the render function taking size into account for coarse clipping.
3940void 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)
3941{
3942 // Perform CPU side clipping for single clipped element to avoid using scissor state
3943 ImVec2 pos = pos_min;
3944 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3945
3946 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3947 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3948 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3949 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3950 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3951
3952 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3953 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3954 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3955
3956 // Render
3957 if (need_clipping)
3958 {
3959 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3960 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3961 }
3962 else
3963 {
3964 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3965 }
3966}
3967
3968void 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)
3969{
3970 // Hide anything after a '##' string
3971 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3972 const int text_len = (int)(text_display_end - text);
3973 if (text_len == 0)
3974 return;
3975
3976 ImGuiContext& g = *GImGui;
3977 ImGuiWindow* window = g.CurrentWindow;
3978 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3979 if (g.LogEnabled)
3980 LogRenderedText(&pos_min, text, text_display_end);
3981}
3982
3983// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3984// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) from 'ellipsis_max_x' which may be beyond it.
3985// 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.
3986// (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceding 'float ellipsis_max' and was the same value for 99% of users.
3987void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3988{
3989 ImGuiContext& g = *GImGui;
3990 if (text_end_full == NULL)
3991 text_end_full = FindRenderedTextEnd(text);
3992 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3993
3994 //draw_list->AddLineV(pos_max.x, pos_min.y - 4, pos_max.y + 6, IM_COL32(0, 0, 255, 255));
3995 //draw_list->AddLineV(ellipsis_max_x, pos_min.y - 2, pos_max.y + 3, IM_COL32(0, 255, 0, 255));
3996
3997 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3998 if (text_size.x > pos_max.x - pos_min.x)
3999 {
4000 // Hello wo...
4001 // | | |
4002 // min max ellipsis_max
4003 // <-> this is generally some padding value
4004
4005 ImFont* font = draw_list->_Data->Font;
4006 const float font_size = draw_list->_Data->FontSize;
4007 const float font_scale = draw_list->_Data->FontScale;
4008 const char* text_end_ellipsis = NULL;
4009 ImFontBaked* baked = font->GetFontBaked(font_size);
4010 const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale;
4011
4012 // We can now claim the space between pos_max.x and ellipsis_max.x
4013 const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
4014 const float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
4015
4016 // Render text, render ellipsis
4017 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
4018 ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y);
4019 ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
4020 font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect);
4021 }
4022 else
4023 {
4024 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
4025 }
4026
4027 if (g.LogEnabled)
4028 LogRenderedText(&pos_min, text, text_end_full);
4029}
4030
4031// Render a rectangle shaped with optional rounding and borders
4032void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding)
4033{
4034 ImGuiContext& g = *GImGui;
4035 ImGuiWindow* window = g.CurrentWindow;
4036 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
4037 const float border_size = g.Style.FrameBorderSize;
4038 if (borders && border_size > 0.0f)
4039 {
4040 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, border_size);
4041 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, border_size);
4042 }
4043}
4044
4045void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
4046{
4047 ImGuiContext& g = *GImGui;
4048 ImGuiWindow* window = g.CurrentWindow;
4049 const float border_size = g.Style.FrameBorderSize;
4050 if (border_size > 0.0f)
4051 {
4052 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, border_size);
4053 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, border_size);
4054 }
4055}
4056
4057void ImGui::RenderColorComponentMarker(const ImRect& bb, ImU32 col, float rounding)
4058{
4059 if (bb.Min.x + 1 >= bb.Max.x)
4060 return;
4061 ImGuiContext& g = *GImGui;
4062 ImGuiWindow* window = g.CurrentWindow;
4063 RenderRectFilledInRangeH(window->DrawList, bb, col, bb.Min.x, ImMin(bb.Min.x + g.Style.ColorMarkerSize, bb.Max.x), rounding);
4064}
4065
4066void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags, float rounding)
4067{
4068 ImGuiContext& g = *GImGui;
4069 if (id != g.NavId)
4070 return;
4071 if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
4072 return;
4073 if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
4074 return;
4075
4076 // We don't early out on 'window->Flags & ImGuiWindowFlags_NoNavInputs' because it would be inconsistent with
4077 // other code directly checking NavCursorVisible. Instead we aim for NavCursorVisible to always be false.
4078 ImGuiWindow* window = g.CurrentWindow;
4079 if (window->DC.NavHideHighlightOneFrame)
4080 return;
4081
4082#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
4083 if (rounding < 0.0f && (flags & ImGuiNavRenderCursorFlags_NoRounding))
4084 rounding = 0.0f;
4085#endif
4086 if (rounding < 0.0f)
4087 rounding = g.Style.FrameRounding;
4088
4089 ImRect display_rect = bb;
4090 display_rect.ClipWith(window->ClipRect);
4091 const float scale_factor = GetScale(); // FIXME-DPI
4092 const float thickness = (float)(int)ImMax(2.0f, 1.5f * scale_factor);
4093 if (flags & ImGuiNavRenderCursorFlags_Compact)
4094 {
4095 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, thickness);
4096 }
4097 else
4098 {
4099 const float distance = (float)(int)(3.0f + thickness * 0.5f);
4100 display_rect.Expand(ImVec2(distance, distance));
4101 bool fully_visible = window->ClipRect.Contains(display_rect);
4102 if (!fully_visible)
4103 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
4104 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, thickness);
4105 if (!fully_visible)
4106 window->DrawList->PopClipRect();
4107 }
4108}
4109
4110void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
4111{
4112 ImGuiContext& g = *GImGui;
4113 if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
4114 mouse_cursor = ImGuiMouseCursor_Arrow;
4115 ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas;
4116 for (ImGuiViewportP* viewport : g.Viewports)
4117 {
4118 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
4119 ImVec2 offset, size, uv[4];
4120 if (!ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, &offset, &size, &uv[0], &uv[2]))
4121 continue;
4122 const ImVec2 pos = base_pos - offset;
4123 const float scale = base_scale;
4124 if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
4125 continue;
4126 ImDrawList* draw_list = GetForegroundDrawList(viewport);
4127 ImTextureRef tex_ref = font_atlas->TexRef;
4128 draw_list->PushTexture(tex_ref);
4129 draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
4130 draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
4131 draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border);
4132 draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill);
4133 if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress)
4134 {
4135 float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI);
4136 float a_max = a_min + IM_PI * 1.65f;
4137 draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max);
4138 draw_list->PathStroke(col_fill, 3.0f * scale);
4139 }
4140 draw_list->PopTexture();
4141 }
4142}
4143
4144//-----------------------------------------------------------------------------
4145// [SECTION] INITIALIZATION, SHUTDOWN
4146//-----------------------------------------------------------------------------
4147
4148// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
4149// 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
4150ImGuiContext* ImGui::GetCurrentContext()
4151{
4152 return GImGui;
4153}
4154
4155void ImGui::SetCurrentContext(ImGuiContext* ctx)
4156{
4157#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
4158 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
4159#else
4160 GImGui = ctx;
4161#endif
4162}
4163
4164void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
4165{
4166 GImAllocatorAllocFunc = alloc_func;
4167 GImAllocatorFreeFunc = free_func;
4168 GImAllocatorUserData = user_data;
4169}
4170
4171// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
4172void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
4173{
4174 *p_alloc_func = GImAllocatorAllocFunc;
4175 *p_free_func = GImAllocatorFreeFunc;
4176 *p_user_data = GImAllocatorUserData;
4177}
4178
4179ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
4180{
4181 ImGuiContext* prev_ctx = GetCurrentContext();
4182 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
4183 SetCurrentContext(ctx);
4184 Initialize();
4185 if (prev_ctx != NULL)
4186 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
4187 return ctx;
4188}
4189
4190void ImGui::DestroyContext(ImGuiContext* ctx)
4191{
4192 ImGuiContext* prev_ctx = GetCurrentContext();
4193 if (ctx == NULL) //-V1051
4194 ctx = prev_ctx;
4195 SetCurrentContext(ctx);
4196 Shutdown();
4197 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
4198 IM_DELETE(ctx);
4199}
4200
4201// IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation.
4202static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
4203{
4204 { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
4205 { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" },
4206 { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" },
4207 { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" },
4208 { ImGuiLocKey_TableReset, "Reset" },
4209 //{ ImGuiLocKey_TableResetAll, "Reset to default###ResetAll" },
4210 { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" },
4211 { ImGuiLocKey_TableResetVisibility, "Reset visibility###ResetVisibility" },
4212 { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" },
4213 { ImGuiLocKey_WindowingPopup, "(Popup)" },
4214 { ImGuiLocKey_WindowingUntitled, "(Untitled)" },
4215 { ImGuiLocKey_OpenLink_s, "Open '%s'" },
4216 { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" },
4217};
4218
4219ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
4220{
4221 IO.Ctx = this;
4222 InputTextState.Ctx = this;
4223
4224 Initialized = false;
4225 WithinFrameScope = WithinFrameScopeWithImplicitWindow = false;
4226 TestEngineHookItems = false;
4227 FrameCount = 0;
4228 FrameCountEnded = FrameCountRendered = -1;
4229 Time = 0.0f;
4230 memset(ContextName, 0, sizeof(ContextName));
4231
4232 Font = NULL;
4233 FontBaked = NULL;
4234 FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f;
4235 FontRasterizerDensity = 1.0f;
4236 IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
4237 if (shared_font_atlas == NULL)
4238 IO.Fonts->OwnerContext = this;
4239 WithinEndChildID = WithinEndPopupID = 0;
4240 TestEngine = NULL;
4241
4242 InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
4243 InputEventsNextEventId = 1;
4244
4245 WindowsActiveCount = 0;
4246 WindowsBorderHoverPadding = 0.0f;
4247 CurrentWindow = NULL;
4248 HoveredWindow = NULL;
4249 HoveredWindowUnderMovingWindow = NULL;
4250 HoveredWindowBeforeClear = NULL;
4251 MovingWindow = NULL;
4252 WheelingWindow = NULL;
4253 WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
4254 WheelingWindowReleaseTimer = 0.0f;
4255
4256 DebugDrawIdConflictsId = 0;
4257 DebugHookIdInfoId = 0;
4258 HoveredId = HoveredIdPreviousFrame = 0;
4259 HoveredIdPreviousFrameItemCount = 0;
4260 HoveredIdAllowOverlap = false;
4261 HoveredIdIsDisabled = false;
4262 HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
4263 ItemUnclipByLog = false;
4264 AnyIdHasBeenEditedThisFrame = false;
4265 ActiveId = 0;
4266 ActiveIdIsAlive = 0;
4267 ActiveIdTimer = 0.0f;
4268 ActiveIdIsJustActivated = false;
4269 ActiveIdWasSelected = ActiveIdWasSoleSelected = false;
4270 ActiveIdAllowOverlap = false;
4271 ActiveIdNoClearOnFocusLoss = false;
4272 ActiveIdHasBeenPressedBefore = false;
4273 ActiveIdHasBeenEditedBefore = false;
4274 ActiveIdHasBeenEditedThisFrame = false;
4275 ActiveIdFromShortcut = false;
4276 ActiveIdClickOffset = ImVec2(-1, -1);
4277 ActiveIdSource = ImGuiInputSource_None;
4278 ActiveIdWindow = NULL;
4279 ActiveIdMouseButton = -1;
4280 ActiveIdDisabledId = 0;
4281 ActiveIdPreviousFrame = 0;
4282 memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData));
4283 memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation));
4284 LastActiveId = 0;
4285 LastActiveIdTimer = 0.0f;
4286 LastActiveIdWasSelected = LastActiveIdWasSoleSelected = false;
4287
4288 LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
4289
4290 ActiveIdUsingNavDirMask = 0x00;
4291 ActiveIdUsingAllKeyboardKeys = false;
4292
4293 CurrentFocusScopeId = 0;
4294 CurrentItemFlags = ImGuiItemFlags_None;
4295 DebugShowGroupRects = false;
4296 GcCompactAll = false;
4297
4298 NavCursorVisible = false;
4299 NavHighlightItemUnderNav = false;
4300 NavMousePosDirty = false;
4301 NavIdIsAlive = false;
4302 NavId = 0;
4303 NavWindow = NULL;
4304 NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
4305 NavLayer = ImGuiNavLayer_Main;
4306 NavIdItemFlags = ImGuiItemFlags_None;
4307 NavOpenContextMenuItemId = NavOpenContextMenuWindowId = 0;
4308 NavNextActivateId = 0;
4309 NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
4310 NavHighlightActivatedId = 0;
4311 NavHighlightActivatedTimer = 0.0f;
4312 NavInputSource = ImGuiInputSource_Keyboard;
4313 NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
4314 NavCursorHideFrames = 0;
4315
4316 NavAnyRequest = false;
4317 NavInitRequest = false;
4318 NavInitRequestFromMove = false;
4319 NavMoveSubmitted = false;
4320 NavMoveScoringItems = false;
4321 NavMoveForwardToNextFrame = false;
4322 NavMoveFlags = ImGuiNavMoveFlags_None;
4323 NavMoveScrollFlags = ImGuiScrollFlags_None;
4324 NavMoveKeyMods = ImGuiMod_None;
4325 NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
4326 NavScoringDebugCount = 0;
4327 NavTabbingDir = 0;
4328 NavTabbingCounter = 0;
4329
4330 NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
4331 NavJustMovedToKeyMods = ImGuiMod_None;
4332 NavJustMovedToIsTabbing = false;
4333 NavJustMovedToHasSelectionData = false;
4334
4335 // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
4336 // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
4337 ConfigNavEnableTabbing = true;
4338 ConfigNavWindowingWithGamepad = true;
4339 ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
4340 ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
4341 NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
4342 NavWindowingInputSource = ImGuiInputSource_None;
4343 NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
4344 NavWindowingToggleLayer = false;
4345 NavWindowingToggleKey = ImGuiKey_None;
4346
4347 DimBgRatio = 0.0f;
4348
4349 DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
4350 DragDropSourceFlags = ImGuiDragDropFlags_None;
4351 DragDropSourceFrameCount = -1;
4352 DragDropMouseButton = -1;
4353 DragDropTargetId = 0;
4354 DragDropTargetFullViewport = 0;
4355 DragDropAcceptFlagsCurr = DragDropAcceptFlagsPrev = ImGuiDragDropFlags_None;
4356 DragDropAcceptIdCurrRectSurface = 0.0f;
4357 DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
4358 DragDropAcceptFrameCount = -1;
4359 DragDropHoldJustPressedId = 0;
4360 memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
4361
4362 ClipperTempDataStacked = 0;
4363
4364 CurrentTable = NULL;
4365 TablesTempDataStacked = 0;
4366 CurrentTabBar = NULL;
4367 CurrentMultiSelect = NULL;
4368 MultiSelectTempDataStacked = 0;
4369
4370 HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
4371 HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
4372
4373 MouseCursor = ImGuiMouseCursor_Arrow;
4374 MouseStationaryTimer = 0.0f;
4375
4376 InputTextPasswordFontBackupFlags = ImFontFlags_None;
4377 InputTextReactivateId = 0;
4378 TempInputId = 0;
4379 memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
4380 BeginMenuDepth = BeginComboDepth = 0;
4381 ColorEditCurrentID = ColorEditSavedID = 0;
4382 ColorEditSavedHue = ColorEditSavedSat = 0.0f;
4383 ColorEditSavedColor = 0;
4384 WindowResizeRelativeMode = false;
4385 ScrollbarSeekMode = 0;
4386 ScrollbarClickDeltaToGrabCenter = 0.0f;
4387 SliderGrabClickOffset = 0.0f;
4388 SliderCurrentAccum = 0.0f;
4389 SliderCurrentAccumDirty = false;
4390 DragCurrentAccumDirty = false;
4391 DragCurrentAccum = 0.0f;
4392 DragSpeedDefaultRatio = 1.0f / 100.0f;
4393 DisabledAlphaBackup = 0.0f;
4394 DisabledStackSize = 0;
4395 TooltipOverrideCount = 0;
4396 TooltipPreviousWindow = NULL;
4397
4398 PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
4399 PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
4400
4401 SettingsLoaded = false;
4402 SettingsDirtyTimer = 0.0f;
4403 HookIdNext = 0;
4404 DemoMarkerCallback = NULL;
4405
4406 memset(LocalizationTable, 0, sizeof(LocalizationTable));
4407
4408 LogEnabled = false;
4409 LogLineFirstItem = false;
4410 LogFlags = ImGuiLogFlags_None;
4411 LogWindow = NULL;
4412 LogNextPrefix = LogNextSuffix = NULL;
4413 LogFile = NULL;
4414 LogLinePosY = FLT_MAX;
4415 LogDepthRef = 0;
4416 LogDepthToExpand = LogDepthToExpandDefault = 2;
4417
4418 ErrorCallback = NULL;
4419 ErrorCallbackUserData = NULL;
4420 ErrorFirst = true;
4421 ErrorCountCurrentFrame = 0;
4422 StackSizesInBeginForCurrentWindow = NULL;
4423
4424 DebugDrawIdConflictsCount = 0;
4425 DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
4426 DebugLocateId = 0;
4427 DebugLogSkippedErrors = 0;
4428 DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4429 DebugLogAutoDisableFrames = 0;
4430 DebugLocateFrames = 0;
4431 DebugBeginReturnValueCullDepth = -1;
4432 DebugItemPickerActive = false;
4433 DebugItemPickerMouseButton = ImGuiMouseButton_Left;
4434 DebugItemPickerBreakId = 0;
4435 DebugFlashStyleColorTime = 0.0f;
4436 DebugFlashStyleColorIdx = ImGuiCol_COUNT;
4437
4438 // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
4439 DebugBreakInWindow = 0;
4440 DebugBreakInTable = 0;
4441 DebugBreakInLocateId = false;
4442 DebugBreakKeyChord = ImGuiKey_Pause;
4443 DebugBreakInShortcutRouting = ImGuiKey_None;
4444
4445 memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
4446 FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
4447 FramerateSecPerFrameAccum = 0.0f;
4448 WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
4449 memset(TempKeychordName, 0, sizeof(TempKeychordName));
4450}
4451
4452ImGuiContext::~ImGuiContext()
4453{
4454 IM_ASSERT(Initialized == false && "Forgot to call DestroyContext()?");
4455}
4456
4457void ImGui::Initialize()
4458{
4459 ImGuiContext& g = *GImGui;
4460 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4461
4462 // Add .ini handle for ImGuiWindow and ImGuiTable types
4463 {
4464 ImGuiSettingsHandler ini_handler;
4465 ini_handler.TypeName = "Window";
4466 ini_handler.TypeHash = ImHashStr("Window");
4467 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4468 ini_handler.CleanupFn = WindowSettingsHandler_Cleanup;
4469 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4470 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4471 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4472 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4473 AddSettingsHandler(&ini_handler);
4474 }
4475 TableSettingsAddSettingsHandler();
4476
4477 // Setup default localization table
4478 LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_COUNTOF(GLocalizationEntriesEnUS));
4479
4480 // Setup default ImGuiPlatformIO clipboard/IME handlers.
4481 g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
4482 g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl;
4483 g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl;
4484 g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl;
4485
4486 // Setup session starting date
4487#ifndef IMGUI_DISABLE_TIME_FUNCTIONS
4488 const time_t session_time = time(NULL);
4489 struct tm session_datetime = {};
4490 if (localtime_r(&session_time, &session_datetime))
4491 g.PlatformIO.Platform_SessionDate = (session_datetime.tm_year + 1900) * 10000 + (session_datetime.tm_mon + 1) * 100 + session_datetime.tm_mday;
4492#endif
4493
4494 // Create default viewport
4495 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4496 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4497 g.Viewports.push_back(viewport);
4498 g.TempBuffer.resize(1024 * 3 + 1, 0);
4499
4500 // Build KeysMayBeCharInput[] lookup table (1 bit per named key)
4501 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4502 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
4503 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
4504 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
4505 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
4506 g.KeysMayBeCharInput.SetBit(key);
4507
4508#ifdef IMGUI_HAS_DOCK
4509#endif
4510
4511 // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow.
4512 // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED.
4513#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
4514 DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
4515#endif
4516
4517 // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context.
4518 // But this link allows us to facilitate/handle a few edge cases better.
4519 ImFontAtlas* atlas = g.IO.Fonts;
4520 g.DrawListSharedData.Context = &g;
4521 RegisterFontAtlas(atlas);
4522
4523 g.Initialized = true;
4524}
4525
4526// This function is merely here to free heap allocations.
4527void ImGui::Shutdown()
4528{
4529 ImGuiContext& g = *GImGui;
4530 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
4531 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
4532
4533 // 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)
4534 for (ImFontAtlas* atlas : g.FontAtlases)
4535 {
4536 UnregisterFontAtlas(atlas);
4537 if (atlas->OwnerContext == &g)
4538 {
4539 IM_ASSERT(atlas->RefCount == 0 && "Destroying context owning a ImFontAtlas which is still used elsewhere!");
4540 if (atlas->RefCount == 0)
4541 {
4542 atlas->Locked = false;
4543 IM_DELETE(atlas);
4544 }
4545 }
4546 }
4547 g.DrawListSharedData.TempBuffer.clear();
4548
4549 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4550 if (!g.Initialized)
4551 return;
4552
4553 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4554 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4555 SaveIniSettingsToDisk(g.IO.IniFilename);
4556
4557 CallContextHooks(&g, ImGuiContextHookType_Shutdown);
4558
4559 // Clear everything else
4560 g.Windows.clear_delete();
4561 g.WindowsFocusOrder.clear();
4562 g.WindowsTempSortBuffer.clear();
4563 g.CurrentWindow = NULL;
4564 g.CurrentWindowStack.clear();
4565 g.WindowsById.Clear();
4566 g.NavWindow = NULL;
4567 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4568 g.ActiveIdWindow = NULL;
4569 g.MovingWindow = NULL;
4570
4571 g.KeysRoutingTable.Clear();
4572
4573 g.ColorStack.clear();
4574 g.StyleVarStack.clear();
4575 g.FontStack.clear();
4576 g.OpenPopupStack.clear();
4577 g.BeginPopupStack.clear();
4578 g.TreeNodeStack.clear();
4579
4580 g.Viewports.clear_delete();
4581
4582 g.TabBars.Clear();
4583 g.CurrentTabBarStack.clear();
4584 g.ShrinkWidthBuffer.clear();
4585
4586 g.ClipperTempData.clear_destruct();
4587
4588 g.Tables.Clear();
4589 g.TablesTempData.clear_destruct();
4590 g.DrawChannelsTempMergeBuffer.clear();
4591
4592 g.MultiSelectStorage.Clear();
4593 g.MultiSelectTempData.clear_destruct();
4594
4595 g.ClipboardHandlerData.clear();
4596 g.MenusIdSubmittedThisFrame.clear();
4597 g.InputTextState.ClearFreeMemory();
4598 g.InputTextLineIndex.clear();
4599 g.InputTextDeactivatedState.ClearFreeMemory();
4600
4601 g.SettingsWindows.clear();
4602 g.SettingsHandlers.clear();
4603
4604 if (g.LogFile)
4605 {
4606#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4607 if (g.LogFile != stdout)
4608#endif
4609 ImFileClose(g.LogFile);
4610 g.LogFile = NULL;
4611 }
4612 g.LogBuffer.clear();
4613 g.DebugLogBuf.clear();
4614 g.DebugLogIndex.clear();
4615
4616 g.Initialized = false;
4617}
4618
4619// When using multiple context it can be helpful to give name a name.
4620// (A) Will be visible in debugger, (B) Will be included in all IMGUI_DEBUG_LOG() calls, (C) Should be <= 15 characters long.
4621void ImGui::SetContextName(ImGuiContext* ctx, const char* name)
4622{
4623 ImStrncpy(ctx->ContextName, name, IM_COUNTOF(ctx->ContextName));
4624}
4625
4626// No specific ordering/dependency support, will see as needed
4627ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
4628{
4629 ImGuiContext& g = *ctx;
4630 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
4631 g.Hooks.push_back(*hook);
4632 g.Hooks.back().HookId = ++g.HookIdNext;
4633 return g.HookIdNext;
4634}
4635
4636// Deferred removal, avoiding issue with changing vector while iterating it
4637void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
4638{
4639 ImGuiContext& g = *ctx;
4640 IM_ASSERT(hook_id != 0);
4641 for (ImGuiContextHook& hook : g.Hooks)
4642 if (hook.HookId == hook_id)
4643 hook.Type = ImGuiContextHookType_PendingRemoval_;
4644}
4645
4646// Call context hooks (used by e.g. test engine)
4647// We assume a small number of hooks so all stored in same array
4648void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
4649{
4650 ImGuiContext& g = *ctx;
4651 for (ImGuiContextHook& hook : g.Hooks)
4652 if (hook.Type == hook_type)
4653 hook.Callback(&g, &hook);
4654}
4655
4656//-----------------------------------------------------------------------------
4657// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4658//-----------------------------------------------------------------------------
4659
4660// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4661ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4662{
4663 memset((void*)this, 0, sizeof(*this));
4664 Ctx = ctx;
4665 Name = ImStrdup(name);
4666 NameBufLen = (int)ImStrlen(name) + 1;
4667 ID = ImHashStr(name);
4668 IDStack.push_back(ID);
4669 MoveId = GetID("#MOVE");
4670 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4671 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4672 AutoPosLastDirection = ImGuiDir_None;
4673 AutoFitFramesX = AutoFitFramesY = -1;
4674 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = 0;
4675 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4676 LastFrameActive = -1;
4677 LastTimeActive = -1.0f;
4678 FontRefSize = 0.0f;
4679 FontWindowScale = FontWindowScaleParents = 1.0f;
4680 SettingsOffset = -1;
4681 DrawList = &DrawListInst;
4682 DrawList->_OwnerName = Name;
4683 DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData);
4684 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4685}
4686
4687ImGuiWindow::~ImGuiWindow()
4688{
4689 IM_ASSERT(DrawList == &DrawListInst);
4690 IM_DELETE(Name);
4691 ColumnsStorage.clear_destruct();
4692}
4693
4694static void SetCurrentWindow(ImGuiWindow* window)
4695{
4696 ImGuiContext& g = *GImGui;
4697 g.CurrentWindow = window;
4698 g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
4699 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4700 g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking
4701 if (window)
4702 {
4703 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
4704 {
4705 ImGuiViewport* viewport = window->Viewport;
4706 g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity()
4707 }
4708 const bool backup_skip_items = window->SkipItems;
4709 window->SkipItems = false;
4710 ImGui::UpdateCurrentFontSize(0.0f);
4711 window->SkipItems = backup_skip_items;
4712 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4713 }
4714}
4715
4716void ImGui::GcCompactTransientMiscBuffers()
4717{
4718 ImGuiContext& g = *GImGui;
4719 g.ItemFlagsStack.clear();
4720 g.GroupStack.clear();
4721 g.InputTextLineIndex.clear();
4722 g.MultiSelectTempDataStacked = 0;
4723 g.MultiSelectTempData.clear_destruct();
4724 TableGcCompactSettings();
4725 for (ImFontAtlas* atlas : g.FontAtlases)
4726 atlas->CompactCache();
4727}
4728
4729// Free up/compact internal window buffers, we can use this when a window becomes unused.
4730// Not freed:
4731// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4732// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4733// FIXME: Consider exposing of elaborating GC policy, e.g. being able to trim excessive ImDrawList gaps. (#9303)
4734void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4735{
4736 window->MemoryCompacted = true;
4737 window->MemoryDrawListIdxCapacity = ImMin((int)(window->DrawList->IdxBuffer.Size * 1.05f), window->DrawList->IdxBuffer.Capacity);
4738 window->MemoryDrawListVtxCapacity = ImMin((int)(window->DrawList->VtxBuffer.Size * 1.05f), window->DrawList->VtxBuffer.Capacity);
4739 window->IDStack.clear();
4740 window->DrawList->_ClearFreeMemory();
4741 window->DC.ChildWindows.clear();
4742 window->DC.ItemWidthStack.clear();
4743 window->DC.TextWrapPosStack.clear();
4744}
4745
4746void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4747{
4748 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4749 // The other buffers tends to amortize much faster.
4750 window->MemoryCompacted = false;
4751 window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4752 window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4753 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4754}
4755
4756void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4757{
4758 ImGuiContext& g = *GImGui;
4759
4760 // Clear previous active id
4761 if (g.ActiveId != 0)
4762 {
4763 // Store deactivate data
4764 ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData;
4765 deactivated_data->ID = g.ActiveId;
4766 deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData?
4767 deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4768 deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId);
4769
4770 // This could be written in a more general way (e.g associate a hook to ActiveId),
4771 // but since this is currently quite an exception we'll leave it as is.
4772 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
4773 if (g.InputTextState.ID == g.ActiveId)
4774 InputTextDeactivateHook(g.ActiveId);
4775
4776 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4777 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4778 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4779 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4780 {
4781 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4782 StopMouseMovingWindow();
4783 }
4784 }
4785
4786 // Set active id
4787 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4788 if (g.ActiveIdIsJustActivated)
4789 {
4790 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() 0x%08X in \"%s\"%*s(previously 0x%08X in \"%s\")\n", id, window ? window->Name : "",
4791 ImMax(0, 20 - (int)(window ? strlen(window->Name) : 0)), "", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "");
4792 g.ActiveIdTimer = 0.0f;
4793 g.ActiveIdHasBeenPressedBefore = false;
4794 g.ActiveIdHasBeenEditedBefore = false;
4795 g.ActiveIdMouseButton = -1;
4796 if (id != 0)
4797 {
4798 g.LastActiveId = id;
4799 g.LastActiveIdTimer = 0.0f;
4800 }
4801 }
4802 g.ActiveId = id;
4803 g.ActiveIdAllowOverlap = false;
4804 g.ActiveIdNoClearOnFocusLoss = false;
4805 g.ActiveIdWindow = window;
4806 g.ActiveIdHasBeenEditedThisFrame = false;
4807 g.ActiveIdFromShortcut = false;
4808 g.ActiveIdDisabledId = 0;
4809 if (id)
4810 {
4811 g.ActiveIdIsAlive = id;
4812 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4813 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4814 }
4815
4816 // Clear declaration of inputs claimed by the widget
4817 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4818 g.ActiveIdUsingNavDirMask = 0x00;
4819 g.ActiveIdUsingAllKeyboardKeys = false;
4820}
4821
4822void ImGui::ClearActiveID()
4823{
4824 SetActiveID(0, NULL); // g.ActiveId = 0;
4825}
4826
4827void ImGui::SetHoveredID(ImGuiID id)
4828{
4829 ImGuiContext& g = *GImGui;
4830 g.HoveredId = id;
4831 g.HoveredIdAllowOverlap = false;
4832 if (id != 0 && g.HoveredIdPreviousFrame != id)
4833 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4834}
4835
4836ImGuiID ImGui::GetHoveredID()
4837{
4838 ImGuiContext& g = *GImGui;
4839 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4840}
4841
4842void ImGui::MarkItemEdited(ImGuiID id)
4843{
4844 // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
4845 // 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.
4846 ImGuiContext& g = *GImGui;
4847
4848 //IM_ASSERT(g.LastItemData.ID == id); // Failing cases include: "widgets_inputtext_scrolling", "widgets_inputtext_multiline_status", "widgets_selectable_input" = case of e.g TempInputText() overlayed manually with different ID (#2718)
4849 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_EditedInternal;
4850 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
4851 return;
4852 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4853
4854 if (g.ActiveId == id || g.ActiveId == 0)
4855 {
4856 // FIXME: Can't we fully rely on LastItemData yet?
4857 g.AnyIdHasBeenEditedThisFrame = g.ActiveIdHasBeenEditedThisFrame = g.ActiveIdHasBeenEditedBefore = true;
4858 }
4859 if (g.DeactivatedItemData.ID == id)
4860 g.DeactivatedItemData.HasBeenEditedBefore = true;
4861
4862 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4863 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4864 // FIXME: This assert is getting a bit meaningless over time. It helped detect some unusual use cases but eventually it is becoming an unnecessary restriction.
4865 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.DeactivatedItemData.ID == id || g.ActiveIdPreviousFrame == id || g.NavJustMovedToId || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4866}
4867
4868bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4869{
4870 // An active popup disable hovering on other windows (apart from its own children)
4871 // FIXME-OPT: This could be cached/stored within the window.
4872 ImGuiContext& g = *GImGui;
4873 if (g.NavWindow)
4874 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
4875 if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
4876 {
4877 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4878 // NB: The 'else' is important because Modal windows are also Popups.
4879 bool want_inhibit = false;
4880 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4881 want_inhibit = true;
4882 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4883 want_inhibit = true;
4884
4885 // Inhibit hover unless the window is within the stack of our modal/popup
4886 if (want_inhibit)
4887 if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4888 return false;
4889 }
4890 return true;
4891}
4892
4893static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4894{
4895 ImGuiContext& g = *GImGui;
4896 if (flags & ImGuiHoveredFlags_DelayNormal)
4897 return g.Style.HoverDelayNormal;
4898 if (flags & ImGuiHoveredFlags_DelayShort)
4899 return g.Style.HoverDelayShort;
4900 return 0.0f;
4901}
4902
4903static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4904{
4905 // Allow instance flags to override shared flags
4906 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4907 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4908 return user_flags | shared_flags;
4909}
4910
4911// This is roughly matching the behavior of internal-facing ItemHoverable()
4912// - 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()
4913// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4914bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4915{
4916 ImGuiContext& g = *GImGui;
4917 ImGuiWindow* window = g.CurrentWindow;
4918 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
4919
4920 if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
4921 {
4922 if (!IsItemFocused())
4923 return false;
4924 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4925 return false;
4926
4927 if (flags & ImGuiHoveredFlags_ForTooltip)
4928 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4929 }
4930 else
4931 {
4932 // Test for bounding box overlap, as updated as ItemAdd()
4933 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4934 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4935 return false;
4936
4937 if (flags & ImGuiHoveredFlags_ForTooltip)
4938 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4939
4940 // Done with rectangle culling so we can perform heavier checks now
4941 // Test if we are hovering the right window (our window could be behind another window)
4942 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4943 // [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
4944 // 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
4945 // the test that has been running for a long while.
4946 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4947 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4948 return false;
4949
4950 // Test if another item is active (e.g. being dragged)
4951 const ImGuiID id = g.LastItemData.ID;
4952 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4953 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap && !g.ActiveIdFromShortcut)
4954 {
4955 // When ActiveId == MoveId it means that either:
4956 // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag)
4957 // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed.
4958 // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId.
4959 bool cancel_is_hovered = true;
4960 if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id))
4961 cancel_is_hovered = false;
4962 if (cancel_is_hovered)
4963 return false;
4964 }
4965
4966 // Test if interactions on this window are blocked by an active popup or modal.
4967 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4968 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4969 return false;
4970
4971 // Test if the item is disabled
4972 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4973 return false;
4974
4975 // Special handling for calling after Begin() which represent the title bar or tab.
4976 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4977 // will never be overwritten so we need to detect the case.
4978 if (id == window->MoveId && window->WriteAccessed)
4979 return false;
4980
4981 // Test if using AllowOverlap and overlapped
4982 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4983 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4984 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4985 return false;
4986 }
4987
4988 // Handle hover delay
4989 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4990 const float delay = CalcDelayFromHoveredFlags(flags);
4991 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4992 {
4993 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(g.LastItemData.Rect.Min);
4994 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4995 g.HoverItemDelayTimer = 0.0f;
4996 g.HoverItemDelayId = hover_delay_id;
4997
4998 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4999 // but once unlocked on a given item we also moving.
5000 //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); }
5001 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
5002 return false;
5003
5004 if (g.HoverItemDelayTimer < delay)
5005 return false;
5006 }
5007
5008 return true;
5009}
5010
5011// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK.
5012// Returns whether the item was hovered, logic differs slightly from IsItemHovered().
5013// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
5014// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
5015// If you used this in your legacy/custom widgets code:
5016// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
5017// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
5018bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
5019{
5020 ImGuiContext& g = *GImGui;
5021 ImGuiWindow* window = g.CurrentWindow;
5022
5023 // Detect ID conflicts
5024 // (this is specifically done here by comparing on hover because it allows us a detection of duplicates that is algorithmically extra cheap, 1 u32 compare per item. No O(log N) lookup whatsoever)
5025#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5026 if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
5027 {
5028 g.HoveredIdPreviousFrameItemCount++;
5029 if (g.DebugDrawIdConflictsId == id)
5030 window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, 2.0f);
5031 }
5032#endif
5033
5034 if (g.HoveredWindow != window)
5035 return false;
5036 if (!IsMouseHoveringRect(bb.Min, bb.Max))
5037 return false;
5038
5039 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
5040 return false;
5041 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
5042 if (!g.ActiveIdFromShortcut)
5043 return false;
5044
5045 // We are done with rectangle culling so we can perform heavier checks now.
5046 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
5047 {
5048 g.HoveredIdIsDisabled = true;
5049 return false;
5050 }
5051
5052 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
5053 // hover test in widgets code. We could also decide to split this function is two.
5054 if (id != 0)
5055 {
5056 // Drag source doesn't report as hovered
5057 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
5058 return false;
5059
5060 SetHoveredID(id);
5061
5062 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
5063 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
5064 if (item_flags & ImGuiItemFlags_AllowOverlap)
5065 {
5066 g.HoveredIdAllowOverlap = true;
5067 if (g.HoveredIdPreviousFrame != id)
5068 return false;
5069 }
5070
5071 // Display shortcut (only works with mouse)
5072 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
5073 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
5074 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
5075 SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
5076 }
5077
5078 // When disabled we'll return false but still set HoveredId
5079 if (item_flags & ImGuiItemFlags_Disabled)
5080 {
5081 // Release active id if turning disabled
5082 if (g.ActiveId == id && id != 0)
5083 ClearActiveID();
5084 g.HoveredIdIsDisabled = true;
5085 return false;
5086 }
5087
5088#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5089 if (id != 0)
5090 {
5091 // [DEBUG] Item Picker tool!
5092 // We perform the check here because reaching is path is rare (1~ time a frame),
5093 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
5094 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
5095 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
5096 GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
5097 if (g.DebugItemPickerBreakId == id)
5098 IM_DEBUG_BREAK();
5099 }
5100#endif
5101
5102 if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
5103 return false;
5104
5105 return true;
5106}
5107
5108// FIXME: This is inlined/duplicated in ItemAdd()
5109// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
5110bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
5111{
5112 ImGuiContext& g = *GImGui;
5113 ImGuiWindow* window = g.CurrentWindow;
5114 if (!bb.Overlaps(window->ClipRect))
5115 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
5116 if (!g.ItemUnclipByLog)
5117 return true;
5118 return false;
5119}
5120
5121// This is also inlined in ItemAdd()
5122// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
5123void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect)
5124{
5125 ImGuiContext& g = *GImGui;
5126 g.LastItemData.ID = item_id;
5127 g.LastItemData.ItemFlags = item_flags;
5128 g.LastItemData.StatusFlags = status_flags;
5129 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
5130}
5131
5132static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
5133{
5134 ImGuiContext& g = *GImGui;
5135 SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect);
5136}
5137
5138static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect)
5139{
5140 ImGuiContext& g = *GImGui;
5141 SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.ChildItemStatusFlags, rect);
5142}
5143
5144float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
5145{
5146 if (wrap_pos_x < 0.0f)
5147 return 0.0f;
5148
5149 ImGuiContext& g = *GImGui;
5150 ImGuiWindow* window = g.CurrentWindow;
5151 if (wrap_pos_x == 0.0f)
5152 {
5153 // We could decide to setup a default wrapping max point for auto-resizing windows,
5154 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
5155 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
5156 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
5157 //else
5158 wrap_pos_x = window->WorkRect.Max.x;
5159 }
5160 else if (wrap_pos_x > 0.0f)
5161 {
5162 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
5163 }
5164
5165 return ImMax(wrap_pos_x - pos.x, 1.0f);
5166}
5167
5168// IM_ALLOC() == ImGui::MemAlloc()
5169void* ImGui::MemAlloc(size_t size)
5170{
5171 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
5172#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5173 if (ImGuiContext* ctx = GImGui)
5174 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
5175#endif
5176 return ptr;
5177}
5178
5179// IM_FREE() == ImGui::MemFree()
5180void ImGui::MemFree(void* ptr)
5181{
5182#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5183 if (ptr != NULL)
5184 if (ImGuiContext* ctx = GImGui)
5185 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
5186#endif
5187 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
5188}
5189
5190void ImGui::DemoMarker(const char* file, int line, const char* section)
5191{
5192 ImGuiContext& g = *GImGui;
5193 if (g.DemoMarkerCallback != NULL)
5194 g.DemoMarkerCallback(file, line, section);
5195}
5196
5197// 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"
5198void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
5199{
5200 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5201 IM_UNUSED(ptr);
5202 if (entry->FrameCount != frame_count)
5203 {
5204 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_COUNTOF(info->LastEntriesBuf);
5205 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5206 entry->FrameCount = frame_count;
5207 entry->AllocCount = entry->FreeCount = 0;
5208 }
5209 if (size != (size_t)-1)
5210 {
5211 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
5212 entry->AllocCount++;
5213 info->TotalAllocCount++;
5214 }
5215 else
5216 {
5217 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
5218 entry->FreeCount++;
5219 info->TotalFreeCount++;
5220 }
5221}
5222
5223// A conformant backend should return NULL on failure (e.g. clipboard data is not text).
5224const char* ImGui::GetClipboardText()
5225{
5226 ImGuiContext& g = *GImGui;
5227 return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : NULL;
5228}
5229
5230void ImGui::SetClipboardText(const char* text)
5231{
5232 ImGuiContext& g = *GImGui;
5233 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5234 g.PlatformIO.Platform_SetClipboardTextFn(&g, text);
5235}
5236
5237const char* ImGui::GetVersion()
5238{
5239 return IMGUI_VERSION;
5240}
5241
5242ImGuiIO& ImGui::GetIO()
5243{
5244 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5245 return GImGui->IO;
5246}
5247
5248// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5249ImGuiIO& ImGui::GetIO(ImGuiContext* ctx)
5250{
5251 IM_ASSERT(ctx != NULL);
5252 return ctx->IO;
5253}
5254
5255ImGuiPlatformIO& ImGui::GetPlatformIO()
5256{
5257 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
5258 return GImGui->PlatformIO;
5259}
5260
5261// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5262ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx)
5263{
5264 IM_ASSERT(ctx != NULL);
5265 return ctx->PlatformIO;
5266}
5267
5268// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
5269ImDrawData* ImGui::GetDrawData()
5270{
5271 ImGuiContext& g = *GImGui;
5272 ImGuiViewportP* viewport = g.Viewports[0];
5273 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
5274}
5275
5276double ImGui::GetTime()
5277{
5278 return GImGui->Time;
5279}
5280
5281int ImGui::GetFrameCount()
5282{
5283 return GImGui->FrameCount;
5284}
5285
5286static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
5287{
5288 // Create the draw list on demand, because they are not frequently used for all viewports
5289 ImGuiContext& g = *GImGui;
5290 IM_ASSERT(drawlist_no < IM_COUNTOF(viewport->BgFgDrawLists));
5291 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
5292 if (draw_list == NULL)
5293 {
5294 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
5295 draw_list->_OwnerName = drawlist_name;
5296 viewport->BgFgDrawLists[drawlist_no] = draw_list;
5297 }
5298
5299 // Our ImDrawList system requires that there is always a command
5300 if (viewport->BgFgDrawListsLastTimeActive[drawlist_no] != (float)g.Time)
5301 {
5302 draw_list->_ResetForNewFrame();
5303 draw_list->PushTexture(g.IO.Fonts->TexRef);
5304 draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
5305 viewport->BgFgDrawListsLastTimeActive[drawlist_no] = (float)g.Time;
5306 }
5307 return draw_list;
5308}
5309
5310ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
5311{
5312 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
5313}
5314
5315ImDrawList* ImGui::GetBackgroundDrawList()
5316{
5317 ImGuiContext& g = *GImGui;
5318 return GetBackgroundDrawList(g.Viewports[0]);
5319}
5320
5321ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
5322{
5323 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
5324}
5325
5326ImDrawList* ImGui::GetForegroundDrawList()
5327{
5328 ImGuiContext& g = *GImGui;
5329 return GetForegroundDrawList(g.Viewports[0]);
5330}
5331
5332ImDrawListSharedData* ImGui::GetDrawListSharedData()
5333{
5334 return &GImGui->DrawListSharedData;
5335}
5336
5337void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
5338{
5339 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
5340 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
5341 // This is because we want ActiveId to be set even when the window is not permitted to move.
5342 ImGuiContext& g = *GImGui;
5343 FocusWindow(window);
5344 SetActiveID(window->MoveId, window);
5345 if (g.IO.ConfigNavCursorVisibleAuto)
5346 g.NavCursorVisible = false;
5347 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
5348 g.ActiveIdNoClearOnFocusLoss = true;
5349 SetActiveIdUsingAllKeyboardKeys();
5350
5351 bool can_move_window = true;
5352 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
5353 can_move_window = false;
5354 if (can_move_window)
5355 g.MovingWindow = window;
5356}
5357
5358// This is not 100% symmetric with StartMouseMovingWindow().
5359// We do NOT clear ActiveID, because:
5360// - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired.
5361// - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item).
5362void ImGui::StopMouseMovingWindow()
5363{
5364 ImGuiContext& g = *GImGui;
5365
5366 // [nb: docking branch has more stuff in this function]
5367
5368 g.MovingWindow = NULL;
5369}
5370
5371// Handle mouse moving window
5372// Note: moving window with the navigation keys (Square + d-pad / Ctrl+Tab + Arrows) are processed in NavUpdateWindowing()
5373// FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId.
5374// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
5375// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
5376void ImGui::UpdateMouseMovingWindowNewFrame()
5377{
5378 ImGuiContext& g = *GImGui;
5379 if (g.MovingWindow != NULL)
5380 {
5381 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
5382 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
5383 KeepAliveID(g.ActiveId);
5384 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
5385 ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
5386 if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
5387 {
5388 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
5389 SetWindowPos(moving_window, pos, ImGuiCond_Always);
5390 FocusWindow(g.MovingWindow);
5391 }
5392 else
5393 {
5394 StopMouseMovingWindow();
5395 ClearActiveID();
5396 }
5397 }
5398 else
5399 {
5400 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
5401 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
5402 {
5403 KeepAliveID(g.ActiveId);
5404 if (!g.IO.MouseDown[0])
5405 ClearActiveID();
5406 }
5407 }
5408}
5409
5410// Initiate focusing and moving window when clicking on empty space or title bar.
5411// Initiate focusing window when clicking on a disabled item.
5412// Handle left-click and right-click focus.
5413void ImGui::UpdateMouseMovingWindowEndFrame()
5414{
5415 ImGuiContext& g = *GImGui;
5416 if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
5417 return;
5418
5419 // Unless we just made a window/popup appear
5420 if (g.NavWindow && g.NavWindow->Appearing)
5421 return;
5422
5423 ImGuiWindow* hovered_window = g.HoveredWindow;
5424
5425 // Click on empty space to focus window and start moving
5426 // (after we're done with all our widgets)
5427 if (IsMouseClicked(0, ImGuiInputFlags_None, ImGuiKeyOwner_NoOwner))
5428 {
5429 // Handle the edge case of a popup being closed while clicking in its empty space.
5430 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
5431 ImGuiWindow* hovered_root = hovered_window ? hovered_window->RootWindow : NULL;
5432 const bool is_closed_popup = hovered_root && (hovered_root->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(hovered_root->PopupId, ImGuiPopupFlags_AnyPopupLevel);
5433 const bool is_queued_focus_request = g.NavMoveSubmitted && (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi);
5434
5435 if (hovered_window != NULL && !is_closed_popup && !is_queued_focus_request)
5436 {
5437 StartMouseMovingWindow(hovered_window); //-V595
5438
5439 // FIXME: In principle we might be able to call StopMouseMovingWindow() below.
5440 // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symmetrical, at the later doesn't clear ActiveId.
5441
5442 // Cancel moving if clicked outside of title bar
5443 if ((hovered_window->BgClickFlags & ImGuiWindowBgClickFlags_Move) == 0) // set by io.ConfigWindowsMoveFromTitleBarOnly
5444 if (!(hovered_root->Flags & ImGuiWindowFlags_NoTitleBar))
5445 if (!hovered_root->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
5446 g.MovingWindow = NULL;
5447
5448 // Cancel moving if clicked over an item which was disabled or inhibited by popups
5449 // (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)
5450 if (g.HoveredIdIsDisabled)
5451 {
5452 g.MovingWindow = NULL;
5453 g.ActiveIdDisabledId = g.HoveredId;
5454 }
5455 }
5456 else if (hovered_window == NULL && g.NavWindow != NULL)
5457 {
5458 // Clicking on void disable focus
5459 FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
5460 }
5461 }
5462
5463 // With right mouse button we close popups without changing focus based on where the mouse is aimed
5464 // Instead, focus will be restored to the window under the bottom-most closed popup.
5465 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
5466 if (g.HoveredId == 0 && IsMouseClicked(1, ImGuiInputFlags_None, ImGuiKeyOwner_NoOwner))
5467 {
5468 // Find the top-most window between HoveredWindow and the top-most Modal Window.
5469 // This is where we can trim the popup stack.
5470 ImGuiWindow* modal = GetTopMostPopupModal();
5471 bool hovered_window_above_modal = hovered_window && (modal == NULL || IsWindowAbove(hovered_window, modal));
5472 ClosePopupsOverWindow(hovered_window_above_modal ? hovered_window : modal, true);
5473 }
5474}
5475
5476static bool IsWindowActiveAndVisible(ImGuiWindow* window)
5477{
5478 return window->Active && !window->Hidden;
5479}
5480
5481// 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)
5482void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos)
5483{
5484 ImGuiContext& g = *GImGui;
5485 ImGuiIO& io = g.IO;
5486
5487 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
5488 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
5489 g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding);
5490
5491 // Find the window hovered by mouse:
5492 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
5493 // - 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.
5494 // - 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.
5495 bool clear_hovered_windows = false;
5496 FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
5497 g.HoveredWindowBeforeClear = g.HoveredWindow;
5498
5499 // Modal windows prevents mouse from hovering behind them.
5500 ImGuiWindow* modal_window = GetTopMostPopupModal();
5501 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window))
5502 clear_hovered_windows = true;
5503
5504 // Disabled mouse hovering (we don't currently clear MousePos, we could)
5505 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
5506 clear_hovered_windows = true;
5507
5508 // We track click ownership. When clicked outside of a window the click is owned by the application and
5509 // won't report hovering nor request capture even while dragging over our windows afterward.
5510 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
5511 const bool has_open_modal = (modal_window != NULL);
5512 int mouse_earliest_down = -1;
5513 bool mouse_any_down = false;
5514 for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++)
5515 {
5516 if (io.MouseClicked[i])
5517 {
5518 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
5519 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
5520 }
5521 mouse_any_down |= io.MouseDown[i];
5522 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
5523 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
5524 mouse_earliest_down = i;
5525 }
5526 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
5527 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
5528
5529 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
5530 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
5531 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
5532 if (!mouse_avail && !mouse_dragging_extern_payload)
5533 clear_hovered_windows = true;
5534
5535 if (clear_hovered_windows)
5536 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5537
5538 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
5539 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
5540 if (g.WantCaptureMouseNextFrame != -1)
5541 {
5542 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
5543 }
5544 else
5545 {
5546 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
5547 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
5548 }
5549
5550 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
5551 io.WantCaptureKeyboard = false;
5552 if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
5553 {
5554 if ((g.ActiveId != 0) || (modal_window != NULL))
5555 io.WantCaptureKeyboard = true;
5556 else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
5557 io.WantCaptureKeyboard = true;
5558 }
5559 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
5560 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
5561
5562 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
5563 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
5564}
5565
5566// Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
5567// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
5568static void SetupDrawListSharedData()
5569{
5570 ImGuiContext& g = *GImGui;
5571 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
5572 for (ImGuiViewportP* viewport : g.Viewports)
5573 virtual_space.Add(viewport->GetMainRect());
5574 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
5575 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
5576 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
5577 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
5578 if (g.Style.AntiAliasedLines)
5579 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
5580 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
5581 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
5582 if (g.Style.AntiAliasedFill)
5583 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
5584 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
5585 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
5586 g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments.
5587}
5588
5589void ImGui::NewFrame()
5590{
5591 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5592 ImGuiContext& g = *GImGui;
5593
5594 // Remove pending delete hooks before frame start.
5595 // This deferred removal avoid issues of removal while iterating the hook vector
5596 for (int n = g.Hooks.Size - 1; n >= 0; n--)
5597 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
5598 g.Hooks.erase(&g.Hooks[n]);
5599
5600 CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
5601
5602 // Check and assert for various common IO and Configuration mistakes
5603 ErrorCheckNewFrameSanityChecks();
5604
5605 // Load settings on first frame, save settings when modified (after a delay)
5606 UpdateSettings();
5607
5608 g.Time += g.IO.DeltaTime;
5609 g.FrameCount += 1;
5610 g.SessionDate = ImGuiPackedDate(g.PlatformIO.Platform_SessionDate);
5611 g.TooltipOverrideCount = 0;
5612 g.WindowsActiveCount = 0;
5613 g.MenusIdSubmittedThisFrame.resize(0);
5614
5615 // Calculate frame-rate for the user, as a purely luxurious feature
5616 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
5617 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
5618 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_COUNTOF(g.FramerateSecPerFrame);
5619 g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_COUNTOF(g.FramerateSecPerFrame));
5620 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
5621
5622 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
5623 g.InputEventsTrail.resize(0);
5624 UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
5625
5626 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
5627 UpdateViewportsNewFrame();
5628
5629 // Update texture list (collect destroyed textures, etc.)
5630 UpdateTexturesNewFrame();
5631
5632 // Setup current font and draw list shared data
5633 SetupDrawListSharedData();
5634 UpdateFontsNewFrame();
5635
5636 g.WithinFrameScope = true;
5637
5638 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
5639 for (ImGuiViewportP* viewport : g.Viewports)
5640 viewport->DrawDataP.Valid = false;
5641
5642 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
5643 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
5644 KeepAliveID(g.DragDropPayload.SourceId);
5645
5646 // [DEBUG]
5647 if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding Ctrl
5648 g.DebugDrawIdConflictsId = 0;
5649 if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
5650 g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame;
5651
5652 // Update HoveredId data
5653 if (!g.HoveredIdPreviousFrame)
5654 g.HoveredIdTimer = 0.0f;
5655 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
5656 g.HoveredIdNotActiveTimer = 0.0f;
5657 if (g.HoveredId)
5658 g.HoveredIdTimer += g.IO.DeltaTime;
5659 if (g.HoveredId && g.ActiveId != g.HoveredId)
5660 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
5661 g.HoveredIdPreviousFrame = g.HoveredId;
5662 g.HoveredIdPreviousFrameItemCount = 0;
5663 g.HoveredId = 0;
5664 g.HoveredIdAllowOverlap = false;
5665 g.HoveredIdIsDisabled = false;
5666
5667 // Clear ActiveID if the item is not alive anymore.
5668 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
5669 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
5670 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
5671 {
5672 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() 0x%08X because it isn't marked alive anymore!\n", g.ActiveId);
5673 ClearActiveID();
5674 }
5675
5676 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
5677 if (g.ActiveId)
5678 g.ActiveIdTimer += g.IO.DeltaTime;
5679 if (g.ActiveId && g.ActiveId == g.LastActiveId)
5680 {
5681 g.LastActiveIdWasSelected = g.ActiveIdWasSelected;
5682 g.LastActiveIdWasSoleSelected = g.ActiveIdWasSoleSelected;
5683 }
5684 g.LastActiveIdTimer += g.IO.DeltaTime;
5685 g.ActiveIdPreviousFrame = g.ActiveId;
5686 g.ActiveIdIsAlive = 0;
5687 g.AnyIdHasBeenEditedThisFrame = false;
5688 g.ActiveIdHasBeenEditedThisFrame = false;
5689 g.ActiveIdIsJustActivated = false;
5690 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
5691 g.TempInputId = 0;
5692 if (g.InputTextReactivateId != 0 && g.InputTextReactivateId != g.DeactivatedItemData.ID)
5693 g.InputTextReactivateId = 0;
5694 if (g.ActiveId == 0)
5695 {
5696 g.ActiveIdUsingNavDirMask = 0x00;
5697 g.ActiveIdUsingAllKeyboardKeys = false;
5698 }
5699 if (g.DeactivatedItemData.ElapseFrame < g.FrameCount)
5700 g.DeactivatedItemData.ID = 0;
5701 g.DeactivatedItemData.IsAlive = false;
5702 if (g.InputTextDeactivatedState.ElapseFrame < g.FrameCount)
5703 g.InputTextDeactivatedState.ID = 0;
5704
5705 // Record when we have been stationary as this state is preserved while over same item.
5706 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5707 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5708 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5709 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5710 else if (g.HoverItemDelayId == 0)
5711 g.HoverItemUnlockedStationaryId = 0;
5712 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5713 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5714 else if (g.HoveredWindow == NULL)
5715 g.HoverWindowUnlockedStationaryId = 0;
5716
5717 // Update hover delay for IsItemHovered() with delays and tooltips
5718 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5719 if (g.HoverItemDelayId != 0)
5720 {
5721 g.HoverItemDelayTimer += g.IO.DeltaTime;
5722 g.HoverItemDelayClearTimer = 0.0f;
5723 g.HoverItemDelayId = 0;
5724 }
5725 else if (g.HoverItemDelayTimer > 0.0f)
5726 {
5727 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5728 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5729 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5730 if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5731 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.
5732 }
5733
5734 // Close popups on focus lost (currently wip/opt-in)
5735 //if (g.IO.AppFocusLost)
5736 // ClosePopupsExceptModals();
5737
5738 // Update keyboard input state
5739 UpdateKeyboardInputs();
5740
5741 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5742 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5743 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5744 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5745
5746 // Drag and drop
5747 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5748 g.DragDropAcceptIdCurr = 0;
5749 g.DragDropAcceptFlagsPrev = g.DragDropAcceptFlagsCurr;
5750 g.DragDropAcceptFlagsCurr = ImGuiDragDropFlags_None;
5751 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5752 g.DragDropWithinSource = false;
5753 g.DragDropWithinTarget = false;
5754 g.DragDropHoldJustPressedId = 0;
5755 if (g.DragDropActive)
5756 {
5757 // Also works when g.ActiveId==0 (aka leftover payload in progress, no active id)
5758 // You may disable this externally by hijacking the input route:
5759 // 'if (GetDragDropPayload() != NULL) { Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive); }
5760 // but you will not get a return value from Shortcut() due to ActiveIdUsingAllKeyboardKeys logic. You can however poll IsKeyPressed(ImGuiKey_Escape) afterwards.
5761 ImGuiID owner_id = g.ActiveId ? g.ActiveId : ImHashStr("##DragDropCancelHandler");
5762 if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteGlobal, owner_id))
5763 {
5764 ClearActiveID();
5765 ClearDragDrop();
5766 }
5767 }
5768 g.TooltipPreviousWindow = NULL;
5769
5770 // Update keyboard/gamepad navigation
5771 NavUpdate();
5772
5773 // Update mouse input state
5774 UpdateMouseInputs();
5775
5776 // Mark all windows as not visible and compact unused memory.
5777 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5778 const bool gc_all = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f);
5779 const float memory_compact_start_time = gc_all ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5780 for (ImGuiWindow* window : g.Windows)
5781 {
5782 window->WasActive = window->Active;
5783 window->Active = false;
5784 window->WriteAccessed = false;
5785 window->BeginCountPreviousFrame = window->BeginCount;
5786 window->BeginCount = 0;
5787
5788 // Garbage collect transient buffers of recently unused windows
5789 if ((!window->WasActive || gc_all) && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5790 GcCompactTransientWindowBuffers(window);
5791 }
5792
5793 // Find hovered window
5794 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5795 // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
5796 UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos);
5797
5798 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5799 UpdateMouseMovingWindowNewFrame();
5800
5801 // Background darkening/whitening
5802 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5803 g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5804 else
5805 g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5806
5807 g.MouseCursor = ImGuiMouseCursor_Arrow;
5808 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5809
5810 // Platform IME data: reset for the frame
5811 g.PlatformImeDataPrev = g.PlatformImeData;
5812 g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false;
5813
5814 // Mouse wheel scrolling, scale
5815 UpdateMouseWheel();
5816
5817 // Garbage collect transient buffers of recently unused tables
5818 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5819 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5820 TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5821 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5822 {
5823 table_temp_data.ReconcileColumnsRequests.clear(); // Unusual: clear every frame because this is rarely used.
5824 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5825 TableGcCompactTransientBuffers(&table_temp_data);
5826 }
5827 if (g.GcCompactAll)
5828 GcCompactTransientMiscBuffers();
5829 g.GcCompactAll = false;
5830
5831 // Closing the focused window restore focus to the first active root window in descending z-order
5832 if (g.NavWindow && !g.NavWindow->WasActive)
5833 FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5834
5835 // No window should be open at the beginning of the frame.
5836 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5837 g.CurrentWindowStack.resize(0);
5838 g.BeginPopupStack.resize(0);
5839 g.ItemFlagsStack.resize(0);
5840 g.ItemFlagsStack.push_back(ImGuiItemFlags_Default_); // Default flags
5841 g.CurrentItemFlags = g.ItemFlagsStack.back();
5842 g.GroupStack.resize(0);
5843
5844 // [DEBUG] Update debug features
5845#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5846 UpdateDebugToolItemPicker();
5847 UpdateDebugToolItemPathQuery();
5848 UpdateDebugToolFlashStyleColor();
5849 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5850 {
5851 g.DebugLocateId = 0;
5852 g.DebugBreakInLocateId = false;
5853 }
5854 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5855 {
5856 DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5857 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5858 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5859 }
5860#endif
5861
5862 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5863 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5864 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5865 g.WithinFrameScopeWithImplicitWindow = true;
5866 SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5867 Begin("Debug##Default");
5868 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5869
5870 // Store stack sizes
5871 g.ErrorCountCurrentFrame = 0;
5872 ErrorRecoveryStoreState(&g.StackSizesInNewFrame);
5873
5874 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5875 // allowing to validate correct Begin/End behavior in user code.
5876#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5877 if (g.IO.ConfigDebugBeginReturnValueLoop)
5878 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5879 else
5880 g.DebugBeginReturnValueCullDepth = -1;
5881#endif
5882
5883 CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5884}
5885
5886// FIXME: Add a more explicit sort order in the window structure.
5887static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5888{
5889 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5890 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5891 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5892 return d;
5893 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5894 return d;
5895 return a->BeginOrderWithinParent - b->BeginOrderWithinParent;
5896}
5897
5898static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5899{
5900 out_sorted_windows->push_back(window);
5901 if (window->Active)
5902 {
5903 int count = window->DC.ChildWindows.Size;
5904 ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5905 for (int i = 0; i < count; i++)
5906 {
5907 ImGuiWindow* child = window->DC.ChildWindows[i];
5908 if (child->Active)
5909 AddWindowToSortBuffer(out_sorted_windows, child);
5910 }
5911 }
5912}
5913
5914static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5915{
5916 ImGuiContext& g = *GImGui;
5917 ImGuiViewportP* viewport = g.Viewports[0];
5918 g.IO.MetricsRenderWindows++;
5919 if (window->DrawList->_Splitter._Count > 1)
5920 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5921 ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5922 for (ImGuiWindow* child : window->DC.ChildWindows)
5923 if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5924 AddWindowToDrawData(child, layer);
5925}
5926
5927static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5928{
5929 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5930}
5931
5932// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5933static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5934{
5935 AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5936}
5937
5938static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5939{
5940 int n = builder->Layers[0]->Size;
5941 int full_size = n;
5942 for (int i = 1; i < IM_COUNTOF(builder->Layers); i++)
5943 full_size += builder->Layers[i]->Size;
5944 builder->Layers[0]->resize(full_size);
5945 for (int layer_n = 1; layer_n < IM_COUNTOF(builder->Layers); layer_n++)
5946 {
5947 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5948 if (layer->empty())
5949 continue;
5950 memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5951 n += layer->Size;
5952 layer->resize(0);
5953 }
5954}
5955
5956static void InitViewportDrawData(ImGuiViewportP* viewport)
5957{
5958 ImGuiContext& g = *GImGui;
5959 ImDrawData* draw_data = &viewport->DrawDataP;
5960
5961 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5962 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5963 viewport->DrawDataBuilder.Layers[0]->resize(0);
5964 viewport->DrawDataBuilder.Layers[1]->resize(0);
5965
5966 draw_data->Valid = true;
5967 draw_data->FrameCount = g.FrameCount;
5968 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5969 draw_data->DisplayPos = viewport->Pos;
5970 draw_data->DisplaySize = viewport->Size;
5971 draw_data->FramebufferScale = g.IO.DisplayFramebufferScale;
5972 draw_data->OwnerViewport = viewport;
5973 draw_data->Textures = &g.PlatformIO.Textures;
5974#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5975 draw_data->CmdListsCount = 0;
5976#endif
5977}
5978
5979// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5980// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5981// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5982// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5983// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5984// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5985// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
5986// which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
5987void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5988{
5989 ImGuiWindow* window = GetCurrentWindow();
5990 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5991 window->ClipRect = window->DrawList->_ClipRectStack.back();
5992}
5993
5994void ImGui::PopClipRect()
5995{
5996 ImGuiWindow* window = GetCurrentWindow();
5997 window->DrawList->PopClipRect();
5998 window->ClipRect = window->DrawList->_ClipRectStack.back();
5999}
6000
6001static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
6002{
6003 if ((col & IM_COL32_A_MASK) == 0)
6004 return;
6005
6006 ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport();
6007 ImRect viewport_rect = viewport->GetMainRect();
6008
6009 // Draw behind window by moving the draw command at the FRONT of the draw list
6010 {
6011 // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
6012 // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
6013 // 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.
6014 ImDrawList* draw_list = window->RootWindow->DrawList;
6015 if (draw_list->CmdBuffer.Size == 0)
6016 draw_list->AddDrawCmd();
6017 draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to strictly ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
6018 draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
6019 ImDrawCmd cmd = draw_list->CmdBuffer.back();
6020 IM_ASSERT(cmd.ElemCount == 6);
6021 draw_list->CmdBuffer.pop_back();
6022 draw_list->CmdBuffer.push_front(cmd);
6023 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
6024 draw_list->PopClipRect();
6025 }
6026}
6027
6028ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
6029{
6030 ImGuiContext& g = *GImGui;
6031 ImGuiWindow* bottom_most_visible_window = parent_window;
6032 for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
6033 {
6034 ImGuiWindow* window = g.Windows[i];
6035 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6036 continue;
6037 if (!IsWindowWithinBeginStackOf(window, parent_window))
6038 break;
6039 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
6040 bottom_most_visible_window = window;
6041 }
6042 return bottom_most_visible_window;
6043}
6044
6045static void ImGui::RenderDimmedBackgrounds()
6046{
6047 ImGuiContext& g = *GImGui;
6048 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
6049 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
6050 return;
6051 const bool dim_bg_for_modal = (modal_window != NULL);
6052 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
6053 if (!dim_bg_for_modal && !dim_bg_for_window_list)
6054 return;
6055
6056 if (dim_bg_for_modal)
6057 {
6058 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
6059 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
6060 RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
6061 }
6062 else if (dim_bg_for_window_list)
6063 {
6064 // Draw dimming behind Ctrl+Tab target window and behind Ctrl+Tab UI window
6065 RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
6066
6067 // Draw border around Ctrl+Tab target window
6068 ImGuiWindow* window = g.NavWindowingTargetAnim;
6069 ImGuiViewport* viewport = GetMainViewport();
6070 float distance = g.FontSize;
6071 ImRect bb = window->Rect();
6072 bb.Expand(distance);
6073 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
6074 bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
6075 if (window->DrawList->CmdBuffer.Size == 0)
6076 window->DrawList->AddDrawCmd();
6077 window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
6078 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 3.0f); // FIXME-DPI
6079 window->DrawList->PopClipRect();
6080 }
6081}
6082
6083// 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.
6084void ImGui::EndFrame()
6085{
6086 ImGuiContext& g = *GImGui;
6087 IM_ASSERT(g.Initialized);
6088
6089 // Don't process EndFrame() multiple times.
6090 if (g.FrameCountEnded == g.FrameCount)
6091 return;
6092 IM_ASSERT_USER_ERROR_RET(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?");
6093
6094 CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
6095
6096 // [EXPERIMENTAL] Recover from errors
6097 if (g.IO.ConfigErrorRecovery)
6098 ErrorRecoveryTryToRecoverState(&g.StackSizesInNewFrame);
6099 ErrorCheckEndFrameSanityChecks();
6100 ErrorCheckEndFrameFinalizeErrorTooltip();
6101
6102 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
6103 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
6104 if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
6105 {
6106 IM_ASSERT(ime_data->ViewportId == IMGUI_VIEWPORT_DEFAULT_ID); // master branch
6107 ImGuiViewport* viewport = GetMainViewport();
6108 IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y, viewport->ID);
6109 g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
6110 }
6111 g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0;
6112
6113 // Hide and unfocus implicit/fallback "Debug" window if it hasn't been used
6114 g.WithinFrameScopeWithImplicitWindow = false;
6115 if (g.CurrentWindow && g.CurrentWindow->IsFallbackWindow && g.CurrentWindow->WriteAccessed == false)
6116 {
6117 g.CurrentWindow->Active = false;
6118 if (g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow)
6119 FocusWindow(NULL);
6120 }
6121 End();
6122
6123 // Update navigation: Ctrl+Tab, wrap-around requests
6124 NavEndFrame();
6125
6126 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
6127 if (g.DragDropActive)
6128 {
6129 bool is_delivered = g.DragDropPayload.Delivery;
6130 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
6131 if (is_delivered || is_elapsed)
6132 ClearDragDrop();
6133 }
6134
6135 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
6136 // If you want to handle source item disappearing: instead of submitting your description tooltip
6137 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
6138 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
6139 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
6140 if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
6141 {
6142 g.DragDropWithinSource = true;
6143 SetTooltip("...");
6144 g.DragDropWithinSource = false;
6145 }
6146
6147 // End frame
6148 g.WithinFrameScope = false;
6149 g.FrameCountEnded = g.FrameCount;
6150 UpdateFontsEndFrame();
6151
6152 // Initiate moving window + handle left-click and right-click focus
6153 UpdateMouseMovingWindowEndFrame();
6154
6155 // Sort the window list so that all child windows are after their parent
6156 // We cannot do that on FocusWindow() because children may not exist yet
6157 g.WindowsTempSortBuffer.resize(0);
6158 g.WindowsTempSortBuffer.reserve(g.Windows.Size);
6159 for (ImGuiWindow* window : g.Windows)
6160 {
6161 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
6162 continue;
6163 AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
6164 }
6165
6166 // 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.
6167 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
6168 g.Windows.swap(g.WindowsTempSortBuffer);
6169 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
6170
6171 UpdateTexturesEndFrame();
6172
6173 // Unlock font atlas
6174 for (ImFontAtlas* atlas : g.FontAtlases)
6175 atlas->Locked = false;
6176
6177 // Clear Input data for next frame
6178 g.IO.MousePosPrev = g.IO.MousePos;
6179 g.IO.AppFocusLost = false;
6180 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
6181 g.IO.InputQueueCharacters.resize(0);
6182
6183 CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
6184}
6185
6186// Prepare the data for rendering so you can call GetDrawData()
6187// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all:
6188// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
6189void ImGui::Render()
6190{
6191 ImGuiContext& g = *GImGui;
6192 IM_ASSERT(g.Initialized);
6193
6194 if (g.FrameCountEnded != g.FrameCount)
6195 EndFrame();
6196 if (g.FrameCountRendered == g.FrameCount)
6197 return;
6198 g.FrameCountRendered = g.FrameCount;
6199
6200 g.IO.MetricsRenderWindows = 0;
6201 CallContextHooks(&g, ImGuiContextHookType_RenderPre);
6202
6203 // Add background ImDrawList (for each active viewport)
6204 for (ImGuiViewportP* viewport : g.Viewports)
6205 {
6206 InitViewportDrawData(viewport);
6207 if (viewport->BgFgDrawLists[0] != NULL && viewport->BgFgDrawListsLastTimeActive[0] == (float)g.Time)
6208 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
6209 }
6210
6211 // Draw modal/window whitening backgrounds
6212 RenderDimmedBackgrounds();
6213
6214 // Add ImDrawList to render
6215 ImGuiWindow* windows_to_render_top_most[2];
6216 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
6217 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
6218 for (ImGuiWindow* window : g.Windows)
6219 {
6220 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
6221 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
6222 AddRootWindowToDrawData(window);
6223 }
6224 for (int n = 0; n < IM_COUNTOF(windows_to_render_top_most); n++)
6225 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
6226 AddRootWindowToDrawData(windows_to_render_top_most[n]);
6227
6228 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
6229 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
6230 RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
6231
6232 // Setup ImDrawData structures for end-user
6233 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
6234 for (ImGuiViewportP* viewport : g.Viewports)
6235 {
6236 FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
6237
6238 // Add foreground ImDrawList (for each active viewport)
6239 if (viewport->BgFgDrawLists[1] != NULL && viewport->BgFgDrawListsLastTimeActive[1] == (float)g.Time)
6240 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
6241
6242 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
6243 ImDrawData* draw_data = &viewport->DrawDataP;
6244 for (ImDrawList* draw_list : draw_data->CmdLists)
6245 draw_list->_PopUnusedDrawCmd();
6246#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6247 draw_data->CmdListsCount = draw_data->CmdLists.Size;
6248#endif
6249 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
6250 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
6251 }
6252
6253#ifndef IMGUI_DISABLE_DEBUG_TOOLS
6254 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
6255 for (ImFontAtlas* atlas : g.FontAtlases)
6256 ImFontAtlasDebugLogTextureRequests(atlas);
6257#endif
6258
6259 CallContextHooks(&g, ImGuiContextHookType_RenderPost);
6260}
6261
6262// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
6263// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
6264ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
6265{
6266 ImGuiContext& g = *GImGui;
6267
6268 const char* text_display_end;
6269 if (hide_text_after_double_hash)
6270 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
6271 else
6272 text_display_end = text_end;
6273
6274 ImFont* font = g.Font;
6275 const float font_size = g.FontSize;
6276 if (text == text_display_end)
6277 return ImVec2(0.0f, font_size);
6278 ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
6279
6280 // Round
6281 // (see 7b0bf230, 4622fa4b6, #791 for details about this.)
6282 // FIXME: Add a way to disable this.
6283 text_size.x = ImCeilFast(text_size.x);
6284
6285 return text_size;
6286}
6287
6288// Find window given position, search front-to-back
6289// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
6290// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
6291// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
6292// called, aka before the next Begin(). Moving window isn't affected.
6293// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
6294void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
6295{
6296 ImGuiContext& g = *GImGui;
6297 ImGuiWindow* hovered_window = NULL;
6298 ImGuiWindow* hovered_window_under_moving_window = NULL;
6299
6300 if (find_first_and_in_any_viewport == false && g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
6301 hovered_window = g.MovingWindow;
6302
6303 ImVec2 padding_regular = g.Style.TouchExtraPadding;
6304 ImVec2 padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding));
6305 for (int i = g.Windows.Size - 1; i >= 0; i--)
6306 {
6307 ImGuiWindow* window = g.Windows[i];
6308 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6309 if (!window->WasActive || window->Hidden)
6310 continue;
6311 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
6312 continue;
6313
6314 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
6315 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
6316 if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
6317 continue;
6318
6319 // Support for one rectangular hole in any given window
6320 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
6321 if (window->HitTestHoleSize.x != 0)
6322 {
6323 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
6324 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
6325 if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
6326 continue;
6327 }
6328
6329 if (find_first_and_in_any_viewport)
6330 {
6331 hovered_window = window;
6332 break;
6333 }
6334 else
6335 {
6336 if (hovered_window == NULL)
6337 hovered_window = window;
6338 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6339 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
6340 hovered_window_under_moving_window = window;
6341 if (hovered_window && hovered_window_under_moving_window)
6342 break;
6343 }
6344 }
6345
6346 *out_hovered_window = hovered_window;
6347 if (out_hovered_window_under_moving_window != NULL)
6348 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
6349}
6350
6351bool ImGui::IsItemActive()
6352{
6353 ImGuiContext& g = *GImGui;
6354 if (g.ActiveId)
6355 return g.ActiveId == g.LastItemData.ID;
6356 return false;
6357}
6358
6359bool ImGui::IsItemActivated()
6360{
6361 ImGuiContext& g = *GImGui;
6362 if (g.ActiveId)
6363 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
6364 return true;
6365 return false;
6366}
6367
6368bool ImGui::IsItemDeactivated()
6369{
6370 ImGuiContext& g = *GImGui;
6371 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
6372 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
6373 return g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount;
6374}
6375
6376// Since 1.92.9: consider using NoLiveEdit flags if all you need to that values are not written bo backing variable while typing.
6377bool ImGui::IsItemDeactivatedAfterEdit()
6378{
6379 ImGuiContext& g = *GImGui;
6380 return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore;
6381}
6382
6383// == (GetItemID() == GetFocusID() && GetFocusID() != 0)
6384bool ImGui::IsItemFocused()
6385{
6386 ImGuiContext& g = *GImGui;
6387 return g.NavId == g.LastItemData.ID && g.NavId != 0;
6388}
6389
6390// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
6391// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
6392bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
6393{
6394 return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
6395}
6396
6397bool ImGui::IsItemToggledOpen()
6398{
6399 ImGuiContext& g = *GImGui;
6400 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
6401}
6402
6403// Call after a Selectable() or TreeNode() items inside a BeginMultiSelect()/EndMultiSelect() scope.
6404// - Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
6405// Outside of a multi-select block:
6406// - It would be misleading/ambiguous to report this signal, as widgets return e.g. a pressed event,
6407// and user code is in charge of altering selection in ways we cannot predict.
6408// Prefer using 'if (IsItemClicked() && !IsItemToggledOpen())' for a manual reimplementation of selection.
6409bool ImGui::IsItemToggledSelection()
6410{
6411 ImGuiContext& g = *GImGui;
6412 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
6413 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
6414}
6415
6416// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
6417// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
6418// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
6419bool ImGui::IsAnyItemHovered()
6420{
6421 ImGuiContext& g = *GImGui;
6422 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
6423}
6424
6425bool ImGui::IsAnyItemActive()
6426{
6427 ImGuiContext& g = *GImGui;
6428 return g.ActiveId != 0;
6429}
6430
6431bool ImGui::IsAnyItemFocused()
6432{
6433 ImGuiContext& g = *GImGui;
6434 return g.NavId != 0 && g.NavCursorVisible;
6435}
6436
6437bool ImGui::IsItemVisible()
6438{
6439 ImGuiContext& g = *GImGui;
6440 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
6441}
6442
6443bool ImGui::IsItemEdited()
6444{
6445 ImGuiContext& g = *GImGui;
6446 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
6447}
6448
6449// Allow next item to be overlapped by subsequent items.
6450// This works by requiring HoveredId to match for two subsequent frames,
6451// so if a following items overwrite it our interactions will naturally be disabled.
6452void ImGui::SetNextItemAllowOverlap()
6453{
6454 ImGuiContext& g = *GImGui;
6455 g.NextItemData.ItemFlagsSet |= ImGuiItemFlags_AllowOverlap;
6456}
6457
6458#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6459// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
6460// Use SetNextItemAllowOverlap() *before* your item instead of calling this!
6461//void ImGui::SetItemAllowOverlap()
6462//{
6463// ImGuiContext& g = *GImGui;
6464// ImGuiID id = g.LastItemData.ID;
6465// if (g.HoveredId == id)
6466// g.HoveredIdAllowOverlap = true;
6467// if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
6468// g.ActiveIdAllowOverlap = true;
6469//}
6470#endif
6471
6472// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
6473// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
6474void ImGui::SetActiveIdUsingAllKeyboardKeys()
6475{
6476 ImGuiContext& g = *GImGui;
6477 IM_ASSERT(g.ActiveId != 0);
6478 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
6479 g.ActiveIdUsingAllKeyboardKeys = true;
6480 NavMoveRequestCancel();
6481}
6482
6483ImGuiID ImGui::GetItemID()
6484{
6485 ImGuiContext& g = *GImGui;
6486 return g.LastItemData.ID;
6487}
6488
6489ImVec2 ImGui::GetItemRectMin()
6490{
6491 ImGuiContext& g = *GImGui;
6492 return g.LastItemData.Rect.Min;
6493}
6494
6495ImVec2 ImGui::GetItemRectMax()
6496{
6497 ImGuiContext& g = *GImGui;
6498 return g.LastItemData.Rect.Max;
6499}
6500
6501ImVec2 ImGui::GetItemRectSize()
6502{
6503 ImGuiContext& g = *GImGui;
6504 return g.LastItemData.Rect.GetSize();
6505}
6506
6507ImGuiItemFlags ImGui::GetItemFlags()
6508{
6509 ImGuiContext& g = *GImGui;
6510 return g.LastItemData.ItemFlags;
6511}
6512
6513// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
6514// ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
6515bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6516{
6517 ImGuiID id = GetCurrentWindow()->GetID(str_id);
6518 return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
6519}
6520
6521bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6522{
6523 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
6524}
6525
6526bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6527{
6528 ImGuiContext& g = *GImGui;
6529 ImGuiWindow* parent_window = g.CurrentWindow;
6530 IM_ASSERT(id != 0);
6531
6532 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
6533 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
6534 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
6535 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
6536 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
6537 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
6538 {
6539 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6540 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6541 }
6542#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6543 //if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) { child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; }
6544 //if (window_flags & ImGuiWindowFlags_NavFlattened) { child_flags |= ImGuiChildFlags_NavFlattened; }
6545#endif
6546 if (child_flags & ImGuiChildFlags_AutoResizeX)
6547 child_flags &= ~ImGuiChildFlags_ResizeX;
6548 if (child_flags & ImGuiChildFlags_AutoResizeY)
6549 child_flags &= ~ImGuiChildFlags_ResizeY;
6550
6551 // Set window flags
6552 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar;
6553 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
6554 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
6555 window_flags |= ImGuiWindowFlags_AlwaysAutoResize; // FIXME: Would be sane to not make single-axis flag set this. (#9355)
6556 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
6557 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
6558
6559 // Special framed style
6560 if (child_flags & ImGuiChildFlags_FrameStyle)
6561 {
6562 PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
6563 PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
6564 PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
6565 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
6566 child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding;
6567 window_flags |= ImGuiWindowFlags_NoMove;
6568 }
6569
6570 // Forward size
6571 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
6572 // (the alternative would to store conditional flags per axis, which is possible but more code)
6573 const ImVec2 size_avail = GetContentRegionAvail();
6574 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
6575 ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
6576
6577 // A SetNextWindowSize() call always has priority (#8020)
6578 // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
6579 // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
6580 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
6581 {
6582 if (g.NextWindowData.SizeVal.x > 0.0f)
6583 {
6584 size.x = g.NextWindowData.SizeVal.x;
6585 child_flags &= ~ImGuiChildFlags_ResizeX;
6586 }
6587 if (g.NextWindowData.SizeVal.y > 0.0f)
6588 {
6589 size.y = g.NextWindowData.SizeVal.y;
6590 child_flags &= ~ImGuiChildFlags_ResizeY;
6591 }
6592 }
6593 SetNextWindowSize(size);
6594
6595 // Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
6596 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
6597 g.NextWindowData.ChildFlags |= child_flags;
6598 else
6599 g.NextWindowData.ChildFlags = child_flags;
6600 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
6601
6602 // 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.
6603 // 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.
6604 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
6605 const char* temp_window_name;
6606 /*if (name && parent_window->IDStack.back() == parent_window->ID)
6607 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
6608 else*/
6609 if (name)
6610 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
6611 else
6612 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
6613
6614 // Set style
6615 const float backup_border_size = g.Style.ChildBorderSize;
6616 if ((child_flags & ImGuiChildFlags_Borders) == 0)
6617 g.Style.ChildBorderSize = 0.0f;
6618
6619 // Begin into window
6620 const bool ret = Begin(temp_window_name, NULL, window_flags);
6621
6622 // Restore style
6623 g.Style.ChildBorderSize = backup_border_size;
6624 if (child_flags & ImGuiChildFlags_FrameStyle)
6625 {
6626 PopStyleVar(3);
6627 PopStyleColor();
6628 }
6629
6630 ImGuiWindow* child_window = g.CurrentWindow;
6631 child_window->ChildId = id;
6632
6633 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
6634 // While this is not really documented/defined, it seems that the expected thing to do.
6635 if (child_window->BeginCount == 1)
6636 parent_window->DC.CursorPos = child_window->Pos;
6637
6638 // Process navigation-in immediately so NavInit can run on first frame
6639 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
6640 const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
6641 if (g.ActiveId == temp_id_for_activation)
6642 ClearActiveID();
6643 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
6644 {
6645 FocusWindow(child_window);
6646 NavInitWindow(child_window, false);
6647 SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
6648 g.ActiveIdSource = g.NavInputSource;
6649 }
6650 return ret;
6651}
6652
6653void ImGui::EndChild()
6654{
6655 ImGuiContext& g = *GImGui;
6656 ImGuiWindow* child_window = g.CurrentWindow;
6657
6658 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
6659 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
6660
6661 g.WithinEndChildID = child_window->ID;
6662 ImVec2 child_size = child_window->Size;
6663 End();
6664 if (child_window->BeginCount == 1)
6665 {
6666 ImGuiWindow* parent_window = g.CurrentWindow;
6667 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
6668 ItemSize(child_size);
6669 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
6670 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
6671 {
6672 ItemAdd(bb, child_window->ChildId);
6673 RenderNavCursor(bb, child_window->ChildId);
6674
6675 // 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)
6676 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
6677 RenderNavCursor(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavRenderCursorFlags_Compact);
6678 }
6679 else
6680 {
6681 // Not navigable into
6682 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
6683 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
6684 ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
6685
6686 // But when flattened we directly reach items, adjust active layer mask accordingly
6687 if (nav_flattened)
6688 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6689 }
6690 if (g.HoveredWindow == child_window)
6691 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6692 child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags;
6693 //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd()
6694 }
6695 else
6696 {
6697 SetLastItemDataForChildWindowItem(child_window, child_window->Rect());
6698 }
6699
6700 g.WithinEndChildID = backup_within_end_child_id;
6701 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6702}
6703
6704ImGuiWindow* ImGui::FindFrontMostVisibleChildWindow(ImGuiWindow* window)
6705{
6706 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
6707 if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
6708 return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
6709 return window;
6710}
6711
6712static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6713{
6714 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
6715 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
6716 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6717}
6718
6719ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6720{
6721 ImGuiContext& g = *GImGui;
6722 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6723}
6724
6725ImGuiWindow* ImGui::FindWindowByName(const char* name)
6726{
6727 ImGuiID id = ImHashStr(name);
6728 return FindWindowByID(id);
6729}
6730
6731static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6732{
6733 if (settings != NULL)
6734 {
6735 window->Pos = ImTrunc(ImVec2(settings->Pos.x, settings->Pos.y));
6736 if (settings->Size.x > 0 && settings->Size.y > 0)
6737 {
6738 window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6739 window->AutoFitFramesX = window->AutoFitFramesY = 0;
6740 }
6741 window->Collapsed = settings->Collapsed;
6742 SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6743 }
6744
6745 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6746 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6747 {
6748 window->AutoFitFramesX = window->AutoFitFramesY = 2;
6749 window->AutoFitOnlyGrows = false;
6750 }
6751 else
6752 {
6753 window->AutoFitFramesX = (window->Size.x <= 0.0f) ? 2 : 0;
6754 window->AutoFitFramesY = (window->Size.y <= 0.0f) ? 2 : 0;
6755 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6756 }
6757}
6758
6759// Note that 'settings' may be NULL.
6760// Sets _Once, _Appearing, _FirstUseEver. _FirstUseEver will be cleared again if there are settings.
6761static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6762{
6763 // Initial window state with e.g. default/arbitrary window position
6764 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6765 ImGuiContext& g = *GImGui;
6766 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6767 window->Pos = main_viewport->Pos + ImVec2(60, 60);
6768 window->Size = window->SizeFull = ImVec2(0, 0);
6769 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6770 ApplyWindowSettings(window, settings);
6771 if (settings != NULL)
6772 settings->LastUsedDate = g.SessionDate;
6773}
6774
6775static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6776{
6777 // Create window the first time
6778 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6779 ImGuiContext& g = *GImGui;
6780 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6781 window->Flags = flags;
6782 g.WindowsById.SetVoidPtr(window->ID, window);
6783
6784 ImGuiWindowSettings* settings = NULL;
6785 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6786 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6787 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6788
6789 InitOrLoadWindowSettings(window, settings);
6790
6791 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6792 g.Windows.push_front(window); // Quite slow but rare and only once
6793 else
6794 g.Windows.push_back(window);
6795
6796 return window;
6797}
6798
6799static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6800{
6801 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6802 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6803 // Perhaps should tend further a neater test for this.
6804 ImGuiContext& g = *GImGui;
6805 ImVec2 size_min;
6806 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6807 {
6808 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : IMGUI_WINDOW_HARD_MIN_SIZE;
6809 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : IMGUI_WINDOW_HARD_MIN_SIZE;
6810 }
6811 else
6812 {
6813 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : IMGUI_WINDOW_HARD_MIN_SIZE;
6814 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : IMGUI_WINDOW_HARD_MIN_SIZE;
6815 }
6816
6817 // Reduce artifacts with very small windows
6818 ImGuiWindow* window_for_height = window;
6819 size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6820 return size_min;
6821}
6822
6823static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6824{
6825 ImGuiContext& g = *GImGui;
6826 ImVec2 new_size = size_desired;
6827 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6828 {
6829 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6830 ImRect cr = g.NextWindowData.SizeConstraintRect;
6831 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6832 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6833 if (g.NextWindowData.SizeCallback)
6834 {
6835 ImGuiSizeCallbackData data;
6836 data.UserData = g.NextWindowData.SizeCallbackUserData;
6837 data.Pos = window->Pos;
6838 data.CurrentSize = window->SizeFull;
6839 data.DesiredSize = new_size;
6840 g.NextWindowData.SizeCallback(&data);
6841 new_size = data.DesiredSize;
6842 }
6843 new_size.x = IM_TRUNC(new_size.x);
6844 new_size.y = IM_TRUNC(new_size.y);
6845 }
6846
6847 // Minimum size
6848 ImVec2 size_min = CalcWindowMinSize(window);
6849 return ImMax(new_size, size_min);
6850}
6851
6852static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6853{
6854 bool preserve_old_content_sizes = false;
6855 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6856 preserve_old_content_sizes = true;
6857 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6858 preserve_old_content_sizes = true;
6859 if (preserve_old_content_sizes)
6860 {
6861 *content_size_current = window->ContentSize;
6862 *content_size_ideal = window->ContentSizeIdeal;
6863 return;
6864 }
6865
6866 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6867 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6868 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6869 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6870}
6871
6872static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents, int axis_mask)
6873{
6874 ImGuiContext& g = *GImGui;
6875 ImGuiStyle& style = g.Style;
6876 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6877 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6878 ImVec2 size_pad = window->WindowPadding * 2.0f;
6879 ImVec2 size_desired;
6880 size_desired.x = (axis_mask & 1) ? size_contents.x + size_pad.x + decoration_w_without_scrollbars : window->Size.x;
6881 size_desired.y = (axis_mask & 2) ? size_contents.y + size_pad.y + decoration_h_without_scrollbars : window->Size.y;
6882
6883 // Determine maximum window size
6884 // Child windows are laid within their parent (unless they are also popups/menus) and thus have no restriction
6885 ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6886
6887 if (window->Flags & ImGuiWindowFlags_Tooltip)
6888 {
6889 // Tooltip always resize (up to maximum size)
6890 return ImMin(size_desired, size_max);
6891 }
6892 else
6893 {
6894 ImVec2 size_min = CalcWindowMinSize(window);
6895 ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max);
6896
6897 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6898 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6899 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6900 float size_contents_for_scrollbar_x = (axis_mask & 1) ? size_contents.x : window->ContentSize.x; // See #9352. In theory this should use same logic as `window->ScrollbarY = ...` codepath in Begin(). Needs some plumbling.
6901 float size_contents_for_scrollbar_y = (axis_mask & 2) ? size_contents.y : window->ContentSize.y;
6902 bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x < size_contents_for_scrollbar_x + size_pad.x + decoration_w_without_scrollbars && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6903 bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y < size_contents_for_scrollbar_y + size_pad.y + decoration_h_without_scrollbars && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6904 if (will_have_scrollbar_x)
6905 size_auto_fit.y += style.ScrollbarSize;
6906 if (will_have_scrollbar_y)
6907 size_auto_fit.x += style.ScrollbarSize;
6908 return size_auto_fit;
6909 }
6910}
6911
6912ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6913{
6914 ImVec2 size_contents_current;
6915 ImVec2 size_contents_ideal;
6916 CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6917 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal, ~0);
6918 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6919 return size_final;
6920}
6921
6922static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6923{
6924 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6925 return ImGuiCol_PopupBg;
6926 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6927 return ImGuiCol_ChildBg;
6928 return ImGuiCol_WindowBg;
6929}
6930
6931static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target_arg, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6932{
6933 ImVec2 corner_target = corner_target_arg;
6934 if (window->Flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6935 {
6936 ImGuiWindow* parent_window = window->ParentWindow;
6937 ImGuiWindowFlags parent_flags = parent_window->Flags;
6938 ImRect limit_rect = parent_window->InnerRect;
6939 limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6940 if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar))
6941 corner_target.x = ImClamp(corner_target.x, limit_rect.Min.x, limit_rect.Max.x);
6942 if (parent_flags & ImGuiWindowFlags_NoScrollbar)
6943 corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y);
6944 }
6945 ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
6946 ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6947 ImVec2 size_expected = pos_max - pos_min;
6948 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6949 *out_pos = pos_min;
6950 if (corner_norm.x == 0.0f)
6951 out_pos->x -= (size_constrained.x - size_expected.x);
6952 if (corner_norm.y == 0.0f)
6953 out_pos->y -= (size_constrained.y - size_expected.y);
6954 *out_size = size_constrained;
6955}
6956
6957// Data for resizing from resize grip / corner
6958struct ImGuiResizeGripDef
6959{
6960 ImVec2 CornerPosN;
6961 ImVec2 InnerDir;
6962 int AngleMin12, AngleMax12;
6963};
6964static const ImGuiResizeGripDef resize_grip_def[4] =
6965{
6966 { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
6967 { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
6968 { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
6969 { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
6970};
6971
6972// Data for resizing from borders
6973struct ImGuiResizeBorderDef
6974{
6975 ImVec2 InnerDir; // Normal toward inside
6976 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6977 float OuterAngle; // Angle toward outside
6978};
6979static const ImGuiResizeBorderDef resize_border_def[4] =
6980{
6981 { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6982 { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6983 { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6984 { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
6985};
6986
6987static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6988{
6989 ImRect rect = window->Rect();
6990 if (thickness == 0.0f)
6991 rect.Max -= ImVec2(1, 1);
6992 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); }
6993 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); }
6994 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); }
6995 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); }
6996 IM_ASSERT(0);
6997 return ImRect();
6998}
6999
7000// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
7001ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
7002{
7003 IM_ASSERT(n >= 0 && n < 4);
7004 ImGuiID id = window->ID;
7005 id = ImHashStr("#RESIZE", 0, id);
7006 id = ImHashData(&n, sizeof(int), id);
7007 return id;
7008}
7009
7010// Borders (Left, Right, Up, Down)
7011ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
7012{
7013 IM_ASSERT(dir >= 0 && dir < 4);
7014 int n = (int)dir + 4;
7015 ImGuiID id = window->ID;
7016 id = ImHashStr("#RESIZE", 0, id);
7017 id = ImHashData(&n, sizeof(int), id);
7018 return id;
7019}
7020
7021// Handle resize for: Resize Grips, Borders, Gamepad
7022// Return true when using auto-fit (double-click on resize grip)
7023static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
7024{
7025 ImGuiContext& g = *GImGui;
7026 ImGuiWindowFlags flags = window->Flags;
7027
7028 if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7029 return false;
7030 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
7031 return false;
7032 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
7033 return false;
7034
7035 int ret_auto_fit_mask = 0x00;
7036 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7037 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
7038 const float grip_hover_outer_size = g.WindowsBorderHoverPadding;
7039
7040 ImRect clamp_rect = visibility_rect;
7041 const bool window_move_from_title_bar = !(window->BgClickFlags & ImGuiWindowBgClickFlags_Move) && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
7042 if (window_move_from_title_bar)
7043 clamp_rect.Min.y -= window->TitleBarHeight;
7044
7045 ImVec2 pos_target(FLT_MAX, FLT_MAX);
7046 ImVec2 size_target(FLT_MAX, FLT_MAX);
7047
7048 // Resize grips and borders are on layer 1
7049 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7050
7051 // Manual resize grips
7052 PushID("#RESIZE");
7053 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7054 {
7055 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
7056 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
7057
7058 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
7059 bool hovered, held;
7060 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
7061 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
7062 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
7063 ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
7064 ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
7065 ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7066 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
7067 if (hovered || held)
7068 SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
7069
7070 if (held && g.IO.MouseDoubleClicked[0])
7071 {
7072 // Auto-fit when double-clicking
7073 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0);
7074 size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
7075 ret_auto_fit_mask = 0x03; // Both axes
7076 ClearActiveID();
7077 }
7078 else if (held)
7079 {
7080 // Resize from any of the four corners
7081 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
7082 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);
7083 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);
7084 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
7085 corner_target = ImClamp(corner_target, clamp_min, clamp_max);
7086 CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
7087 }
7088
7089 // Only lower-left grip is visible before hovering/activating
7090 const bool resize_grip_visible = held || hovered || (resize_grip_n == 0 && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
7091 if (resize_grip_visible)
7092 resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
7093 }
7094
7095 int resize_border_mask = 0x00;
7096 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7097 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
7098 else
7099 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
7100 for (int border_n = 0; border_n < 4; border_n++)
7101 {
7102 if ((resize_border_mask & (1 << border_n)) == 0)
7103 continue;
7104 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7105 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
7106
7107 bool hovered, held;
7108 ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding);
7109 ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
7110 ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
7111 ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7112 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
7113 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
7114 hovered = false;
7115 if (hovered || held)
7116 SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
7117 if (held && g.IO.MouseDoubleClicked[0])
7118 {
7119 // Double-clicking bottom or right border auto-fit on this axis
7120 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
7121 if (border_n == 1 || border_n == 3) // Right and bottom border
7122 {
7123 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, 1 << axis);
7124 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
7125 ret_auto_fit_mask |= (1 << axis);
7126 hovered = held = false; // So border doesn't show highlighted at new position
7127 }
7128 ClearActiveID();
7129 }
7130 else if (held)
7131 {
7132 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
7133 // 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.
7134 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
7135 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false));
7136 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
7137 {
7138 g.WindowResizeBorderExpectedRect = border_rect;
7139 g.WindowResizeRelativeMode = false;
7140 }
7141 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
7142 g.WindowResizeRelativeMode = true;
7143
7144 const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
7145 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
7146 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above.
7147
7148 // Use absolute mode position
7149 ImVec2 border_target = window->Pos;
7150 border_target[axis] = border_target_abs_mode_for_axis;
7151
7152 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
7153 bool ignore_resize = false;
7154 if (g.WindowResizeRelativeMode)
7155 {
7156 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
7157 border_target[axis] = border_target_rel_mode_for_axis;
7158 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))
7159 ignore_resize = true;
7160 }
7161
7162 // Clamp, apply
7163 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);
7164 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
7165 border_target = ImClamp(border_target, clamp_min, clamp_max);
7166 if (!ignore_resize)
7167 CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
7168 }
7169 if (hovered)
7170 *border_hovered = border_n;
7171 if (held)
7172 *border_held = border_n;
7173 }
7174 PopID();
7175
7176 // Restore nav layer
7177 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7178
7179 // Navigation resize (keyboard/gamepad)
7180 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
7181 // Not even sure the callback works here.
7182 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
7183 {
7184 ImVec2 nav_resize_dir;
7185 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
7186 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
7187 if (g.NavInputSource == ImGuiInputSource_Gamepad)
7188 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
7189 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
7190 {
7191 const float NAV_RESIZE_SPEED = 600.0f;
7192 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * GetScale();
7193 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
7194 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
7195 g.NavWindowingToggleLayer = false;
7196 g.NavHighlightItemUnderNav = true;
7197 resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
7198 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
7199 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
7200 {
7201 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
7202 size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
7203 g.NavWindowingAccumDeltaSize -= accum_floored;
7204 }
7205 }
7206 }
7207
7208 // Apply back modified position/size to window
7209 const ImVec2 old_pos = window->Pos;
7210 const ImVec2 old_size = window->SizeFull;
7211 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
7212 window->Size.x = window->SizeFull.x = size_target.x;
7213 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
7214 window->Size.y = window->SizeFull.y = size_target.y;
7215 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
7216 window->Pos.x = ImTrunc(pos_target.x);
7217 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
7218 window->Pos.y = ImTrunc(pos_target.y);
7219 if (old_pos.x != window->Pos.x || old_pos.y != window->Pos.y || old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7220 MarkIniSettingsDirty(window);
7221
7222 // Recalculate next expected border expected coordinates
7223 if (*border_held != -1)
7224 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding);
7225
7226 return ret_auto_fit_mask;
7227}
7228
7229static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
7230{
7231 ImVec2 size_for_clamping = window->Size;
7232 if (!(window->BgClickFlags & ImGuiWindowBgClickFlags_Move) && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7233 size_for_clamping.y = window->TitleBarHeight;
7234 window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
7235}
7236
7237static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
7238{
7239 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7240 const float rounding = window->WindowRounding;
7241 const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
7242 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);
7243 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);
7244 window->DrawList->PathStroke(border_col, border_size);
7245}
7246
7247static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
7248{
7249 ImGuiContext& g = *GImGui;
7250 const float border_size = window->WindowBorderSize;
7251 const ImU32 border_col = GetColorU32(ImGuiCol_Border);
7252 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
7253 window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, window->WindowBorderSize);
7254 else if (border_size > 0.0f)
7255 {
7256 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
7257 RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
7258 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
7259 RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
7260 }
7261 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
7262 {
7263 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
7264 const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
7265 RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
7266 }
7267 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7268 {
7269 float y = window->Pos.y + window->TitleBarHeight - 1;
7270 window->DrawList->AddLineH(window->Pos.x + border_size * 0.5f, window->Pos.x + window->Size.x - border_size * 0.5f, y, border_col, g.Style.FrameBorderSize);
7271 }
7272}
7273
7274// Draw background and borders
7275// Draw and handle scrollbars
7276void 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)
7277{
7278 ImGuiContext& g = *GImGui;
7279 ImGuiStyle& style = g.Style;
7280 ImGuiWindowFlags flags = window->Flags;
7281
7282 // Ensure that Scrollbar() doesn't read last frame's SkipItems
7283 IM_ASSERT(window->BeginCount == 0);
7284 window->SkipItems = false;
7285 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7286
7287 // Draw window + handle manual resize
7288 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
7289 const float window_rounding = window->WindowRounding;
7290 const float window_border_size = window->WindowBorderSize;
7291 if (window->Collapsed)
7292 {
7293 // Title bar only
7294 const float backup_border_size = style.FrameBorderSize;
7295 g.Style.FrameBorderSize = window->WindowBorderSize;
7296 ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
7297 RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
7298 g.Style.FrameBorderSize = backup_border_size;
7299 }
7300 else
7301 {
7302 // Window background
7303 if (!(flags & ImGuiWindowFlags_NoBackground))
7304 {
7305 ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
7306 bool override_alpha = false;
7307 float alpha = 1.0f;
7308 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha)
7309 {
7310 alpha = g.NextWindowData.BgAlphaVal;
7311 override_alpha = true;
7312 }
7313 if (override_alpha)
7314 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
7315 if (bg_col & IM_COL32_A_MASK)
7316 {
7317 ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size);
7318 ImDrawFlags bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersBottom;
7319 ImDrawList* bg_draw_list = window->DrawList;
7320 bg_draw_list->AddRectFilled(bg_rect.Min, bg_rect.Max, bg_col, window_rounding, bg_rounding_flags);
7321 }
7322 }
7323
7324 // Title bar
7325 if (!(flags & ImGuiWindowFlags_NoTitleBar))
7326 {
7327 ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
7328 window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
7329 }
7330
7331 // Menu bar
7332 if (flags & ImGuiWindowFlags_MenuBar)
7333 {
7334 ImRect menu_bar_rect = window->MenuBarRect();
7335 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.
7336 window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
7337 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
7338 window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5f, menu_bar_rect.Max.x - window_border_size * 0.5f, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
7339 }
7340
7341 // Scrollbars
7342 if (window->ScrollbarX)
7343 Scrollbar(ImGuiAxis_X);
7344 if (window->ScrollbarY)
7345 Scrollbar(ImGuiAxis_Y);
7346
7347 // Render resize grips (after their input handling so we don't have a frame of latency)
7348 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
7349 {
7350 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7351 {
7352 const ImU32 col = resize_grip_col[resize_grip_n];
7353 if ((col & IM_COL32_A_MASK) == 0)
7354 continue;
7355 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
7356 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
7357 const float border_inner = IM_ROUND(window_border_size * 0.5f);
7358 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner)));
7359 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size)));
7360 window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12);
7361 window->DrawList->PathFillConvex(col);
7362 }
7363 }
7364
7365 // Borders
7366 if (handle_borders_and_resize_grips)
7367 RenderWindowOuterBorders(window);
7368 }
7369 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7370}
7371
7372// Render title text, collapse button, close button
7373void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
7374{
7375 ImGuiContext& g = *GImGui;
7376 ImGuiStyle& style = g.Style;
7377 ImGuiWindowFlags flags = window->Flags;
7378
7379 const bool has_close_button = (p_open != NULL);
7380 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
7381
7382 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
7383 // 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?
7384 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
7385 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
7386 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7387
7388 // Layout buttons
7389 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
7390 float pad_l = style.FramePadding.x;
7391 float pad_r = style.FramePadding.x;
7392 float button_sz = g.FontSize;
7393 ImVec2 close_button_pos;
7394 ImVec2 collapse_button_pos;
7395 if (has_close_button)
7396 {
7397 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7398 pad_r += button_sz + style.ItemInnerSpacing.x;
7399 }
7400 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
7401 {
7402 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7403 pad_r += button_sz + style.ItemInnerSpacing.x;
7404 }
7405 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
7406 {
7407 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
7408 pad_l += button_sz + style.ItemInnerSpacing.x;
7409 }
7410
7411 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
7412 if (has_collapse_button)
7413 if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
7414 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
7415
7416 // Close button
7417 if (has_close_button)
7418 {
7419 ImGuiItemFlags backup_item_flags = g.CurrentItemFlags;
7420 g.CurrentItemFlags |= ImGuiItemFlags_NoFocus;
7421 if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
7422 *p_open = false;
7423 g.CurrentItemFlags = backup_item_flags;
7424 }
7425
7426 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7427 g.CurrentItemFlags = item_flags_backup;
7428
7429 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
7430 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
7431 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
7432 const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
7433
7434 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
7435 // while uncentered title text will still reach edges correctly.
7436 if (pad_l > style.FramePadding.x)
7437 pad_l += g.Style.ItemInnerSpacing.x;
7438 if (pad_r > style.FramePadding.x)
7439 pad_r += g.Style.ItemInnerSpacing.x;
7440 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
7441 {
7442 float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
7443 float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
7444 pad_l = ImMax(pad_l, pad_extend * centerness);
7445 pad_r = ImMax(pad_r, pad_extend * centerness);
7446 }
7447
7448 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);
7449 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);
7450 if (flags & ImGuiWindowFlags_UnsavedDocument)
7451 {
7452 ImVec2 marker_pos;
7453 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);
7454 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
7455 if (marker_pos.x > layout_r.Min.x)
7456 {
7457 RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_UnsavedMarker));
7458 clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
7459 }
7460 }
7461 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7462 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7463 RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
7464}
7465
7466void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
7467{
7468 window->ParentWindow = parent_window;
7469 window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
7470 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
7471 window->RootWindow = parent_window->RootWindow;
7472 if (parent_window && (flags & ImGuiWindowFlags_Popup))
7473 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
7474 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)))
7475 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
7476 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
7477 {
7478 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
7479 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
7480 }
7481}
7482
7483// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
7484// This is designed as a toy/test-bed for
7485void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
7486{
7487 ImGuiContext& g = *GImGui;
7488 window->SkipRefresh = false;
7489 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
7490 return;
7491 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
7492 {
7493 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
7494 if (window->Appearing) // If currently appearing
7495 return;
7496 if (window->Hidden) // If was hidden (previous frame)
7497 return;
7498 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow)
7499 if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, window))
7500 return;
7501 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow)
7502 if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(g.NavWindow->RootWindow, window))
7503 return;
7504 window->DrawList = NULL;
7505 window->SkipRefresh = true;
7506 }
7507}
7508
7509static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
7510{
7511 window->Active = true;
7512 for (ImGuiWindow* child : window->DC.ChildWindows)
7513 if (!child->Hidden)
7514 {
7515 child->Active = child->SkipRefresh = true;
7516 SetWindowActiveForSkipRefresh(child);
7517 }
7518}
7519
7520// Push a new Dear ImGui window to add widgets to.
7521// - 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.
7522// - Begin/End can be called multiple times during the frame with the same window name to append content.
7523// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
7524// 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.
7525// - 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.
7526// - 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.
7527bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
7528{
7529 ImGuiContext& g = *GImGui;
7530 const ImGuiStyle& style = g.Style;
7531 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
7532 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
7533 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
7534
7535 // Find or create
7536 ImGuiWindow* window = FindWindowByName(name);
7537 const bool window_just_created = (window == NULL);
7538 if (window_just_created)
7539 window = CreateNewWindow(name, flags);
7540
7541 // [DEBUG] Debug break requested by user
7542 if (g.DebugBreakInWindow == window->ID)
7543 IM_DEBUG_BREAK();
7544
7545 // Automatically disable manual moving/resizing when NoInputs is set
7546 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
7547 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
7548
7549 const int current_frame = g.FrameCount;
7550 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
7551 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
7552
7553 // Update the Appearing flag
7554 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
7555 if (flags & ImGuiWindowFlags_Popup)
7556 {
7557 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7558 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
7559 window_just_activated_by_user |= (window != popup_ref.Window);
7560 }
7561 window->Appearing = window_just_activated_by_user;
7562 if (window->Appearing)
7563 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7564
7565 // Update Flags, LastFrameActive, BeginOrderXXX fields
7566 if (first_begin_of_the_frame)
7567 {
7568 UpdateWindowInFocusOrderList(window, window_just_created, flags);
7569 window->Flags = (ImGuiWindowFlags)flags;
7570 window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7571 window->LastFrameActive = current_frame;
7572 window->LastTimeActive = (float)g.Time;
7573 window->BeginOrderWithinParent = 0;
7574 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7575 }
7576 else
7577 {
7578 flags = window->Flags;
7579 }
7580
7581 // 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
7582 ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7583 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7584 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7585
7586 // We allow window memory to be compacted so recreate the base stack when needed.
7587 if (window->IDStack.Size == 0)
7588 window->IDStack.push_back(window->ID);
7589
7590 // Add to stack
7591 g.CurrentWindow = window;
7592 g.CurrentWindowStack.resize(g.CurrentWindowStack.Size + 1);
7593 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7594 window_stack_data.Window = window;
7595 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7596 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7597 window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f;
7598 ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin);
7599 g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
7600 if (flags & ImGuiWindowFlags_ChildMenu)
7601 g.BeginMenuDepth++;
7602
7603 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7604 if (first_begin_of_the_frame)
7605 {
7606 UpdateWindowParentAndRootLinks(window, flags, parent_window);
7607 window->ParentWindowInBeginStack = parent_window_in_stack;
7608
7609 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7610 // e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7611 window->ParentWindowForFocusRoute = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window_in_stack : NULL;
7612
7613 // Inherent SetWindowFontScale() from parent until we fix this system...
7614 window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f;
7615 }
7616
7617 // Add to focus scope stack
7618 PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7619 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7620
7621 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7622 if (flags & ImGuiWindowFlags_Popup)
7623 {
7624 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7625 popup_ref.Window = window;
7626 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7627 g.BeginPopupStack.push_back(popup_ref);
7628 window->PopupId = popup_ref.PopupId;
7629 }
7630
7631 // Process SetNextWindow***() calls
7632 // (FIXME: Consider splitting the HasXXX flags into X/Y components)
7633 bool window_pos_set_by_api = false;
7634 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7635 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos)
7636 {
7637 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7638 if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7639 {
7640 // May be processed on the next frame if this is our first frame and we are measuring size
7641 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7642 window->SetWindowPosVal = g.NextWindowData.PosVal;
7643 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7644 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7645 }
7646 else
7647 {
7648 SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7649 }
7650 }
7651 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize)
7652 {
7653 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7654 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7655 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7656 g.NextWindowData.SizeVal.x = window->SizeFull.x;
7657 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7658 g.NextWindowData.SizeVal.y = window->SizeFull.y;
7659 SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7660 }
7661 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll)
7662 {
7663 if (g.NextWindowData.ScrollVal.x >= 0.0f)
7664 {
7665 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7666 window->ScrollTargetCenterRatio.x = 0.0f;
7667 }
7668 if (g.NextWindowData.ScrollVal.y >= 0.0f)
7669 {
7670 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7671 window->ScrollTargetCenterRatio.y = 0.0f;
7672 }
7673 }
7674 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize)
7675 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7676 else if (first_begin_of_the_frame)
7677 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7678 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed)
7679 SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7680 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus)
7681 FocusWindow(window);
7682 if (window->Appearing)
7683 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7684
7685 // [EXPERIMENTAL] Skip Refresh mode
7686 UpdateWindowSkipRefresh(window);
7687
7688 // Nested root windows (typically tooltips) override disabled state
7689 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7690 BeginDisabledOverrideReenable();
7691
7692 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7693 g.CurrentWindow = NULL;
7694
7695 // When reusing window again multiple times a frame, just append content (don't need to setup again)
7696 if (first_begin_of_the_frame && !window->SkipRefresh)
7697 {
7698 // Initialize
7699 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7700 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7701 window->Active = true;
7702 window->HasCloseButton = (p_open != NULL);
7703 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7704 window->IDStack.resize(1);
7705 window->DrawList->_ResetForNewFrame();
7706 window->DC.CurrentTableIdx = -1;
7707
7708 // Restore buffer capacity when woken from a compacted state, to avoid
7709 if (window->MemoryCompacted)
7710 GcAwakeTransientWindowBuffers(window);
7711
7712 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7713 // 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.
7714 bool window_title_visible_elsewhere = false;
7715 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->WasActive && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using Ctrl+Tab
7716 window_title_visible_elsewhere = true;
7717 if (flags & ImGuiWindowFlags_ChildMenu)
7718 window_title_visible_elsewhere = true;
7719 if ((window_title_visible_elsewhere || window_just_activated_by_user) && !window_just_created && strcmp(name, window->Name) != 0)
7720 {
7721 size_t buf_len = (size_t)window->NameBufLen;
7722 window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7723 window->NameBufLen = (int)buf_len;
7724 }
7725
7726 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7727
7728 // Update contents size from last frame for auto-fitting (or use explicit size)
7729 CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7730 if (window->HiddenFramesCanSkipItems > 0)
7731 window->HiddenFramesCanSkipItems--;
7732 if (window->HiddenFramesCannotSkipItems > 0)
7733 window->HiddenFramesCannotSkipItems--;
7734 if (window->HiddenFramesForRenderOnly > 0)
7735 window->HiddenFramesForRenderOnly--;
7736
7737 // Hide new windows for one frame until they calculate their size
7738 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7739 window->HiddenFramesCannotSkipItems = 1;
7740
7741 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7742 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7743 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7744 {
7745 window->HiddenFramesCannotSkipItems = 1;
7746 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7747 {
7748 if (!window_size_x_set_by_api)
7749 window->Size.x = window->SizeFull.x = 0.f;
7750 if (!window_size_y_set_by_api)
7751 window->Size.y = window->SizeFull.y = 0.f;
7752 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7753 }
7754 }
7755
7756 // SELECT VIEWPORT
7757 // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
7758
7759 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
7760 SetWindowViewport(window, viewport);
7761 SetCurrentWindow(window);
7762
7763 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7764
7765 if (flags & ImGuiWindowFlags_ChildWindow)
7766 window->WindowBorderSize = style.ChildBorderSize;
7767 else
7768 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7769 window->WindowPadding = style.WindowPadding;
7770 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7771 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7772
7773 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7774 window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7775 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7776 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7777 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7778 window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window.
7779
7780 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7781 // Those flags will be altered further down in the function depending on more conditions.
7782 bool use_current_size_for_scrollbar_x = window_just_created;
7783 bool use_current_size_for_scrollbar_y = window_just_created;
7784 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7785 use_current_size_for_scrollbar_x = true;
7786 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7787 use_current_size_for_scrollbar_y = true;
7788
7789 // Collapse window by double-clicking on title bar
7790 // 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
7791 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
7792 {
7793 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
7794 // so verify that we don't have items over the title bar.
7795 ImRect title_bar_rect = window->TitleBarRect();
7796 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7797 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7798 {
7799 window->WantCollapseToggle = true;
7800 SetKeyOwner(ImGuiKey_MouseLeft, window->MoveId); // Claim input the same way ButtonBehavior() does. Prevent a same-frame move from triggering other items. (#9439)
7801 }
7802 if (window->WantCollapseToggle)
7803 {
7804 window->Collapsed = !window->Collapsed;
7805 if (!window->Collapsed)
7806 use_current_size_for_scrollbar_y = true;
7807 MarkIniSettingsDirty(window);
7808 }
7809 }
7810 else
7811 {
7812 window->Collapsed = false;
7813 }
7814 window->WantCollapseToggle = false;
7815
7816 // SIZE
7817
7818 // Outer Decoration Sizes
7819 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7820 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7821 window->DecoOuterSizeX1 = 0.0f;
7822 window->DecoOuterSizeX2 = 0.0f;
7823 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7824 window->DecoOuterSizeY2 = 0.0f;
7825 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7826
7827 // Calculate auto-fit size, handle automatic resize
7828 // - Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7829 // - We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7830 // - Auto-fit may only grow window during the first few frames.
7831 {
7832 const bool size_auto_fit_x_always = !window_size_x_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed;
7833 const bool size_auto_fit_y_always = !window_size_y_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed;
7834 const bool size_auto_fit_x_current = !window_size_x_set_by_api && (window->AutoFitFramesX > 0);
7835 const bool size_auto_fit_y_current = !window_size_y_set_by_api && (window->AutoFitFramesY > 0);
7836 int size_auto_fit_mask = 0;
7837 if (size_auto_fit_x_always || size_auto_fit_x_current)
7838 size_auto_fit_mask |= (1 << ImGuiAxis_X);
7839 if (size_auto_fit_y_always || size_auto_fit_y_current)
7840 size_auto_fit_mask |= (1 << ImGuiAxis_Y);
7841 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, size_auto_fit_mask);
7842
7843 const ImVec2 old_size = window->SizeFull;
7844 if (size_auto_fit_x_always || size_auto_fit_x_current)
7845 {
7846 if (size_auto_fit_x_always)
7847 window->SizeFull.x = size_auto_fit.x;
7848 else
7849 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7850 use_current_size_for_scrollbar_x = true;
7851 }
7852 if (size_auto_fit_y_always || size_auto_fit_y_current)
7853 {
7854 if (size_auto_fit_y_always)
7855 window->SizeFull.y = size_auto_fit.y;
7856 else
7857 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7858 use_current_size_for_scrollbar_y = true;
7859 }
7860 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7861 MarkIniSettingsDirty(window);
7862 }
7863
7864 // Apply minimum/maximum window size constraints and final size
7865 window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7866 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7867
7868 // POSITION
7869
7870 // Popup latch its initial position, will position itself when it appears next frame
7871 if (window_just_activated_by_user)
7872 {
7873 window->AutoPosLastDirection = ImGuiDir_None;
7874 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7875 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7876 }
7877
7878 // Position child window
7879 if (flags & ImGuiWindowFlags_ChildWindow)
7880 {
7881 IM_ASSERT(parent_window && parent_window->Active);
7882 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7883 parent_window->DC.ChildWindows.push_back(window);
7884 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7885 window->Pos = parent_window->DC.CursorPos;
7886 }
7887
7888 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7889 if (window_pos_with_pivot)
7890 SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7891 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7892 window->Pos = FindBestWindowPosForPopup(window);
7893 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7894 window->Pos = FindBestWindowPosForPopup(window);
7895 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7896 window->Pos = FindBestWindowPosForPopup(window);
7897
7898 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7899 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7900 ImRect viewport_rect(viewport->GetMainRect());
7901 ImRect viewport_work_rect(viewport->GetWorkRect());
7902 ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7903 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7904
7905 // Clamp position/size so window stays visible within its viewport or monitor
7906 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7907 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7908 if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
7909 ClampWindowPos(window, visibility_rect);
7910 window->Pos = ImTrunc(window->Pos);
7911
7912 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7913 // Large values tend to lead to variety of artifacts and are not recommended.
7914 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7915
7916 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7917 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7918 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7919
7920 // Apply window focus (new and reactivated windows are moved to front)
7921 bool want_focus = false;
7922 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7923 {
7924 if (flags & ImGuiWindowFlags_Popup)
7925 want_focus = true;
7926 else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
7927 want_focus = true;
7928 }
7929
7930 // [Test Engine] Register whole window in the item system (before submitting further decorations)
7931#ifdef IMGUI_ENABLE_TEST_ENGINE
7932 if (g.TestEngineHookItems)
7933 {
7934 IM_ASSERT(window->IDStack.Size == 1);
7935 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7936 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7937 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7938 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7939 window->IDStack.Size = 1;
7940 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7941
7942 }
7943#endif
7944
7945 // Decide if we are going to handle borders and resize grips
7946 // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815)
7947 // Whenever we add support for full decorated child windows we will likely make this logic more general.
7948 bool handle_borders_and_resize_grips = true;
7949 if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems)
7950 handle_borders_and_resize_grips = false;
7951
7952 // Handle manual resize: Resize Grips, Borders, Gamepad
7953 // Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set.
7954 int border_hovered = -1, border_held = -1;
7955 ImU32 resize_grip_col[4] = {};
7956 int resize_grip_count;
7957 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
7958 resize_grip_count = ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) ? 1 : 0;
7959 else
7960 resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7961
7962 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7963 if (handle_borders_and_resize_grips && !window->Collapsed)
7964 if (int auto_fit_mask = UpdateWindowManualResize(window, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7965 {
7966 if (auto_fit_mask & (1 << ImGuiAxis_X))
7967 use_current_size_for_scrollbar_x = true;
7968 if (auto_fit_mask & (1 << ImGuiAxis_Y))
7969 use_current_size_for_scrollbar_y = true;
7970 }
7971 window->ResizeBorderHovered = (signed char)border_hovered;
7972 window->ResizeBorderHeld = (signed char)border_held;
7973
7974 // SCROLLBAR VISIBILITY
7975
7976 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7977 if (!window->Collapsed)
7978 {
7979 // When reading the current size we need to read it after size constraints have been applied.
7980 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7981 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7982 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7983 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7984 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7985 float size_for_scrollbars_x = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7986 float size_for_scrollbars_y = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7987 bool scrollbar_x_prev = window->ScrollbarX;
7988 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7989 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_for_scrollbars_y) && !(flags & ImGuiWindowFlags_NoScrollbar));
7990 window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_for_scrollbars_x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7991
7992 // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
7993 // (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause.
7994 // The better solution is to, either (1) enforce visibility by using ImGuiWindowFlags_AlwaysHorizontalScrollbar or (2) declare stable contents width with SetNextWindowContentSize(), if you can compute it)
7995 window->ScrollbarXStabilizeToggledHistory <<= 1;
7996 window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00;
7997 const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history.
7998 if (scrollbar_x_stabilize)
7999 window->ScrollbarX = true;
8000 //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled)
8001 // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name);
8002 window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize;
8003
8004 if (window->ScrollbarX && !window->ScrollbarY)
8005 window->ScrollbarY = (needed_size_from_last_frame.y > size_for_scrollbars_y - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
8006 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
8007
8008 // Amend the partially filled window->DecorationXXX values.
8009 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
8010 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
8011 }
8012
8013 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
8014 // Update various regions. Variables they depend on should be set above in this function.
8015 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
8016
8017 // Outer rectangle
8018 // Not affected by window border size. Used by:
8019 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
8020 // - Begin() initial clipping rect for drawing window background and borders.
8021 // - Begin() clipping whole child
8022 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
8023 const ImRect outer_rect = window->Rect();
8024 const ImRect title_bar_rect = window->TitleBarRect();
8025 window->OuterRectClipped = outer_rect;
8026 window->OuterRectClipped.ClipWith(host_rect);
8027
8028 // Inner rectangle
8029 // Not affected by window border size. Used by:
8030 // - InnerClipRect
8031 // - ScrollToRectEx()
8032 // - NavUpdatePageUpPageDown()
8033 // - Scrollbar()
8034 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
8035 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
8036 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
8037 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
8038
8039 // Inner clipping rectangle.
8040 // - Extend a outside of normal work region up to borders.
8041 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
8042 // - It also makes clipped items be more noticeable.
8043 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
8044 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
8045 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
8046 // Affected by window/frame border size. Used by:
8047 // - Begin() initial clip rect
8048 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
8049
8050 // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner.
8051 // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize,
8052 // 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).
8053 window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f);
8054 window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size * 0.5f);
8055 window->InnerClipRect.Max.x = ImFloor(window->InnerRect.Max.x - window->WindowBorderSize * 0.5f);
8056 window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
8057 window->InnerClipRect.ClipWithFull(host_rect);
8058
8059 // SCROLLING
8060
8061 // Lock down maximum scrolling
8062 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
8063 // for right/bottom aligned items without creating a scrollbar.
8064 window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
8065 window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
8066
8067 // Apply scrolling
8068 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
8069 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
8070 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
8071
8072 // DRAWING
8073
8074 // Setup draw list and outer clipping rectangle
8075 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
8076 window->DrawList->PushTexture(g.Font->OwnerAtlas->TexRef);
8077 PushClipRect(host_rect.Min, host_rect.Max, false);
8078
8079 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
8080 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
8081 // 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)
8082 {
8083 bool render_decorations_in_parent = false;
8084 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
8085 {
8086 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
8087 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
8088 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
8089 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
8090 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
8091 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
8092 render_decorations_in_parent = true;
8093 }
8094 if (render_decorations_in_parent)
8095 window->DrawList = parent_window->DrawList;
8096
8097 // Handle title bar, scrollbar, resize grips and resize borders
8098 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
8099 const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
8100 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
8101
8102 if (render_decorations_in_parent)
8103 window->DrawList = &window->DrawListInst;
8104 }
8105
8106 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
8107
8108 // Work rectangle.
8109 // Affected by window padding and border size. Used by:
8110 // - Columns() for right-most edge
8111 // - TreeNode(), CollapsingHeader() for right-most edge
8112 // - BeginTabBar() for right-most edge
8113 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
8114 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
8115 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)));
8116 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)));
8117 window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
8118 window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
8119 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
8120 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
8121 window->ParentWorkRect = window->WorkRect;
8122
8123 // [LEGACY] Content Region
8124 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
8125 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
8126 // Used by:
8127 // - Mouse wheel scrolling + many other things
8128 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
8129 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
8130 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)));
8131 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)));
8132
8133 // Setup drawing context
8134 // (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.)
8135 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
8136 window->DC.GroupOffset.x = 0.0f;
8137 window->DC.ColumnsOffset.x = 0.0f;
8138
8139 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
8140 // 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.
8141 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
8142 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
8143 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
8144 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
8145 window->DC.CursorPos = window->DC.CursorStartPos;
8146 window->DC.CursorPosPrevLine = window->DC.CursorPos;
8147 window->DC.CursorMaxPos = window->DC.CursorStartPos;
8148 window->DC.IdealMaxPos = window->DC.CursorStartPos;
8149 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
8150 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
8151 window->DC.IsSameLine = window->DC.IsSetPos = false;
8152
8153 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8154 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
8155 window->DC.NavLayersActiveMaskNext = 0x00;
8156 window->DC.NavIsScrollPushableX = true;
8157 window->DC.NavHideHighlightOneFrame = false;
8158 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
8159
8160 window->DC.MenuBarAppending = false;
8161 window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
8162 window->DC.TreeDepth = 0;
8163 window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00;
8164 window->DC.ChildWindows.resize(0);
8165 window->DC.StateStorage = &window->StateStorage;
8166 window->DC.CurrentColumns = NULL;
8167 window->DC.LayoutType = ImGuiLayoutType_Vertical;
8168 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
8169
8170 // Default item width. Make it proportional to window size if window can be manually resized.
8171 // (we cannot use AutoFitFramesX/AutoFitFramesY which is a temporary state)
8172 bool is_resizable_width;
8173 if (flags & ImGuiWindowFlags_ChildWindow)
8174 is_resizable_width = (window->Size.x > 0.0f) && !(window->ChildFlags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AlwaysAutoResize));
8175 else
8176 is_resizable_width = (window->Size.x > 0.0f) && !(flags & ImGuiWindowFlags_AlwaysAutoResize);
8177 if (is_resizable_width)
8178 window->DC.ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
8179 else
8180 window->DC.ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
8181 window->DC.ItemWidth = window->DC.ItemWidthDefault;
8182 window->DC.ItemWidthStack.resize(0);
8183 window->DC.TextWrapPos = -1.0f; // Disabled
8184 window->DC.TextWrapPosStack.resize(0);
8185 if (flags & ImGuiWindowFlags_Modal)
8186 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
8187
8188 if (window->AutoFitFramesX > 0)
8189 window->AutoFitFramesX--;
8190 if (window->AutoFitFramesY > 0)
8191 window->AutoFitFramesY--;
8192
8193 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
8194 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
8195 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
8196 // - Position window behind the modal that is not a begin-parent of this window.
8197 if (want_focus)
8198 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
8199 if (want_focus && window == g.NavWindow)
8200 NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
8201
8202 // Pressing Ctrl+C copy window content into the clipboard
8203 // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
8204 // [EXPERIMENTAL] Text outputs has many issues.
8205 if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
8206 if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C))
8207 LogToClipboard(0);
8208
8209 // Title bar
8210 if (!(flags & ImGuiWindowFlags_NoTitleBar))
8211 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);
8212
8213 // Clear hit test shape every frame
8214 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
8215
8216 if (flags & ImGuiWindowFlags_Tooltip)
8217 g.TooltipPreviousWindow = window;
8218
8219 // Set default BgClickFlags
8220 // This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overridden by user code.
8221 // FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button.
8222 window->BgClickFlags = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->BgClickFlags : (g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move);
8223
8224 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
8225 // This is useful to allow creating context menus on title bar only, etc.
8226 window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None;
8227 window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
8228 SetLastItemDataForWindow(window, title_bar_rect);
8229
8230 // [DEBUG]
8231#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8232 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
8233 DebugLocateItemResolveWithLastItem();
8234#endif
8235
8236 // [Test Engine] Register title bar / tab with MoveId.
8237#ifdef IMGUI_ENABLE_TEST_ENGINE
8238 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
8239 {
8240 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8241 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
8242 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8243 }
8244#endif
8245 }
8246 else
8247 {
8248 // Skip refresh always mark active
8249 if (window->SkipRefresh)
8250 SetWindowActiveForSkipRefresh(window);
8251
8252 // Append
8253 SetCurrentWindow(window);
8254 SetLastItemDataForWindow(window, window->TitleBarRect());
8255 }
8256
8257 if (!window->SkipRefresh)
8258 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
8259
8260 // 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)
8261 window->WriteAccessed = false;
8262 window->BeginCount++;
8263 g.NextWindowData.ClearFlags();
8264
8265 // Update visibility
8266 if (first_begin_of_the_frame && !window->SkipRefresh)
8267 {
8268 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
8269 {
8270 // Child window can be out of sight and have "negative" clip windows.
8271 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
8272 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
8273 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
8274 if (!g.LogEnabled && !nav_request)
8275 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
8276 {
8277 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
8278 window->HiddenFramesCannotSkipItems = 1;
8279 else
8280 window->HiddenFramesCanSkipItems = 1;
8281 }
8282
8283 // Hide along with parent or if parent is collapsed
8284 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
8285 window->HiddenFramesCanSkipItems = 1;
8286 if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0)
8287 window->HiddenFramesCannotSkipItems = 1;
8288 }
8289
8290 // 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)
8291 if (style.Alpha <= 0.0f)
8292 window->HiddenFramesCanSkipItems = 1;
8293
8294 // Update the Hidden flag
8295 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
8296 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
8297
8298 // Disable inputs for requested number of frames
8299 if (window->DisableInputsFrames > 0)
8300 {
8301 window->DisableInputsFrames--;
8302 window->Flags |= ImGuiWindowFlags_NoInputs;
8303 }
8304
8305 // Update the SkipItems flag, used to early out of all items functions (no layout required)
8306 bool skip_items = false;
8307 if (window->Collapsed || !window->Active || hidden_regular)
8308 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
8309 skip_items = true;
8310 window->SkipItems = skip_items;
8311 }
8312 else if (first_begin_of_the_frame)
8313 {
8314 // Skip refresh mode
8315 window->SkipItems = true;
8316 }
8317
8318 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
8319 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
8320#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8321 if (!window->IsFallbackWindow)
8322 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
8323 {
8324 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
8325 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
8326 return false;
8327 }
8328#endif
8329
8330 return !window->SkipItems;
8331}
8332
8333void ImGui::End()
8334{
8335 ImGuiContext& g = *GImGui;
8336 ImGuiWindow* window = g.CurrentWindow;
8337
8338 // Error checking: verify that user hasn't called End() too many times!
8339 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
8340 {
8341 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
8342 return;
8343 }
8344 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
8345
8346 // Error checking: verify that user doesn't directly call End() on a child window.
8347 if (window->Flags & ImGuiWindowFlags_Popup)
8348 IM_ASSERT_USER_ERROR(g.WithinEndPopupID == window->ID, "Must call EndPopup() and not End()!");
8349 if (window->Flags & ImGuiWindowFlags_ChildWindow)
8350 IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!");
8351
8352 // Close anything that is open
8353 if (window->DC.CurrentColumns)
8354 EndColumns();
8355 if (!window->SkipRefresh)
8356 PopClipRect(); // Inner window clip rectangle
8357 PopFocusScope();
8358 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
8359 EndDisabledOverrideReenable();
8360
8361 if (window->SkipRefresh)
8362 {
8363 IM_ASSERT(window->DrawList == NULL);
8364 window->DrawList = &window->DrawListInst;
8365 }
8366
8367 // Stop logging
8368 if (g.LogWindow == window) // FIXME: add more options for scope of logging
8369 LogFinish();
8370
8371 if (window->DC.IsSetPos)
8372 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
8373
8374 // Pop from window stack
8375 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
8376 if (window->Flags & ImGuiWindowFlags_ChildMenu)
8377 g.BeginMenuDepth--;
8378 if (window->Flags & ImGuiWindowFlags_Popup)
8379 g.BeginPopupStack.pop_back();
8380
8381 // Error handling, state recovery
8382 if (g.IO.ConfigErrorRecovery)
8383 ErrorRecoveryTryToRecoverWindowState(&window_stack_data.StackSizesInBegin);
8384
8385 g.CurrentWindowStack.pop_back();
8386 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
8387}
8388
8389void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8390{
8391 ImGuiContext& g = *GImGui;
8392 ImGuiItemFlags item_flags = g.CurrentItemFlags;
8393 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8394 if (enabled)
8395 item_flags |= option;
8396 else
8397 item_flags &= ~option;
8398 g.CurrentItemFlags = item_flags;
8399 g.ItemFlagsStack.push_back(item_flags);
8400}
8401
8402void ImGui::PopItemFlag()
8403{
8404 ImGuiContext& g = *GImGui;
8405 IM_ASSERT_USER_ERROR_RET(g.ItemFlagsStack.Size > 1, "Calling PopItemFlag() too many times!");
8406 g.ItemFlagsStack.pop_back();
8407 g.CurrentItemFlags = g.ItemFlagsStack.back();
8408}
8409
8410// BeginDisabled()/EndDisabled()
8411// - 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)
8412// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8413// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8414// - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
8415// (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)
8416// - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
8417void ImGui::BeginDisabled(bool disabled)
8418{
8419 ImGuiContext& g = *GImGui;
8420 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8421 if (!was_disabled && disabled)
8422 {
8423 g.DisabledAlphaBackup = g.Style.Alpha;
8424 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8425 }
8426 if (was_disabled || disabled)
8427 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8428 g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8429 g.DisabledStackSize++;
8430}
8431
8432void ImGui::EndDisabled()
8433{
8434 ImGuiContext& g = *GImGui;
8435 IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!");
8436 g.DisabledStackSize--;
8437 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8438 //PopItemFlag();
8439 g.ItemFlagsStack.pop_back();
8440 g.CurrentItemFlags = g.ItemFlagsStack.back();
8441 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8442 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8443}
8444
8445// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8446// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8447// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8448void ImGui::BeginDisabledOverrideReenable()
8449{
8450 ImGuiContext& g = *GImGui;
8451 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8452 g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha;
8453 g.Style.Alpha = g.DisabledAlphaBackup;
8454 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8455 g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8456 g.DisabledStackSize++;
8457}
8458
8459void ImGui::EndDisabledOverrideReenable()
8460{
8461 ImGuiContext& g = *GImGui;
8462 IM_ASSERT(g.DisabledStackSize > 0);
8463 g.DisabledStackSize--;
8464 g.ItemFlagsStack.pop_back();
8465 g.CurrentItemFlags = g.ItemFlagsStack.back();
8466 g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup;
8467}
8468
8469// ATTENTION THIS IS IN LEGACY LOCAL SPACE.
8470void ImGui::PushTextWrapPos(float wrap_local_pos_x)
8471{
8472 ImGuiContext& g = *GImGui;
8473 ImGuiWindow* window = g.CurrentWindow;
8474 window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8475 window->DC.TextWrapPos = wrap_local_pos_x;
8476}
8477
8478void ImGui::PopTextWrapPos()
8479{
8480 ImGuiContext& g = *GImGui;
8481 ImGuiWindow* window = g.CurrentWindow;
8482 IM_ASSERT_USER_ERROR_RET(window->DC.TextWrapPosStack.Size > 0, "Calling PopTextWrapPos() too many times!");
8483 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8484 window->DC.TextWrapPosStack.pop_back();
8485}
8486
8487static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)
8488{
8489 ImGuiWindow* last_window = NULL;
8490 while (last_window != window)
8491 {
8492 last_window = window;
8493 window = window->RootWindow;
8494 if (popup_hierarchy)
8495 window = window->RootWindowPopupTree;
8496 }
8497 return window;
8498}
8499
8500bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)
8501{
8502 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);
8503 if (window_root == potential_parent)
8504 return true;
8505 while (window != NULL)
8506 {
8507 if (window == potential_parent)
8508 return true;
8509 if (window == window_root) // end of chain
8510 return false;
8511 window = window->ParentWindow;
8512 }
8513 return false;
8514}
8515
8516bool ImGui::IsWindowInBeginStack(ImGuiWindow* window)
8517{
8518 ImGuiContext& g = *GImGui;
8519 for (int n = g.CurrentWindowStack.Size - 1; n >= 0; n--)
8520 if (g.CurrentWindowStack[n].Window == window)
8521 return true;
8522 return false;
8523}
8524
8525bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8526{
8527 if (window->RootWindow == potential_parent)
8528 return true;
8529 while (window != NULL)
8530 {
8531 if (window == potential_parent)
8532 return true;
8533 window = window->ParentWindowInBeginStack;
8534 }
8535 return false;
8536}
8537
8538bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8539{
8540 ImGuiContext& g = *GImGui;
8541
8542 // 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
8543 const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8544 if (display_layer_delta != 0)
8545 return display_layer_delta > 0;
8546
8547 for (int i = g.Windows.Size - 1; i >= 0; i--)
8548 {
8549 ImGuiWindow* candidate_window = g.Windows[i];
8550 if (candidate_window == potential_above)
8551 return true;
8552 if (candidate_window == potential_below)
8553 return false;
8554 }
8555 return false;
8556}
8557
8558// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8559// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8560// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8561// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8562bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8563{
8564 ImGuiContext& g = *GImGui;
8565 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
8566
8567 ImGuiWindow* ref_window = g.HoveredWindow;
8568 ImGuiWindow* cur_window = g.CurrentWindow;
8569 if (ref_window == NULL)
8570 return false;
8571
8572 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8573 {
8574 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8575 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8576 if (flags & ImGuiHoveredFlags_RootWindow)
8577 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
8578
8579 bool result;
8580 if (flags & ImGuiHoveredFlags_ChildWindows)
8581 result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
8582 else
8583 result = (ref_window == cur_window);
8584 if (!result)
8585 return false;
8586 }
8587
8588 if (!IsWindowContentHoverable(ref_window, flags))
8589 return false;
8590 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8591 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8592 return false;
8593
8594 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8595 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8596 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8597 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8598 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8599 if (flags & ImGuiHoveredFlags_ForTooltip)
8600 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8601 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8602 return false;
8603
8604 return true;
8605}
8606
8607float ImGui::GetWindowWidth()
8608{
8609 ImGuiWindow* window = GImGui->CurrentWindow;
8610 return window->Size.x;
8611}
8612
8613float ImGui::GetWindowHeight()
8614{
8615 ImGuiWindow* window = GImGui->CurrentWindow;
8616 return window->Size.y;
8617}
8618
8619ImVec2 ImGui::GetWindowPos()
8620{
8621 ImGuiContext& g = *GImGui;
8622 ImGuiWindow* window = g.CurrentWindow;
8623 return window->Pos;
8624}
8625
8626void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8627{
8628 // Test condition (NB: bit 0 is always true) and clear flags for next time
8629 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8630 return;
8631
8632 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8633 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8634 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8635
8636 // Set
8637 const ImVec2 old_pos = window->Pos;
8638 window->Pos = ImTrunc(pos);
8639 ImVec2 offset = window->Pos - old_pos;
8640 if (offset.x == 0.0f && offset.y == 0.0f)
8641 return;
8642 MarkIniSettingsDirty(window);
8643 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
8644 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8645 window->DC.IdealMaxPos += offset;
8646 window->DC.CursorStartPos += offset;
8647}
8648
8649void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8650{
8651 ImGuiWindow* window = GetCurrentWindowRead();
8652 SetWindowPos(window, pos, cond);
8653}
8654
8655void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8656{
8657 if (ImGuiWindow* window = FindWindowByName(name))
8658 SetWindowPos(window, pos, cond);
8659}
8660
8661ImVec2 ImGui::GetWindowSize()
8662{
8663 ImGuiWindow* window = GetCurrentWindowRead();
8664 return window->Size;
8665}
8666
8667void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8668{
8669 // Test condition (NB: bit 0 is always true) and clear flags for next time
8670 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8671 return;
8672
8673 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8674 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8675
8676 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8677 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8678 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8679 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8680 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8681
8682 // Set
8683 ImVec2 old_size = window->SizeFull;
8684 if (size.x <= 0.0f)
8685 window->AutoFitOnlyGrows = false;
8686 else
8687 window->SizeFull.x = IM_TRUNC(size.x);
8688 if (size.y <= 0.0f)
8689 window->AutoFitOnlyGrows = false;
8690 else
8691 window->SizeFull.y = IM_TRUNC(size.y);
8692 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8693 MarkIniSettingsDirty(window);
8694}
8695
8696void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8697{
8698 SetWindowSize(GImGui->CurrentWindow, size, cond);
8699}
8700
8701void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8702{
8703 if (ImGuiWindow* window = FindWindowByName(name))
8704 SetWindowSize(window, size, cond);
8705}
8706
8707void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8708{
8709 // Test condition (NB: bit 0 is always true) and clear flags for next time
8710 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8711 return;
8712 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8713
8714 // Queue applying in Begin()
8715 if (window->WantCollapseToggle)
8716 window->Collapsed ^= 1;
8717 window->WantCollapseToggle = (window->Collapsed != collapsed);
8718}
8719
8720void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8721{
8722 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8723 window->HitTestHoleSize = ImVec2ih(size);
8724 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8725}
8726
8727void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8728{
8729 window->Hidden = window->SkipItems = true;
8730 window->HiddenFramesCanSkipItems = 1;
8731}
8732
8733void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8734{
8735 SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8736}
8737
8738bool ImGui::IsWindowCollapsed()
8739{
8740 ImGuiWindow* window = GetCurrentWindowRead();
8741 return window->Collapsed;
8742}
8743
8744bool ImGui::IsWindowAppearing()
8745{
8746 ImGuiWindow* window = GetCurrentWindowRead();
8747 return window->Appearing;
8748}
8749
8750void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8751{
8752 if (ImGuiWindow* window = FindWindowByName(name))
8753 SetWindowCollapsed(window, collapsed, cond);
8754}
8755
8756void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8757{
8758 ImGuiContext& g = *GImGui;
8759 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8760 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos;
8761 g.NextWindowData.PosVal = pos;
8762 g.NextWindowData.PosPivotVal = pivot;
8763 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8764}
8765
8766void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8767{
8768 ImGuiContext& g = *GImGui;
8769 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8770 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize;
8771 g.NextWindowData.SizeVal = size;
8772 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8773}
8774
8775// For each axis:
8776// - 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.
8777// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8778// - See "Demo->Examples->Constrained-resizing window" for examples.
8779void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8780{
8781 ImGuiContext& g = *GImGui;
8782 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8783 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8784 g.NextWindowData.SizeCallback = custom_callback;
8785 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8786}
8787
8788// Content size = inner scrollable rectangle, padded with WindowPadding.
8789// SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8790void ImGui::SetNextWindowContentSize(const ImVec2& size)
8791{
8792 ImGuiContext& g = *GImGui;
8793 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize;
8794 g.NextWindowData.ContentSizeVal = ImTrunc(size);
8795}
8796
8797void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8798{
8799 ImGuiContext& g = *GImGui;
8800 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll;
8801 g.NextWindowData.ScrollVal = scroll;
8802}
8803
8804void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8805{
8806 ImGuiContext& g = *GImGui;
8807 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8808 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed;
8809 g.NextWindowData.CollapsedVal = collapsed;
8810 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8811}
8812
8813void ImGui::SetNextWindowBgAlpha(float alpha)
8814{
8815 ImGuiContext& g = *GImGui;
8816 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8817 g.NextWindowData.BgAlphaVal = alpha;
8818}
8819
8820// This is experimental and meant to be a toy for exploring a future/wider range of features.
8821void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8822{
8823 ImGuiContext& g = *GImGui;
8824 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8825 g.NextWindowData.RefreshFlagsVal = flags;
8826}
8827
8828ImDrawList* ImGui::GetWindowDrawList()
8829{
8830 ImGuiWindow* window = GetCurrentWindow();
8831 return window->DrawList;
8832}
8833
8834ImFont* ImGui::GetFont()
8835{
8836 return GImGui->Font;
8837}
8838
8839ImFontBaked* ImGui::GetFontBaked()
8840{
8841 return GImGui->FontBaked;
8842}
8843
8844// Get current font size (= height in pixels) of current font, with global scale factors applied.
8845// - Use style.FontSizeBase to get value before global scale factors.
8846// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors)
8847float ImGui::GetFontSize()
8848{
8849 return GImGui->FontSize;
8850}
8851
8852ImVec2 ImGui::GetFontTexUvWhitePixel()
8853{
8854 return GImGui->DrawListSharedData.TexUvWhitePixel;
8855}
8856
8857// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows.
8858#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
8859void ImGui::SetWindowFontScale(float scale)
8860{
8861 IM_ASSERT(scale > 0.0f);
8862 ImGuiWindow* window = GetCurrentWindow();
8863 window->FontWindowScale = scale;
8864 UpdateCurrentFontSize(0.0f);
8865}
8866#endif
8867
8868void ImGui::PushFocusScope(ImGuiID id)
8869{
8870 ImGuiContext& g = *GImGui;
8871 ImGuiFocusScopeData data;
8872 data.ID = id;
8873 data.WindowID = g.CurrentWindow->ID;
8874 g.FocusScopeStack.push_back(data);
8875 g.CurrentFocusScopeId = id;
8876}
8877
8878void ImGui::PopFocusScope()
8879{
8880 ImGuiContext& g = *GImGui;
8881 IM_ASSERT_USER_ERROR_RET(g.FocusScopeStack.Size > g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack, "Calling PopFocusScope() too many times!");
8882 g.FocusScopeStack.pop_back();
8883 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8884}
8885
8886bool ImGui::IsInNavFocusRoute(ImGuiID focus_scope_id)
8887{
8888 ImGuiContext& g = *GImGui;
8889 if (g.NavFocusScopeId == focus_scope_id)
8890 return true;
8891 for (const ImGuiFocusScopeData& focus_scope : g.NavFocusRoute)
8892 if (focus_scope.ID == focus_scope_id)
8893 return true;
8894 return false;
8895}
8896
8897void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8898{
8899 ImGuiContext& g = *GImGui;
8900 g.NavFocusScopeId = focus_scope_id;
8901 g.NavFocusRoute.resize(0); // Invalidate
8902 if (focus_scope_id == 0)
8903 return;
8904 IM_ASSERT(g.NavWindow != NULL);
8905
8906 // Store current path (in reverse order)
8907 if (focus_scope_id == g.CurrentFocusScopeId)
8908 {
8909 // Top of focus stack contains local focus scopes inside current window
8910 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8911 g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8912 }
8913 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8914 g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8915 else
8916 return;
8917
8918 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8919 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8920 g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8921 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8922}
8923
8924// Focus = move navigation cursor, set scrolling, set focus window.
8925void ImGui::FocusItem()
8926{
8927 ImGuiContext& g = *GImGui;
8928 ImGuiWindow* window = g.CurrentWindow;
8929 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8930 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8931 {
8932 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8933 return;
8934 }
8935
8936 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
8937 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8938 SetNavWindow(window);
8939 NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8940 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8941}
8942
8943void ImGui::ActivateItemByID(ImGuiID id)
8944{
8945 ImGuiContext& g = *GImGui;
8946 g.NavNextActivateId = id;
8947 g.NavNextActivateFlags = ImGuiActivateFlags_None;
8948}
8949
8950// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8951// But ActivateItem() should function without altering scroll/focus?
8952void ImGui::SetKeyboardFocusHere(int offset)
8953{
8954 ImGuiContext& g = *GImGui;
8955 ImGuiWindow* window = g.CurrentWindow;
8956 IM_ASSERT(offset >= -1); // -1 is allowed but not below
8957 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8958
8959 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8960 // When we refactor this function into ActivateItem() we may want to make this an option.
8961 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8962 // is also automatically dropped in the event g.ActiveId is stolen.
8963 if (g.DragDropActive || g.MovingWindow != NULL)
8964 {
8965 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8966 return;
8967 }
8968
8969 SetNavWindow(window);
8970
8971 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
8972 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8973 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.
8974 if (offset == -1)
8975 {
8976 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8977 }
8978 else
8979 {
8980 g.NavTabbingDir = 1;
8981 g.NavTabbingCounter = offset + 1;
8982 }
8983}
8984
8985void ImGui::SetItemDefaultFocus()
8986{
8987 ImGuiContext& g = *GImGui;
8988 ImGuiWindow* window = g.CurrentWindow;
8989 if (!window->Appearing)
8990 return;
8991 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8992 return;
8993
8994 g.NavInitRequest = false;
8995 NavApplyItemToResult(&g.NavInitResult);
8996 NavUpdateAnyRequestFlag();
8997
8998 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8999 if (!window->ClipRect.Contains(g.LastItemData.Rect))
9000 ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
9001}
9002
9003void ImGui::SetStateStorage(ImGuiStorage* tree)
9004{
9005 ImGuiWindow* window = GImGui->CurrentWindow;
9006 window->DC.StateStorage = tree ? tree : &window->StateStorage;
9007}
9008
9009ImGuiStorage* ImGui::GetStateStorage()
9010{
9011 ImGuiWindow* window = GImGui->CurrentWindow;
9012 return window->DC.StateStorage;
9013}
9014
9015bool ImGui::IsRectVisible(const ImVec2& size)
9016{
9017 ImGuiWindow* window = GImGui->CurrentWindow;
9018 return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
9019}
9020
9021bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
9022{
9023 ImGuiWindow* window = GImGui->CurrentWindow;
9024 return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
9025}
9026
9027//-----------------------------------------------------------------------------
9028// [SECTION] FONTS, TEXTURES
9029//-----------------------------------------------------------------------------
9030// Most of the relevant font logic is in imgui_draw.cpp.
9031// Those are high-level support functions.
9032//-----------------------------------------------------------------------------
9033// - UpdateTexturesNewFrame() [Internal]
9034// - UpdateTexturesEndFrame() [Internal]
9035// - UpdateFontsNewFrame() [Internal]
9036// - UpdateFontsEndFrame() [Internal]
9037// - GetDefaultFont() [Internal]
9038// - RegisterUserTexture() [Internal]
9039// - UnregisterUserTexture() [Internal]
9040// - RegisterFontAtlas() [Internal]
9041// - UnregisterFontAtlas() [Internal]
9042// - SetCurrentFont() [Internal]
9043// - UpdateCurrentFontSize() [Internal]
9044// - SetFontRasterizerDensity() [Internal]
9045// - PushFont()
9046// - PopFont()
9047//-----------------------------------------------------------------------------
9048
9049static void ImGui::UpdateTexturesNewFrame()
9050{
9051 // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count.
9052 ImGuiContext& g = *GImGui;
9053 const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
9054 for (ImFontAtlas* atlas : g.FontAtlases)
9055 {
9056 if (atlas->OwnerContext == &g)
9057 {
9058 ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures);
9059 }
9060 else
9061 {
9062 // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it.
9063 // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context.
9064 // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that.
9065 // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures.
9066 IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1);
9067 IM_ASSERT(atlas->RendererHasTextures == has_textures);
9068 }
9069 }
9070 for (ImTextureData* tex : g.UserTextures)
9071 ImTextureDataUpdateNewFrame(tex);
9072}
9073
9074// Build a single texture list
9075static void ImGui::UpdateTexturesEndFrame()
9076{
9077 ImGuiContext& g = *GImGui;
9078 g.PlatformIO.Textures.resize(0);
9079 for (ImFontAtlas* atlas : g.FontAtlases)
9080 for (ImTextureData* tex : atlas->TexList)
9081 {
9082 // We provide this information so backends can decide whether to destroy textures.
9083 // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized.
9084 tex->RefCount = (unsigned short)atlas->RefCount;
9085 g.PlatformIO.Textures.push_back(tex);
9086 }
9087 for (ImTextureData* tex : g.UserTextures)
9088 g.PlatformIO.Textures.push_back(tex);
9089}
9090
9091void ImGui::UpdateFontsNewFrame()
9092{
9093 ImGuiContext& g = *GImGui;
9094 if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
9095 for (ImFontAtlas* atlas : g.FontAtlases)
9096 atlas->Locked = true;
9097
9098 if (g.Style._NextFrameFontSizeBase != 0.0f)
9099 {
9100 g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase;
9101 g.Style._NextFrameFontSizeBase = 0.0f;
9102 }
9103
9104 // Apply default font size the first time
9105 ImFont* font = ImGui::GetDefaultFont();
9106 if (g.Style.FontSizeBase <= 0.0f)
9107 g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE_BASE);
9108
9109 // Set initial font
9110 g.Font = font;
9111 g.FontSizeBase = g.Style.FontSizeBase;
9112 g.FontSize = 0.0f;
9113 ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize
9114 SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale
9115 g.FontStack.push_back(font_stack_data);
9116 IM_ASSERT(g.Font->IsLoaded());
9117}
9118
9119void ImGui::UpdateFontsEndFrame()
9120{
9121 PopFont();
9122}
9123
9124ImFont* ImGui::GetDefaultFont()
9125{
9126 ImGuiContext& g = *GImGui;
9127 ImFontAtlas* atlas = g.IO.Fonts;
9128 if (atlas->Builder == NULL || atlas->Fonts.Size == 0)
9129 ImFontAtlasBuildMain(atlas);
9130 return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0];
9131}
9132
9133// EXPERIMENTAL. Use ImTextureDataQueueUpload() to queue updates. Textures logic will be automatically be updated in NewFrame().
9134void ImGui::RegisterUserTexture(ImTextureData* tex)
9135{
9136 ImGuiContext& g = *GImGui;
9137 tex->RefCount++;
9138 g.UserTextures.push_back(tex);
9139}
9140
9141void ImGui::UnregisterUserTexture(ImTextureData* tex)
9142{
9143 ImGuiContext& g = *GImGui;
9144 IM_ASSERT(tex->RefCount > 0);
9145 tex->RefCount--;
9146 g.UserTextures.find_erase(tex);
9147}
9148
9149void ImGui::RegisterFontAtlas(ImFontAtlas* atlas)
9150{
9151 ImGuiContext& g = *GImGui;
9152 if (g.FontAtlases.Size == 0)
9153 IM_ASSERT(atlas == g.IO.Fonts);
9154 atlas->RefCount++;
9155 g.FontAtlases.push_back(atlas);
9156 ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData);
9157 for (ImTextureData* tex : atlas->TexList)
9158 tex->RefCount = (unsigned short)atlas->RefCount;
9159}
9160
9161void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas)
9162{
9163 ImGuiContext& g = *GImGui;
9164 IM_ASSERT(atlas->RefCount > 0);
9165 ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData);
9166 g.FontAtlases.find_erase(atlas);
9167 atlas->RefCount--;
9168 for (ImTextureData* tex : atlas->TexList)
9169 tex->RefCount = (unsigned short)atlas->RefCount;
9170}
9171
9172// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList.
9173// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls.
9174// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
9175// - Some code paths never really fully worked with multiple atlas textures.
9176// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture()
9177// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
9178// because we have a concrete need and a test bed for multiple atlas textures.
9179// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ?
9180void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling)
9181{
9182 ImGuiContext& g = *GImGui;
9183 g.Font = font;
9184 g.FontSizeBase = font_size_before_scaling;
9185 UpdateCurrentFontSize(font_size_after_scaling);
9186
9187 if (font != NULL)
9188 {
9189 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
9190#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9191 IM_ASSERT(font->Scale > 0.0f);
9192#endif
9193 ImFontAtlas* atlas = font->OwnerAtlas;
9194 g.DrawListSharedData.FontAtlas = atlas;
9195 g.DrawListSharedData.Font = font;
9196 ImFontAtlasUpdateDrawListsSharedData(atlas);
9197 if (g.CurrentWindow != NULL)
9198 g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef);
9199 }
9200}
9201
9202void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling)
9203{
9204 ImGuiContext& g = *GImGui;
9205 ImGuiWindow* window = g.CurrentWindow;
9206
9207 g.Style.FontSizeBase = g.FontSizeBase;
9208
9209 // Restoring is pretty much only used by PopFont()
9210 float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f;
9211 if (final_size == 0.0f)
9212 {
9213 final_size = g.FontSizeBase;
9214
9215 // Global scale factors
9216 final_size *= g.Style.FontScaleMain; // Main global scale factor
9217 final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor (in docking branch: automatically updated when io.ConfigDpiScaleFonts is enabled).
9218
9219 // Window scale (mostly obsolete now)
9220 if (window != NULL)
9221 final_size *= window->FontWindowScale;
9222
9223 // Legacy scale factors
9224#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9225 final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead!
9226 if (g.Font != NULL)
9227 final_size *= g.Font->Scale; // Was never really useful.
9228#endif
9229 }
9230
9231 // Round font size
9232 // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
9233 // - We may support it better later and remove this rounding.
9234 final_size = GetRoundedFontSize(final_size);
9235 final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX);
9236 if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures))
9237 g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity;
9238
9239 g.FontSize = final_size;
9240 g.DrawListSharedData.FontSize = g.FontSize;
9241
9242 // Early out to avoid hidden window keeping bakes referenced and out of GC reach.
9243 // - However this leave a pretty subtle and damning error surface area if g.FontBaked was mismatching.
9244 // Probably needs to be reevaluated into e.g. setting g.FontBaked = nullptr to mark it as dirty.
9245 // - Note that 'PushFont(); Begin(); End(); PopFont()' from within any collapsed window is not compromised, because Begin() calls SetCurrentWindow()->...->UpdateCurrentSize()
9246 if (window != NULL && window->SkipItems)
9247 {
9248 ImGuiTable* table = g.CurrentTable;
9249 const bool allow_early_out = table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false); // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data.
9250 if (allow_early_out)
9251 return;
9252 }
9253
9254 g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL;
9255 g.FontBakedScale = (g.FontBaked != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f;
9256 g.DrawListSharedData.FontScale = g.FontBakedScale;
9257}
9258
9259// Exposed in case user may want to override setting density.
9260// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it.
9261void ImGui::SetFontRasterizerDensity(float rasterizer_density)
9262{
9263 ImGuiContext& g = *GImGui;
9264 IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures);
9265 if (g.FontRasterizerDensity == rasterizer_density)
9266 return;
9267 g.FontRasterizerDensity = rasterizer_density;
9268 UpdateCurrentFontSize(0.0f);
9269}
9270
9271// If you want to scale an existing font size! Read comments in imgui.h!
9272void ImGui::PushFont(ImFont* font, float font_size_base)
9273{
9274 ImGuiContext& g = *GImGui;
9275 if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont())
9276 font = g.Font;
9277 IM_ASSERT(font != NULL);
9278 IM_ASSERT(font_size_base >= 0.0f);
9279
9280 g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize });
9281 if (font_size_base == 0.0f)
9282 font_size_base = g.FontSizeBase; // Keep current font size
9283 SetCurrentFont(font, font_size_base, 0.0f);
9284}
9285
9286void ImGui::PopFont()
9287{
9288 ImGuiContext& g = *GImGui;
9289 IM_ASSERT_USER_ERROR_RET(g.FontStack.Size > 0, "Calling PopFont() too many times!");
9290 ImFontStackData* font_stack_data = &g.FontStack.back();
9291 SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling);
9292 g.FontStack.pop_back();
9293}
9294
9295//-----------------------------------------------------------------------------
9296// [SECTION] ID STACK
9297//-----------------------------------------------------------------------------
9298
9299// This is one of the very rare legacy case where we use ImGuiWindow methods,
9300// it should ideally be flattened at some point but it's been used a lots by widgets.
9301IM_MSVC_RUNTIME_CHECKS_OFF
9302ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
9303{
9304 ImGuiID seed = IDStack.back();
9305 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
9306#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9307 ImGuiContext& g = *Ctx;
9308 if (g.DebugHookIdInfoId == id)
9309 ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
9310#endif
9311 return id;
9312}
9313
9314ImGuiID ImGuiWindow::GetID(const void* ptr)
9315{
9316 ImGuiID seed = IDStack.back();
9317 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
9318#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9319 ImGuiContext& g = *Ctx;
9320 if (g.DebugHookIdInfoId == id)
9321 ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
9322#endif
9323 return id;
9324}
9325
9326ImGuiID ImGuiWindow::GetID(int n)
9327{
9328 ImGuiID seed = IDStack.back();
9329 ImGuiID id = ImHashData(&n, sizeof(n), seed);
9330#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9331 ImGuiContext& g = *Ctx;
9332 if (g.DebugHookIdInfoId == id)
9333 ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
9334#endif
9335 return id;
9336}
9337
9338// This is only used in rare/specific situations to manufacture an ID out of nowhere.
9339// FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
9340ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs)
9341{
9342 ImGuiID seed = IDStack.back();
9343 ImVec2 p_rel = ImGui::WindowPosAbsToRel(this, p_abs);
9344 ImGuiID id = ImHashData(&p_rel, sizeof(p_rel), seed);
9345 return id;
9346}
9347
9348// "
9349ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
9350{
9351 ImGuiID seed = IDStack.back();
9352 ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
9353 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
9354 return id;
9355}
9356
9357void ImGui::PushID(const char* str_id)
9358{
9359 ImGuiContext& g = *GImGui;
9360 ImGuiWindow* window = g.CurrentWindow;
9361 ImGuiID id = window->GetID(str_id);
9362 window->IDStack.push_back(id);
9363}
9364
9365void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
9366{
9367 ImGuiContext& g = *GImGui;
9368 ImGuiWindow* window = g.CurrentWindow;
9369 ImGuiID id = window->GetID(str_id_begin, str_id_end);
9370 window->IDStack.push_back(id);
9371}
9372
9373void ImGui::PushID(const void* ptr_id)
9374{
9375 ImGuiContext& g = *GImGui;
9376 ImGuiWindow* window = g.CurrentWindow;
9377 ImGuiID id = window->GetID(ptr_id);
9378 window->IDStack.push_back(id);
9379}
9380
9381void ImGui::PushID(int int_id)
9382{
9383 ImGuiContext& g = *GImGui;
9384 ImGuiWindow* window = g.CurrentWindow;
9385 ImGuiID id = window->GetID(int_id);
9386 window->IDStack.push_back(id);
9387}
9388
9389// Push a given id value ignoring the ID stack as a seed.
9390void ImGui::PushOverrideID(ImGuiID id)
9391{
9392 ImGuiContext& g = *GImGui;
9393 ImGuiWindow* window = g.CurrentWindow;
9394#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9395 if (g.DebugHookIdInfoId == id)
9396 DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
9397#endif
9398 window->IDStack.push_back(id);
9399}
9400
9401// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
9402// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
9403// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
9404ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
9405{
9406 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
9407#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9408 ImGuiContext& g = *GImGui;
9409 if (g.DebugHookIdInfoId == id)
9410 DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
9411#endif
9412 return id;
9413}
9414
9415ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
9416{
9417 ImGuiID id = ImHashData(&n, sizeof(n), seed);
9418#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9419 ImGuiContext& g = *GImGui;
9420 if (g.DebugHookIdInfoId == id)
9421 DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
9422#endif
9423 return id;
9424}
9425
9426void ImGui::PopID()
9427{
9428 ImGuiWindow* window = GImGui->CurrentWindow;
9429 IM_ASSERT_USER_ERROR_RET(window->IDStack.Size > 1, "Calling PopID() too many times!");
9430 window->IDStack.pop_back();
9431}
9432
9433ImGuiID ImGui::GetID(const char* str_id)
9434{
9435 ImGuiWindow* window = GImGui->CurrentWindow;
9436 return window->GetID(str_id);
9437}
9438
9439ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9440{
9441 ImGuiWindow* window = GImGui->CurrentWindow;
9442 return window->GetID(str_id_begin, str_id_end);
9443}
9444
9445ImGuiID ImGui::GetID(const void* ptr_id)
9446{
9447 ImGuiWindow* window = GImGui->CurrentWindow;
9448 return window->GetID(ptr_id);
9449}
9450
9451ImGuiID ImGui::GetID(int int_id)
9452{
9453 ImGuiWindow* window = GImGui->CurrentWindow;
9454 return window->GetID(int_id);
9455}
9456IM_MSVC_RUNTIME_CHECKS_RESTORE
9457
9458//-----------------------------------------------------------------------------
9459// [SECTION] INPUTS
9460//-----------------------------------------------------------------------------
9461// - GetModForLRModKey() [Internal]
9462// - FixupKeyChord() [Internal]
9463// - GetKeyData() [Internal]
9464// - GetKeyIndex() [Internal]
9465// - GetKeyName()
9466// - GetKeyChordName() [Internal]
9467// - CalcTypematicRepeatAmount() [Internal]
9468// - GetTypematicRepeatRate() [Internal]
9469// - GetKeyPressedAmount() [Internal]
9470// - GetKeyMagnitude2d() [Internal]
9471//-----------------------------------------------------------------------------
9472// - UpdateKeyRoutingTable() [Internal]
9473// - GetRoutingIdFromOwnerId() [Internal]
9474// - GetShortcutRoutingData() [Internal]
9475// - CalcRoutingScore() [Internal]
9476// - SetShortcutRouting() [Internal]
9477// - TestShortcutRouting() [Internal]
9478//-----------------------------------------------------------------------------
9479// - IsKeyDown()
9480// - IsKeyPressed()
9481// - IsKeyReleased()
9482//-----------------------------------------------------------------------------
9483// - IsMouseDown()
9484// - IsMouseClicked()
9485// - IsMouseReleased()
9486// - IsMouseDoubleClicked()
9487// - GetMouseClickedCount()
9488// - GetItemClickedCountWithSingleClickDelay()
9489// - IsMouseHoveringRect() [Internal]
9490// - IsMouseDragPastThreshold() [Internal]
9491// - IsMouseDragging()
9492// - GetMousePos()
9493// - SetMousePos() [Internal]
9494// - GetMousePosOnOpeningCurrentPopup()
9495// - IsMousePosValid()
9496// - IsAnyMouseDown()
9497// - GetMouseDragDelta()
9498// - ResetMouseDragDelta()
9499// - GetMouseCursor()
9500// - SetMouseCursor()
9501//-----------------------------------------------------------------------------
9502// - UpdateAliasKey()
9503// - GetMergedModsFromKeys()
9504// - UpdateKeyboardInputs()
9505// - UpdateMouseInputs()
9506//-----------------------------------------------------------------------------
9507// - LockWheelingWindow [Internal]
9508// - FindBestWheelingWindow [Internal]
9509// - UpdateMouseWheel() [Internal]
9510//-----------------------------------------------------------------------------
9511// - SetNextFrameWantCaptureKeyboard()
9512// - SetNextFrameWantCaptureMouse()
9513//-----------------------------------------------------------------------------
9514// - GetInputSourceName() [Internal]
9515// - DebugPrintInputEvent() [Internal]
9516// - UpdateInputEvents() [Internal]
9517//-----------------------------------------------------------------------------
9518// - GetKeyOwner() [Internal]
9519// - TestKeyOwner() [Internal]
9520// - SetKeyOwner() [Internal]
9521// - SetItemKeyOwner() [Internal]
9522// - Shortcut() [Internal]
9523//-----------------------------------------------------------------------------
9524
9525static ImGuiKeyChord GetModForLRModKey(ImGuiKey key)
9526{
9527 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9528 return ImGuiMod_Ctrl;
9529 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9530 return ImGuiMod_Shift;
9531 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9532 return ImGuiMod_Alt;
9533 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9534 return ImGuiMod_Super;
9535 return ImGuiMod_None;
9536}
9537
9538ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9539{
9540 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9541 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9542 if (IsLRModKey(key))
9543 key_chord |= GetModForLRModKey(key);
9544 return key_chord;
9545}
9546
9547ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9548{
9549 ImGuiContext& g = *ctx;
9550
9551 // Special storage location for mods
9552 if (key & ImGuiMod_Mask_)
9553 key = ConvertSingleModFlagToKey(key);
9554
9555 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9556 return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
9557}
9558
9559// Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
9560static const char* const GKeyNames[] =
9561{
9562 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9563 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9564 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9565 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9566 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9567 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9568 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9569 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9570 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9571 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9572 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9573 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9574 "AppBack", "AppForward", "Oem102",
9575 "GamepadStart", "GamepadBack",
9576 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9577 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9578 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9579 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9580 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9581 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9582 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9583};
9584IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_COUNTOF(GKeyNames));
9585
9586const char* ImGui::GetKeyName(ImGuiKey key)
9587{
9588 if (key == ImGuiKey_None)
9589 return "None";
9590 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9591 if (key & ImGuiMod_Mask_)
9592 key = ConvertSingleModFlagToKey(key);
9593 if (!IsNamedKey(key))
9594 return "Unknown";
9595
9596 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9597}
9598
9599// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9600// Lifetime of return value: valid until next call to same function.
9601const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9602{
9603 ImGuiContext& g = *GImGui;
9604
9605 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9606 if (IsLRModKey(key))
9607 key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9608 ImFormatString(g.TempKeychordName, IM_COUNTOF(g.TempKeychordName), "%s%s%s%s%s",
9609 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9610 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9611 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9612 (key_chord & ImGuiMod_Super) ? "Super+" : "",
9613 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9614 size_t len;
9615 if (key == ImGuiKey_None && key_chord != 0)
9616 if ((len = ImStrlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9617 g.TempKeychordName[len - 1] = 0;
9618 return g.TempKeychordName;
9619}
9620
9621// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9622// t1 = current time (e.g.: g.Time)
9623// An event is triggered at:
9624// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
9625int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9626{
9627 if (t1 == 0.0f)
9628 return 1;
9629 if (t0 >= t1)
9630 return 0;
9631 if (repeat_rate <= 0.0f)
9632 return t0 < repeat_delay && t1 >= repeat_delay;
9633 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9634 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9635 const int count = count_t1 - count_t0;
9636 return count;
9637}
9638
9639void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9640{
9641 ImGuiContext& g = *GImGui;
9642 switch (flags & ImGuiInputFlags_RepeatRateMask_)
9643 {
9644 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9645 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9646 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9647 }
9648}
9649
9650// Return value representing the number of presses in the last time period, for the given repeat rate
9651// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9652int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9653{
9654 ImGuiContext& g = *GImGui;
9655 const ImGuiKeyData* key_data = GetKeyData(key);
9656 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)
9657 return 0;
9658 const float t = key_data->DownDuration;
9659 return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9660}
9661
9662// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9663ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9664{
9665 return ImVec2(
9666 GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9667 GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9668}
9669
9670// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9671// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
9672// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
9673// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9674static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9675{
9676 ImGuiContext& g = *GImGui;
9677 rt->EntriesNext.resize(0);
9678 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9679 {
9680 const int new_routing_start_idx = rt->EntriesNext.Size;
9681 ImGuiKeyRoutingData* routing_entry;
9682 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9683 {
9684 routing_entry = &rt->Entries[old_routing_idx];
9685 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9686 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9687 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9688 routing_entry->RoutingNextScore = 0;
9689 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9690 continue;
9691 rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9692
9693 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9694 // This is the result of previous frame's SetShortcutRouting() call.
9695 if (routing_entry->Mods == g.IO.KeyMods)
9696 {
9697 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9698 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9699 {
9700 owner_data->OwnerCurr = routing_entry->RoutingCurr;
9701 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9702 }
9703 }
9704 }
9705
9706 // Rewrite linked-list
9707 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9708 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9709 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9710 }
9711 rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9712}
9713
9714// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9715static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9716{
9717 ImGuiContext& g = *GImGui;
9718 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9719}
9720
9721ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9722{
9723 // Majority of shortcuts will be Key + any number of Mods
9724 // We accept _Single_ mod with ImGuiKey_None.
9725 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
9726 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
9727 // - Shortcut(ImGuiMod_Ctrl); // Legal
9728 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
9729 ImGuiContext& g = *GImGui;
9730 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9731 ImGuiKeyRoutingData* routing_data;
9732 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9733 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9734 if (key == ImGuiKey_None)
9735 key = ConvertSingleModFlagToKey(mods);
9736 IM_ASSERT(IsNamedKey(key));
9737
9738 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9739 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9740 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9741 {
9742 routing_data = &rt->Entries[idx];
9743 if (routing_data->Mods == mods)
9744 return routing_data;
9745 }
9746
9747 // Add to linked-list
9748 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9749 rt->Entries.push_back(ImGuiKeyRoutingData());
9750 routing_data = &rt->Entries[routing_data_idx];
9751 routing_data->Mods = (ImU16)mods;
9752 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9753 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9754 return routing_data;
9755}
9756
9757// Current score encoding
9758// - 0: Never route
9759// - 1: ImGuiInputFlags_RouteGlobal (lower priority)
9760// - 100..199: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9761// 200: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9762// 300: ImGuiInputFlags_RouteActive or ImGuiInputFlags_RouteFocused (if item active)
9763// 400: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9764// - 500..599: ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteOverActive (if window in focus-stack) (higher priority)
9765// 'flags' should include an explicit routing policy
9766static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9767{
9768 ImGuiContext& g = *GImGui;
9769 if (flags & ImGuiInputFlags_RouteFocused)
9770 {
9771 // ActiveID gets high priority
9772 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9773 if (owner_id != 0 && g.ActiveId == owner_id)
9774 return 300;
9775
9776 // Score based on distance to focused window (lower is better)
9777 // Assuming both windows are submitting a routing request,
9778 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9779 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
9780 // Assuming only WindowA is submitting a routing request,
9781 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9782 // This essentially follow the window->ParentWindowForFocusRoute chain.
9783 if (focus_scope_id == 0)
9784 return 0;
9785 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9786 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9787 {
9788 if (flags & ImGuiInputFlags_RouteOverActive) // && g.ActiveId != 0 && g.ActiveId != owner_id)
9789 return 599 - index_in_focus_path;
9790 else
9791 return 199 - index_in_focus_path;
9792 }
9793 return 0;
9794 }
9795 else if (flags & ImGuiInputFlags_RouteActive)
9796 {
9797 if (owner_id != 0 && g.ActiveId == owner_id)
9798 return 300;
9799 return 0;
9800 }
9801 else if (flags & ImGuiInputFlags_RouteGlobal)
9802 {
9803 if (flags & ImGuiInputFlags_RouteOverActive)
9804 return 400;
9805 if (owner_id != 0 && g.ActiveId == owner_id)
9806 return 300;
9807 if (flags & ImGuiInputFlags_RouteOverFocused)
9808 return 200;
9809 return 1;
9810 }
9811 IM_ASSERT(0);
9812 return 0;
9813}
9814
9815// - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9816// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9817// - 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.
9818static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9819{
9820 // Mimic 'ignore_char_inputs' logic in InputText()
9821 ImGuiContext& g = *GImGui;
9822
9823 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9824 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9825 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9826 if (ignore_char_inputs)
9827 return false;
9828
9829 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9830 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9831 if (key == ImGuiKey_None)
9832 return false;
9833 return g.KeysMayBeCharInput.TestBit(key);
9834}
9835
9836// Request a desired route for an input chord (key + mods).
9837// Return true if the route is available this frame.
9838// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9839// (Conceptually this does a "Submit for next frame" + "Test for current frame".
9840// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9841bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9842{
9843 ImGuiContext& g = *GImGui;
9844 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9845 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9846 else
9847 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9848 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9849 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteUnlessBgFocused))
9850 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9851 if (flags & ImGuiInputFlags_RouteOverActive)
9852 IM_ASSERT(flags & (ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteFocused));
9853
9854 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9855 key_chord = FixupKeyChord(key_chord);
9856
9857 // [DEBUG] Debug break requested by user
9858 if (g.DebugBreakInShortcutRouting == key_chord)
9859 IM_DEBUG_BREAK();
9860
9861 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9862 if (g.NavWindow == NULL)
9863 return false;
9864
9865 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9866 if (flags & ImGuiInputFlags_RouteAlways)
9867 {
9868 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9869 return true;
9870 }
9871
9872 // Specific culling when there's an active item.
9873 if (g.ActiveId != 0 && g.ActiveId != owner_id)
9874 {
9875 if (flags & ImGuiInputFlags_RouteActive)
9876 return false;
9877
9878 // Cull shortcuts with no modifiers when it could generate a character.
9879 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9880 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9881 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9882 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9883 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9884 {
9885 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9886 return false;
9887 }
9888
9889 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9890 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9891 {
9892 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9893 if (key == ImGuiKey_None)
9894 key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9895 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9896 return false;
9897 }
9898 }
9899
9900 // Where do we evaluate route for?
9901 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9902 if (flags & ImGuiInputFlags_RouteFromRootWindow)
9903 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9904
9905 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9906 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9907 if (score == 0)
9908 return false;
9909
9910 // Submit routing for NEXT frame (assuming score is sufficient)
9911 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using >= instead of >).
9912 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9913 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score >= routing_data->RoutingNextScore) : (score > routing_data->RoutingNextScore);
9914 if (score > routing_data->RoutingNextScore)
9915 {
9916 routing_data->RoutingNext = owner_id;
9917 routing_data->RoutingNextScore = (ImU16)score;
9918 }
9919
9920 // Return routing state for CURRENT frame
9921 if (routing_data->RoutingCurr == owner_id)
9922 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9923 return routing_data->RoutingCurr == owner_id;
9924}
9925
9926// Currently unused by core (but used by tests)
9927// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9928bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9929{
9930 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9931 key_chord = FixupKeyChord(key_chord);
9932 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9933 return routing_data->RoutingCurr == routing_id;
9934}
9935
9936// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9937// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9938bool ImGui::IsKeyDown(ImGuiKey key)
9939{
9940 return IsKeyDown(key, ImGuiKeyOwner_Any);
9941}
9942
9943bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9944{
9945 const ImGuiKeyData* key_data = GetKeyData(key);
9946 if (!key_data->Down)
9947 return false;
9948 if (!TestKeyOwner(key, owner_id))
9949 return false;
9950 return true;
9951}
9952
9953bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9954{
9955 return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9956}
9957
9958// Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9959bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9960{
9961 const ImGuiKeyData* key_data = GetKeyData(key);
9962 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)
9963 return false;
9964 const float t = key_data->DownDuration;
9965 if (t < 0.0f)
9966 return false;
9967 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9968 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9969 flags |= ImGuiInputFlags_Repeat;
9970
9971 bool pressed = (t == 0.0f);
9972 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9973 {
9974 float repeat_delay, repeat_rate;
9975 GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9976 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9977 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9978 {
9979 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9980 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9981 ImGuiContext& g = *GImGui;
9982 double key_pressed_time = g.Time - t + 0.00001f;
9983 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9984 pressed = false;
9985 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9986 pressed = false;
9987 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9988 pressed = false;
9989 }
9990 }
9991 if (!pressed)
9992 return false;
9993 if (!TestKeyOwner(key, owner_id))
9994 return false;
9995 return true;
9996}
9997
9998bool ImGui::IsKeyReleased(ImGuiKey key)
9999{
10000 return IsKeyReleased(key, ImGuiKeyOwner_Any);
10001}
10002
10003bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
10004{
10005 const ImGuiKeyData* key_data = GetKeyData(key);
10006 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
10007 return false;
10008 if (!TestKeyOwner(key, owner_id))
10009 return false;
10010 return true;
10011}
10012
10013bool ImGui::IsMouseDown(ImGuiMouseButton button)
10014{
10015 ImGuiContext& g = *GImGui;
10016 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10017 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.
10018}
10019
10020bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
10021{
10022 ImGuiContext& g = *GImGui;
10023 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10024 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.
10025}
10026
10027bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
10028{
10029 return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10030}
10031
10032bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
10033{
10034 ImGuiContext& g = *GImGui;
10035 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10036 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)
10037 return false;
10038 const float t = g.IO.MouseDownDuration[button];
10039 if (t < 0.0f)
10040 return false;
10041 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
10042
10043 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
10044 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
10045 if (!pressed)
10046 return false;
10047
10048 if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
10049 return false;
10050
10051 return true;
10052}
10053
10054bool ImGui::IsMouseReleased(ImGuiMouseButton button)
10055{
10056 ImGuiContext& g = *GImGui;
10057 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10058 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
10059}
10060
10061bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
10062{
10063 ImGuiContext& g = *GImGui;
10064 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10065 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
10066}
10067
10068
10069// Prefer higher-level helper GetItemClickedCountWithSingleClickDelay()
10070// Use if you absolutely need to distinguish single-click from double-click by introducing a delay.
10071// Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test.
10072// This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
10073bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay)
10074{
10075 ImGuiContext& g = *GImGui;
10076 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10077 if (IsMouseDown(button))
10078 return false;
10079 if (delay < 0.0f)
10080 delay = g.IO.MouseSingleClickDelay;
10081 const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]);
10082 return (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay);
10083}
10084
10085bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
10086{
10087 ImGuiContext& g = *GImGui;
10088 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10089 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
10090}
10091
10092bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
10093{
10094 ImGuiContext& g = *GImGui;
10095 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10096 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
10097}
10098
10099int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
10100{
10101 ImGuiContext& g = *GImGui;
10102 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10103 return g.IO.MouseClickedCount[button];
10104}
10105
10106// FIXME: This is close to what BeginDragDropSource() is doing, maybe rework.
10107static ImGuiID LastItemOverlayButtonForNullId(ImGuiMouseButton mouse_button)
10108{
10109 ImGuiContext& g = *GImGui;
10110 IM_ASSERT(g.LastItemData.ID == 0);
10111 ImGuiWindow* window = g.CurrentWindow;
10112 ImGuiID id = window->GetIDFromRectangle(g.LastItemData.Rect);
10113 if (g.IO.MouseClicked[mouse_button] && ImGui::ItemHoverable(g.LastItemData.Rect, id, g.LastItemData.ItemFlags))
10114 {
10115 ImGui::SetActiveID(id, window);
10116 ImGui::FocusWindow(window);
10117 }
10118 else if (g.ActiveId == id)
10119 {
10120 ImGui::KeepAliveID(id);
10121 if (!g.IO.MouseDown[mouse_button])
10122 ImGui::ClearActiveID();
10123 }
10124 return id;
10125}
10126
10127// [BETA] Building block for disambiguation between single-click and double-click.
10128// - Returns 1 on single-click but delayed by io.MouseSingleClickDelay (which is always > io.MouseDoubleClickTime) after mouse release.
10129// - Returns 2+ on double-click and subsequent repeated clicks.
10130// In order use that to replicate Windows Explorer's "click on label to rename after a delay",
10131// When the function returns 1 for a delayed single click, you can add with further tests:
10132// - If you want to test that the mouse position AT THE TIME of the click (before the delay): you can use the 'io.MouseClickedPos[mouse_button]' position.
10133// - If you want to test that the mouse position is still over the item at the end of delay: you can use '&& IsItemHovered()'.
10134// - If you want to test that the item was selected or the sole selection AT THE TIME of the click (before the delay): you can test for 'g.LastActiveIdWasSelected' or 'g.LastActiveIdWasSoleSelected'.
10135// e.g.
10136// int click_count = ImGui::GetItemClickedCountWithSingleClickDelay(mouse_button);
10137// if (click_count == 1 && ImGui::GetCurrentContext()->LastActiveIdWasSoleSelected)
10138// StartRename();
10139// if (click_count == 2)
10140// Launch();
10141int ImGui::GetItemClickedCountWithSingleClickDelay(ImGuiMouseButton mouse_button, float delay)
10142{
10143 // Action: double-click and subsequent clicks
10144 ImGuiContext& g = *GImGui;
10145 if (g.IO.MouseClickedCount[mouse_button] >= 2 && IsItemClicked(mouse_button))
10146 return g.IO.MouseClickedCount[mouse_button];
10147
10148 // Action: second click, delayed
10149 ImGuiID id = g.LastItemData.ID;
10150 if (id == 0)
10151 id = LastItemOverlayButtonForNullId(mouse_button);
10152 if (g.LastActiveId == id)
10153 {
10154 if (delay >= 0.0f)
10155 delay = ImMax(delay, g.IO.MouseDoubleClickTime + 0.01f);
10156 if (IsMouseReleasedWithDelay(mouse_button, delay) && g.IO.MouseClickedLastCount[mouse_button] == 1)
10157 return 1;
10158 }
10159 return 0;
10160}
10161
10162// Test if mouse cursor is hovering given rectangle
10163// NB- Rectangle is clipped by our current clip setting
10164// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
10165bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
10166{
10167 ImGuiContext& g = *GImGui;
10168
10169 // Clip
10170 ImRect rect_clipped(r_min, r_max);
10171 if (clip)
10172 rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
10173
10174 // Hit testing, expanded for touch input
10175 if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
10176 return false;
10177 return true;
10178}
10179
10180// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
10181// [Internal] This doesn't test if the button is pressed
10182bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
10183{
10184 ImGuiContext& g = *GImGui;
10185 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10186 if (lock_threshold < 0.0f)
10187 lock_threshold = g.IO.MouseDragThreshold;
10188 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
10189}
10190
10191bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
10192{
10193 ImGuiContext& g = *GImGui;
10194 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10195 if (!g.IO.MouseDown[button])
10196 return false;
10197 return IsMouseDragPastThreshold(button, lock_threshold);
10198}
10199
10200ImVec2 ImGui::GetMousePos()
10201{
10202 ImGuiContext& g = *GImGui;
10203 return g.IO.MousePos;
10204}
10205
10206// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
10207// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
10208void ImGui::TeleportMousePos(const ImVec2& pos)
10209{
10210 ImGuiContext& g = *GImGui;
10211 g.IO.MousePos = g.IO.MousePosPrev = pos;
10212 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
10213 g.IO.WantSetMousePos = true;
10214 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
10215}
10216
10217// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
10218ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
10219{
10220 ImGuiContext& g = *GImGui;
10221 if (g.BeginPopupStack.Size > 0)
10222 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
10223 return g.IO.MousePos;
10224}
10225
10226// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
10227bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
10228{
10229 // The assert is only to silence a false-positive in XCode Static Analysis.
10230 // 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).
10231 IM_ASSERT(GImGui != NULL);
10232 const float MOUSE_INVALID = -256000.0f;
10233 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
10234 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
10235}
10236
10237// [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.
10238bool ImGui::IsAnyMouseDown()
10239{
10240 ImGuiContext& g = *GImGui;
10241 for (int n = 0; n < IM_COUNTOF(g.IO.MouseDown); n++)
10242 if (g.IO.MouseDown[n])
10243 return true;
10244 return false;
10245}
10246
10247// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
10248// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
10249// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
10250ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
10251{
10252 ImGuiContext& g = *GImGui;
10253 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10254 if (lock_threshold < 0.0f)
10255 lock_threshold = g.IO.MouseDragThreshold;
10256 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
10257 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
10258 if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
10259 return g.IO.MousePos - g.IO.MouseClickedPos[button];
10260 return ImVec2(0.0f, 0.0f);
10261}
10262
10263void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
10264{
10265 ImGuiContext& g = *GImGui;
10266 IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown));
10267 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
10268 g.IO.MouseClickedPos[button] = g.IO.MousePos;
10269}
10270
10271// Get desired mouse cursor shape.
10272// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
10273// updated during the frame, and locked in EndFrame()/Render().
10274// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
10275ImGuiMouseCursor ImGui::GetMouseCursor()
10276{
10277 ImGuiContext& g = *GImGui;
10278 return g.MouseCursor;
10279}
10280
10281// We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
10282// 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
10283// handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
10284void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
10285{
10286 ImGuiContext& g = *GImGui;
10287 g.MouseCursor = cursor_type;
10288}
10289
10290static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
10291{
10292 IM_ASSERT(ImGui::IsAliasKey(key));
10293 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
10294 key_data->Down = v;
10295 key_data->AnalogValue = analog_value;
10296}
10297
10298// [Internal] Do not use directly
10299static ImGuiKeyChord GetMergedModsFromKeys()
10300{
10301 // Bypass IsKeyDown() for the unlikely case where user used a ImGuiInputFlags_LockXXXX on those.
10302 ImGuiKeyChord mods = 0;
10303 if (ImGui::GetKeyData(ImGuiMod_Ctrl)->Down) { mods |= ImGuiMod_Ctrl; }
10304 if (ImGui::GetKeyData(ImGuiMod_Shift)->Down) { mods |= ImGuiMod_Shift; }
10305 if (ImGui::GetKeyData(ImGuiMod_Alt)->Down) { mods |= ImGuiMod_Alt; }
10306 if (ImGui::GetKeyData(ImGuiMod_Super)->Down) { mods |= ImGuiMod_Super; }
10307 return mods;
10308}
10309
10310static void ImGui::UpdateKeyboardInputs()
10311{
10312 ImGuiContext& g = *GImGui;
10313 ImGuiIO& io = g.IO;
10314
10315 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10316 io.ClearInputKeys();
10317
10318 // Update aliases
10319 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
10320 UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
10321 UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
10322 UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
10323
10324 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
10325 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10326 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10327 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
10328 const ImGuiKeyChord prev_key_mods = io.KeyMods;
10329 io.KeyMods = GetMergedModsFromKeys();
10330 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
10331 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
10332 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
10333 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
10334 if (prev_key_mods != io.KeyMods)
10335 g.LastKeyModsChangeTime = g.Time;
10336 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
10337 g.LastKeyModsChangeFromNoneTime = g.Time;
10338
10339 // Clear gamepad data if disabled
10340 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
10341 for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
10342 {
10343 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
10344 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
10345 }
10346
10347 // Update keys
10348 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
10349 {
10350 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10351 key_data->DownDurationPrev = key_data->DownDuration;
10352 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
10353 if (key_data->DownDuration == 0.0f)
10354 {
10355 if (IsKeyboardKey((ImGuiKey)key))
10356 g.LastKeyboardKeyPressTime = g.Time;
10357 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
10358 g.LastKeyboardKeyPressTime = g.Time;
10359 }
10360 }
10361
10362 // Update keys/input owner (named keys only): one entry per key
10363 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
10364 {
10365 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10366 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
10367 owner_data->OwnerCurr = owner_data->OwnerNext;
10368 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.
10369 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
10370 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
10371 }
10372
10373 // Update key routing (for e.g. shortcuts)
10374 UpdateKeyRoutingTable(&g.KeysRoutingTable);
10375}
10376
10377static void ImGui::UpdateMouseInputs()
10378{
10379 ImGuiContext& g = *GImGui;
10380 ImGuiIO& io = g.IO;
10381
10382 // Mouse Wheel swapping flag
10383 // As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead
10384 // - We avoid doing it on OSX as it the OS input layer handles this already.
10385 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
10386 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
10387 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
10388
10389 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
10390 if (IsMousePosValid(&io.MousePos))
10391 io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
10392
10393 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
10394 if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
10395 io.MouseDelta = io.MousePos - io.MousePosPrev;
10396 else
10397 io.MouseDelta = ImVec2(0.0f, 0.0f);
10398
10399 // Update stationary timer.
10400 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
10401 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
10402 const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
10403 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
10404 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
10405
10406 // 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.
10407 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
10408 g.NavHighlightItemUnderNav = false;
10409
10410 for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++)
10411 {
10412 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
10413 io.MouseClickedCount[i] = 0; // Will be filled below
10414 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
10415 if (io.MouseReleased[i])
10416 io.MouseReleasedTime[i] = g.Time;
10417 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
10418 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
10419 if (io.MouseClicked[i])
10420 {
10421 bool is_repeated_click = false;
10422 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
10423 {
10424 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10425 if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
10426 is_repeated_click = true;
10427 }
10428 if (is_repeated_click)
10429 io.MouseClickedLastCount[i]++;
10430 else
10431 io.MouseClickedLastCount[i] = 1;
10432 io.MouseClickedTime[i] = g.Time;
10433 io.MouseClickedPos[i] = io.MousePos;
10434 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10435 io.MouseDragMaxDistanceSqr[i] = 0.0f;
10436 }
10437 else if (io.MouseDown[i])
10438 {
10439 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10440 float delta_sqr_click_pos = IsMousePosValid(&io.MousePos) ? ImLengthSqr(io.MousePos - io.MouseClickedPos[i]) : 0.0f;
10441 io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], delta_sqr_click_pos);
10442 }
10443
10444 // We provide io.MouseDoubleClicked[] as a legacy service
10445 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10446
10447 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
10448 if (io.MouseClicked[i])
10449 g.NavHighlightItemUnderNav = false;
10450 }
10451}
10452
10453static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10454{
10455 ImGuiContext& g = *GImGui;
10456 if (window)
10457 g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10458 else
10459 g.WheelingWindowReleaseTimer = 0.0f;
10460 if (g.WheelingWindow == window)
10461 return;
10462 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10463 g.WheelingWindow = window;
10464 g.WheelingWindowRefMousePos = g.IO.MousePos;
10465 if (window == NULL)
10466 {
10467 g.WheelingWindowStartFrame = -1;
10468 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10469 }
10470}
10471
10472static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10473{
10474 // For each axis, find window in the hierarchy that may want to use scrolling
10475 ImGuiContext& g = *GImGui;
10476 ImGuiWindow* windows[2] = { NULL, NULL };
10477 for (int axis = 0; axis < 2; axis++)
10478 if (wheel[axis] != 0.0f)
10479 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10480 {
10481 // Bubble up into parent window if:
10482 // - a child window doesn't allow any scrolling.
10483 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10484 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10485 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10486 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10487 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10488 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10489 break; // select this window
10490 }
10491 if (windows[0] == NULL && windows[1] == NULL)
10492 return NULL;
10493
10494 // If there's only one window or only one axis then there's no ambiguity
10495 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10496 return windows[1] ? windows[1] : windows[0];
10497
10498 // If candidate are different windows we need to decide which one to prioritize
10499 // - First frame: only find a winner if one axis is zero.
10500 // - Subsequent frames: only find a winner when one is more than the other.
10501 if (g.WheelingWindowStartFrame == -1)
10502 g.WheelingWindowStartFrame = g.FrameCount;
10503 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10504 {
10505 g.WheelingWindowWheelRemainder = wheel;
10506 return NULL;
10507 }
10508 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10509}
10510
10511// Called by NewFrame()
10512void ImGui::UpdateMouseWheel()
10513{
10514 // Reset the locked window if we move the mouse or after the timer elapses.
10515 // 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)
10516 ImGuiContext& g = *GImGui;
10517 if (g.WheelingWindow != NULL)
10518 {
10519 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10520 if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10521 g.WheelingWindowReleaseTimer = 0.0f;
10522 if (g.WheelingWindowReleaseTimer <= 0.0f)
10523 LockWheelingWindow(NULL, 0.0f);
10524 }
10525
10526 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10527 if (!mouse_window || mouse_window->Collapsed)
10528 return;
10529
10530 ImGuiID owner_id = mouse_window->ID;
10531 ImVec2 wheel;
10532 wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, owner_id) ? g.IO.MouseWheelH : 0.0f;
10533 wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, owner_id) ? g.IO.MouseWheel : 0.0f;
10534 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10535 if (g.WheelingWindow != NULL)
10536 {
10537 SetKeyOwner(ImGuiKey_MouseWheelX, owner_id);
10538 SetKeyOwner(ImGuiKey_MouseWheelY, owner_id);
10539 }
10540
10541 // Zoom / Scale window
10542 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10543 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10544 {
10545 LockWheelingWindow(mouse_window, wheel.y);
10546 ImGuiWindow* window = mouse_window;
10547 const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10548 const float scale = new_font_scale / window->FontWindowScale;
10549 window->FontWindowScale = new_font_scale;
10550 if (window == window->RootWindow)
10551 {
10552 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10553 SetWindowPos(window, window->Pos + offset, 0);
10554 window->Size = ImTrunc(window->Size * scale); // FIXME: Legacy-ish code, call SetWindowSize()?
10555 window->SizeFull = ImTrunc(window->SizeFull * scale);
10556 MarkIniSettingsDirty(window);
10557 }
10558 return;
10559 }
10560 if (g.IO.KeyCtrl)
10561 return;
10562
10563 // Mouse wheel scrolling
10564 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10565 if (g.IO.MouseWheelRequestAxisSwap)
10566 wheel = ImVec2(wheel.y, 0.0f);
10567
10568 // Maintain a rough average of moving magnitude on both axes
10569 // FIXME: should by based on wall clock time rather than frame-counter
10570 g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10571 g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10572
10573 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10574 wheel += g.WheelingWindowWheelRemainder;
10575 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10576 if (wheel.x == 0.0f && wheel.y == 0.0f)
10577 return;
10578
10579 // Mouse wheel scrolling: find target and apply
10580 // - don't renew lock if axis doesn't apply on the window.
10581 // - select a main axis when both axes are being moved.
10582 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10583 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10584 {
10585 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10586 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10587 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10588 if (do_scroll[ImGuiAxis_X])
10589 {
10590 LockWheelingWindow(window, wheel.x);
10591 float max_step = window->InnerRect.GetWidth() * 0.67f;
10592 float scroll_step = ImTrunc(ImMin(2 * window->FontRefSize, max_step));
10593 SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10594 g.WheelingWindowScrolledFrame = g.FrameCount;
10595 }
10596 if (do_scroll[ImGuiAxis_Y])
10597 {
10598 LockWheelingWindow(window, wheel.y);
10599 float max_step = window->InnerRect.GetHeight() * 0.67f;
10600 float scroll_step = ImTrunc(ImMin(5 * window->FontRefSize, max_step));
10601 SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10602 g.WheelingWindowScrolledFrame = g.FrameCount;
10603 }
10604 }
10605}
10606
10607void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10608{
10609 ImGuiContext& g = *GImGui;
10610 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10611}
10612
10613void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10614{
10615 ImGuiContext& g = *GImGui;
10616 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10617}
10618
10619#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10620static const char* GetInputSourceName(ImGuiInputSource source)
10621{
10622 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10623 IM_ASSERT(IM_COUNTOF(input_source_names) == ImGuiInputSource_COUNT);
10624 if (source < 0 || source >= ImGuiInputSource_COUNT)
10625 return "Unknown";
10626 return input_source_names[source];
10627}
10628static const char* GetMouseSourceName(ImGuiMouseSource source)
10629{
10630 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10631 IM_ASSERT(IM_COUNTOF(mouse_source_names) == ImGuiMouseSource_COUNT);
10632 if (source < 0 || source >= ImGuiMouseSource_COUNT)
10633 return "Unknown";
10634 return mouse_source_names[source];
10635}
10636static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10637{
10638 ImGuiContext& g = *GImGui;
10639 char buf[5];
10640 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; }
10641 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; }
10642 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; }
10643 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; }
10644 if (e->Type == ImGuiInputEventType_Text) { ImTextCharToUtf8(buf, e->Text.Char); IMGUI_DEBUG_LOG_IO("[io] %s: Text: '%s' (U+%08X)\n", prefix, buf, e->Text.Char); return; }
10645 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10646}
10647#endif
10648
10649// Process input queue
10650// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10651// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10652// - 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)
10653void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10654{
10655 ImGuiContext& g = *GImGui;
10656 ImGuiIO& io = g.IO;
10657
10658 // Only trickle chars<>key when working with InputText()
10659 // FIXME: InputText() could parse event trail?
10660 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10661 const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10662
10663 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
10664 int mouse_button_changed = 0x00;
10665 ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
10666
10667 int event_n = 0;
10668 for (; event_n < g.InputEventsQueue.Size; event_n++)
10669 {
10670 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10671 if (e->Type == ImGuiInputEventType_MousePos)
10672 {
10673 if (g.IO.WantSetMousePos)
10674 continue;
10675 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10676 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10677 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10678 break;
10679 io.MousePos = event_pos;
10680 io.MouseSource = e->MousePos.MouseSource;
10681 mouse_moved = true;
10682 }
10683 else if (e->Type == ImGuiInputEventType_MouseButton)
10684 {
10685 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10686 const ImGuiMouseButton button = e->MouseButton.Button;
10687 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10688 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10689 break;
10690 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10691 break;
10692 io.MouseDown[button] = e->MouseButton.Down;
10693 io.MouseSource = e->MouseButton.MouseSource;
10694 mouse_button_changed |= (1 << button);
10695 }
10696 else if (e->Type == ImGuiInputEventType_MouseWheel)
10697 {
10698 // Trickling Rule: Stop processing queued events if we got multiple action on the event
10699 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10700 break;
10701 io.MouseWheelH += e->MouseWheel.WheelX;
10702 io.MouseWheel += e->MouseWheel.WheelY;
10703 io.MouseSource = e->MouseWheel.MouseSource;
10704 mouse_wheeled = true;
10705 }
10706 else if (e->Type == ImGuiInputEventType_Key)
10707 {
10708 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10709 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10710 continue;
10711 ImGuiKey key = e->Key.Key;
10712 IM_ASSERT(key != ImGuiKey_None);
10713 ImGuiKeyData* key_data = GetKeyData(key);
10714 const int key_data_index = (int)(key_data - g.IO.KeysData);
10715 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || mouse_button_changed != 0))
10716 break;
10717
10718 const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(GetMergedModsFromKeys() | key);
10719 if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
10720 break;
10721
10722 if (key_data->Down != e->Key.Down) // Analog change only do not trigger this, so it won't block e.g. further mouse pos events testing key_changed.
10723 {
10724 key_changed = true;
10725 key_changed_mask.SetBit(key_data_index);
10726 if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
10727 key_changed_nonchar = true;
10728 }
10729
10730 key_data->Down = e->Key.Down;
10731 key_data->AnalogValue = e->Key.AnalogValue;
10732 }
10733 else if (e->Type == ImGuiInputEventType_Text)
10734 {
10735 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10736 continue;
10737 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10738 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10739 break;
10740 if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar)
10741 break;
10742 unsigned int c = e->Text.Char;
10743 io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10744 if (trickle_interleaved_nonchar_keys_and_text)
10745 text_inputted = true;
10746 }
10747 else if (e->Type == ImGuiInputEventType_Focus)
10748 {
10749 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10750 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10751 const bool focus_lost = !e->AppFocused.Focused;
10752 io.AppFocusLost = focus_lost;
10753 }
10754 else
10755 {
10756 IM_ASSERT(0 && "Unknown event!");
10757 }
10758 }
10759
10760 // Record trail (for domain-specific applications wanting to access a precise trail)
10761 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10762 for (int n = 0; n < event_n; n++)
10763 g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10764
10765 // [DEBUG]
10766#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10767 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10768 for (int n = 0; n < g.InputEventsQueue.Size; n++)
10769 DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10770#endif
10771
10772 // Remaining events will be processed on the next frame
10773 // FIXME-MULTITHREADING: io.AddKeyEvent() etc. calls are mostly thread-safe apart from the fact they push to this
10774 // queue which may be resized here. Could potentially rework this to narrow down the section needing a mutex? (#5772)
10775 if (event_n == g.InputEventsQueue.Size)
10776 g.InputEventsQueue.resize(0);
10777 else
10778 g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10779
10780 // Clear buttons state when focus is lost
10781 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10782 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10783 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10784 if (g.IO.AppFocusLost)
10785 {
10786 g.IO.ClearInputKeys();
10787 g.IO.ClearInputMouse();
10788 }
10789}
10790
10791ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10792{
10793 if (!IsNamedKeyOrMod(key))
10794 return ImGuiKeyOwner_NoOwner;
10795
10796 ImGuiContext& g = *GImGui;
10797 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10798 ImGuiID owner_id = owner_data->OwnerCurr;
10799
10800 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10801 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10802 return ImGuiKeyOwner_NoOwner;
10803
10804 return owner_id;
10805}
10806
10807// TestKeyOwner(..., ID) : (owner == None || owner == ID)
10808// TestKeyOwner(..., None) : (owner == None)
10809// TestKeyOwner(..., Any) : no owner test
10810// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10811bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10812{
10813 if (!IsNamedKeyOrMod(key))
10814 return true;
10815
10816 ImGuiContext& g = *GImGui;
10817 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10818 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10819 return false;
10820
10821 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10822 if (owner_id == ImGuiKeyOwner_Any)
10823 return owner_data->LockThisFrame == false;
10824
10825 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10826 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10827 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10828 if (owner_data->OwnerCurr != owner_id)
10829 {
10830 if (owner_data->LockThisFrame)
10831 return false;
10832 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10833 return false;
10834 }
10835
10836 return true;
10837}
10838
10839// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10840// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10841// - SetKeyOwner(..., None) : clears owner
10842// - SetKeyOwner(..., Any, !Lock) : illegal (assert)
10843// - SetKeyOwner(..., Any or None, Lock) : set lock
10844// Ownership is automatically released on the frame after a release, see code in UpdateKeyboardInputs().
10845void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10846{
10847 ImGuiContext& g = *GImGui;
10848 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)
10849 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10850 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10851
10852 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10853 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10854
10855 // We cannot lock by default as it would likely break lots of legacy code.
10856 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10857 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10858 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10859}
10860
10861// Rarely used helper
10862void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10863{
10864 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10865 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10866 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10867 if (key_chord & ImGuiMod_Super) { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10868 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10869}
10870
10871// This is more or less equivalent to a fancier version of:
10872// if (IsItemHovered() || IsItemActive())
10873// SetKeyOwner(key, GetItemID());
10874// 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.
10875// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10876// 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.
10877bool ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10878{
10879 ImGuiContext& g = *GImGui;
10880 ImGuiID id = g.LastItemData.ID;
10881 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10882 return false;
10883 if ((flags & ImGuiInputFlags_CondMask_) == 0)
10884 flags |= ImGuiInputFlags_CondDefault_;
10885 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10886 {
10887 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10888 if (!TestKeyOwner(key, id))
10889 return false;
10890 SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10891 return true;
10892 }
10893 return false;
10894}
10895
10896bool ImGui::SetItemKeyOwner(ImGuiKey key)
10897{
10898 return SetItemKeyOwner(key, ImGuiInputFlags_None);
10899}
10900
10901// This is the only public API until we expose owner_id versions of the API as replacements.
10902bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10903{
10904 return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10905}
10906
10907// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10908bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10909{
10910 ImGuiContext& g = *GImGui;
10911 key_chord = FixupKeyChord(key_chord);
10912 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10913 if (g.IO.KeyMods != mods)
10914 return false;
10915
10916 // Special storage location for mods
10917 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10918 if (key == ImGuiKey_None)
10919 key = ConvertSingleModFlagToKey(mods);
10920 if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10921 return false;
10922 return true;
10923}
10924
10925void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10926{
10927 ImGuiContext& g = *GImGui;
10928 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
10929 g.NextItemData.Shortcut = key_chord;
10930 g.NextItemData.ShortcutFlags = flags;
10931}
10932
10933// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10934void ImGui::ItemHandleShortcut(ImGuiID id)
10935{
10936 ImGuiContext& g = *GImGui;
10937 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10938 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10939
10940 if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
10941 return;
10942 if (flags & ImGuiInputFlags_Tooltip)
10943 {
10944 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10945 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10946 }
10947 if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10948 return;
10949
10950 // FIXME: Generalize Activation queue?
10951 g.NavActivateId = id; // Will effectively disable clipping.
10952 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10953 //if (g.ActiveId == 0 || g.ActiveId == id)
10954 g.NavActivateDownId = g.NavActivatePressedId = id;
10955 NavHighlightActivated(id);
10956}
10957
10958bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10959{
10960 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10961}
10962
10963bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10964{
10965 ImGuiContext& g = *GImGui;
10966 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10967
10968 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10969 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10970 flags |= ImGuiInputFlags_RouteFocused;
10971
10972 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10973 // Effectively makes Shortcut() always input-owner aware.
10974 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10975 owner_id = GetRoutingIdFromOwnerId(owner_id);
10976
10977 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10978 return false;
10979
10980 // Submit route
10981 if (!SetShortcutRouting(key_chord, flags, owner_id))
10982 return false;
10983
10984 // Default repeat behavior for Shortcut()
10985 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10986 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10987 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10988
10989 if (!IsKeyChordPressed(key_chord, flags, owner_id))
10990 return false;
10991
10992 // Claim mods during the press
10993 SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10994
10995 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10996 return true;
10997}
10998
10999//-----------------------------------------------------------------------------
11000// [SECTION] ERROR CHECKING, STATE RECOVERY
11001//-----------------------------------------------------------------------------
11002// - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
11003// - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11004// - ErrorCheckNewFrameSanityChecks()
11005// - ErrorCheckEndFrameSanityChecks()
11006// - ErrorRecoveryStoreState()
11007// - ErrorRecoveryTryToRecoverState()
11008// - ErrorRecoveryTryToRecoverWindowState()
11009// - ErrorLog()
11010//-----------------------------------------------------------------------------
11011
11012// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
11013// Called by IMGUI_CHECKVERSION().
11014// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
11015// If this triggers you have mismatched headers and compiled code versions.
11016// - It could be because of a build issue (using new headers with old compiled code)
11017// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
11018// THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
11019// Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
11020// Otherwise it is possible that different compilation units would see different structure layout.
11021// If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
11022bool 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)
11023{
11024 bool error = false;
11025 if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
11026 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
11027 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
11028 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
11029 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
11030 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
11031 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
11032 return !error;
11033}
11034
11035// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos()
11036// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing
11037// windows, table column contents size used for auto-resizing columns, group size).
11038// This was causing issues and ambiguities and we needed to retire that.
11039// 2022/08/05 (1.89): extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED. However we gated the new logic behind a '#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS' block.
11040// 2025/06/25 (1.92): removed the legacy path and turned into an assert. It was a mistake that there was a #ifndef before: our obsolescence schedule gets pushed back a bit more :(
11041//
11042// Previously this would make the window content size ~200x200:
11043// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE
11044// Instead, please submit an item:
11045// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
11046// Alternative:
11047// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
11048//
11049// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item,
11050// and with a position that would grow the parent contents size.
11051//
11052// Advanced:
11053// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos())
11054// had a side-effect on layout! In particular this caused problem to compute group boundaries.
11055// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the
11056// group to be taller because auto-sizing generally adds padding on bottom and right side.
11057// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect.
11058// Using vertical alignment patterns would frequently trigger this sorts of issue.
11059// - See https://github.com/ocornut/imgui/issues/5548 for more details.
11060void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11061{
11062 ImGuiContext& g = *GImGui;
11063 ImGuiWindow* window = g.CurrentWindow;
11064 IM_ASSERT(window->DC.IsSetPos);
11065 window->DC.IsSetPos = false;
11066 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
11067 return;
11068 if (window->SkipItems)
11069 return;
11070 IM_ASSERT_USER_ERROR(0, "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries.\nPlease submit an item e.g. Dummy() afterwards in order to grow window/parent boundaries.");
11071
11072 // For reference, the old behavior was essentially:
11073 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11074}
11075
11076static void ImGui::ErrorCheckNewFrameSanityChecks()
11077{
11078 ImGuiContext& g = *GImGui;
11079
11080 // Check user IM_ASSERT macro
11081 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
11082 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
11083 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
11084 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
11085 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
11086 if (true) IM_ASSERT(1); else IM_ASSERT(0);
11087
11088 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
11089 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
11090#ifdef __EMSCRIPTEN__
11091 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
11092 g.IO.DeltaTime = 0.00001f;
11093#endif
11094
11095 // Check user data
11096 // (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)
11097 IM_ASSERT(g.Initialized);
11098 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
11099 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
11100 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
11101 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
11102 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
11103 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
11104 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!");
11105 IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders.
11106 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
11107 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
11108 IM_ASSERT(ImIsPowerOfTwo(g.IO.ConfigColorEditFlags & ImGuiColorEditFlags_DisplayMask_)); // Check only 1 option is selected
11109 IM_ASSERT(ImIsPowerOfTwo(g.IO.ConfigColorEditFlags & ImGuiColorEditFlags_DataTypeMask_)); // "
11110 IM_ASSERT(ImIsPowerOfTwo(g.IO.ConfigColorEditFlags & ImGuiColorEditFlags_PickerMask_)); // "
11111 IM_ASSERT(ImIsPowerOfTwo(g.IO.ConfigColorEditFlags & ImGuiColorEditFlags_InputMask_)); // "
11112
11113 IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes);
11114 IM_ASSERT(g.IO.MouseSingleClickDelay > g.IO.MouseDoubleClickTime);
11115
11116 // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
11117 if (g.IO.ConfigErrorRecovery)
11118 IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
11119
11120#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11121 if (g.IO.FontGlobalScale > 1.0f)
11122 IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!");
11123
11124 // Remap legacy names
11125 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
11126 {
11127 g.IO.ConfigNavMoveSetMousePos = true;
11128 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
11129 }
11130 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
11131 {
11132 g.IO.ConfigNavCaptureKeyboard = false;
11133 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
11134 }
11135
11136 // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
11137 if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
11138 g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
11139 if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
11140 g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); };
11141#endif
11142}
11143
11144static void ImGui::ErrorCheckEndFrameSanityChecks()
11145{
11146 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
11147 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
11148 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
11149 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
11150 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
11151 // while still correctly asserting on mid-frame key press events.
11152 ImGuiContext& g = *GImGui;
11153 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
11154 IM_UNUSED(g);
11155 IM_UNUSED(key_mods);
11156 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
11157 IM_UNUSED(key_mods);
11158
11159 IM_ASSERT(g.CurrentWindowStack.Size == 1);
11160 IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
11161}
11162
11163// Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
11164void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
11165{
11166 ImGuiContext& g = *GImGui;
11167 state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
11168 state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
11169 state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
11170 state_out->SizeOfColorStack = (short)g.ColorStack.Size;
11171 state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
11172 state_out->SizeOfFontStack = (short)g.FontStack.Size;
11173 state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
11174 state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
11175 state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
11176 state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
11177 state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
11178}
11179
11180// Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
11181// Called by e.g. EndFrame() but may be called for manual recovery.
11182// Attempt to recover full window stack.
11183void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
11184{
11185 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
11186 ImGuiContext& g = *GImGui;
11187 while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
11188 {
11189 // Recap:
11190 // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
11191 // - Always call a matching End() for each Begin() call, regardless of its return value!
11192 // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
11193 // - We will fix that in a future major update.
11194 ImGuiWindow* window = g.CurrentWindow;
11195 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11196 {
11197 if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
11198 {
11199 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11200 EndTable();
11201 }
11202 else
11203 {
11204 IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
11205 EndChild();
11206 }
11207 }
11208 else
11209 {
11210 IM_ASSERT_USER_ERROR(0, "Missing End()");
11211 End();
11212 }
11213 }
11214 if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
11215 ErrorRecoveryTryToRecoverWindowState(state_in);
11216}
11217
11218// Called by e.g. End() but may be called for manual recovery.
11219// Read '// Error Handling [BETA]' block in imgui_internal.h for details.
11220// Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
11221void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
11222{
11223 ImGuiContext& g = *GImGui;
11224
11225 while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
11226 {
11227 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11228 EndTable();
11229 }
11230
11231 ImGuiWindow* window = g.CurrentWindow;
11232
11233 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
11234 while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
11235 {
11236 IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
11237 EndTabBar();
11238 }
11239 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
11240 {
11241 IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
11242 EndMultiSelect();
11243 }
11244 if (window->DC.MenuBarAppending) //-V1044
11245 {
11246 IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()");
11247 EndMenuBar();
11248 }
11249 while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
11250 {
11251 IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
11252 TreePop();
11253 }
11254 while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
11255 {
11256 IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
11257 EndGroup();
11258 }
11259 IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
11260 while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
11261 {
11262 IM_ASSERT_USER_ERROR(0, "Missing PopID()");
11263 PopID();
11264 }
11265 while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
11266 {
11267 IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
11268 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11269 EndDisabled();
11270 else
11271 {
11272 EndDisabledOverrideReenable();
11273 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
11274 }
11275 }
11276 IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
11277 while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
11278 {
11279 IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
11280 PopStyleColor();
11281 }
11282 while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
11283 {
11284 IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
11285 PopItemFlag();
11286 }
11287 while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
11288 {
11289 IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
11290 PopStyleVar();
11291 }
11292 while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
11293 {
11294 IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
11295 PopFont();
11296 }
11297 while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
11298 {
11299 IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
11300 PopFocusScope();
11301 }
11302 //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
11303}
11304
11305bool ImGui::ErrorLog(const char* msg)
11306{
11307 ImGuiContext& g = *GImGui;
11308
11309 // Output to debug log
11310#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11311 ImGuiWindow* window = g.CurrentWindow;
11312
11313 if (g.IO.ConfigErrorRecoveryEnableDebugLog)
11314 {
11315 if (g.ErrorFirst)
11316 IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
11317 g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
11318 IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
11319 }
11320 g.ErrorFirst = false;
11321
11322 // Output to tooltip
11323 if (g.IO.ConfigErrorRecoveryEnableTooltip)
11324 {
11325 if (g.WithinFrameScope && BeginErrorTooltip())
11326 {
11327 if (g.ErrorCountCurrentFrame < 20)
11328 {
11329 Text("In window '%s': %s", window ? window->Name : "NULL", msg);
11330 if (window && (!window->IsFallbackWindow || window->WasActive))
11331 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
11332 }
11333 if (g.ErrorCountCurrentFrame == 20)
11334 Text("(and more errors)");
11335 // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
11336 EndErrorTooltip();
11337 }
11338 g.ErrorCountCurrentFrame++;
11339 }
11340#endif
11341
11342 // Output to callback
11343 if (g.ErrorCallback != NULL)
11344 g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
11345
11346 // Return whether we should assert
11347 return g.IO.ConfigErrorRecoveryEnableAssert;
11348}
11349
11350// Display an error tooltip when same ID as HoveredId was submitted multiple times.
11351// See code in ItemHoverable() for an explanation of why we associate this error to HoveredId + code drawing of rectangles over individual items instances.
11352void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
11353{
11354#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11355 ImGuiContext& g = *GImGui;
11356 if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false)
11357 g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
11358 if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
11359 {
11360 Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
11361 BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
11362 BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
11363 //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.
11364 BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
11365 Separator();
11366 if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker)
11367 {
11368 Text("(Hold Ctrl to: use ");
11369 SameLine(0.0f, 0.0f);
11370 if (SmallButton("Item Picker"))
11371 DebugStartItemPicker();
11372 SameLine(0.0f, 0.0f);
11373 Text(" to break in item call-stack, or ");
11374 }
11375 else
11376 {
11377 Text("(Hold Ctrl to: ");
11378 }
11379 SameLine(0.0f, 0.0f);
11380 TextLinkOpenURL("read FAQ \"About ID Stack System\"", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
11381 SameLine(0.0f, 0.0f);
11382 Text(")");
11383 EndErrorTooltip();
11384 }
11385
11386 if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
11387 {
11388 Separator();
11389 Text("(Hold Ctrl to: ");
11390 SameLine(0.0f, 0.0f);
11391 if (SmallButton("Enable Asserts"))
11392 g.IO.ConfigErrorRecoveryEnableAssert = true;
11393 //SameLine();
11394 //if (SmallButton("Hide Error Tooltips"))
11395 // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
11396 SameLine(0, 0);
11397 Text(")");
11398 EndErrorTooltip();
11399 }
11400#endif
11401}
11402
11403// Pseudo-tooltip. Follow mouse until Ctrl is held. When Ctrl is held we lock position, allowing to click it.
11404bool ImGui::BeginErrorTooltip()
11405{
11406 ImGuiContext& g = *GImGui;
11407 ImGuiWindow* window = FindWindowByName("##Tooltip_Error");
11408 const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
11409 PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.15f));
11410 if (use_locked_pos)
11411 SetNextWindowPos(g.ErrorTooltipLockedPos);
11412 bool is_visible = Begin("##Tooltip_Error", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
11413 PopStyleColor();
11414 if (is_visible && g.CurrentWindow->BeginCount == 1)
11415 {
11416 SeparatorText("MESSAGE FROM DEAR IMGUI");
11417 BringWindowToDisplayFront(g.CurrentWindow);
11418 BringWindowToFocusFront(g.CurrentWindow);
11419 g.ErrorTooltipLockedPos = GetWindowPos();
11420 }
11421 else if (!is_visible)
11422 {
11423 End();
11424 }
11425 return is_visible;
11426}
11427
11428void ImGui::EndErrorTooltip()
11429{
11430 End();
11431}
11432
11433//-----------------------------------------------------------------------------
11434// [SECTION] ITEM SUBMISSION
11435//-----------------------------------------------------------------------------
11436// - KeepAliveID()
11437// - ItemAdd()
11438//-----------------------------------------------------------------------------
11439
11440// 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().
11441void ImGui::KeepAliveID(ImGuiID id)
11442{
11443 ImGuiContext& g = *GImGui;
11444 if (g.ActiveId == id)
11445 g.ActiveIdIsAlive = id;
11446 if (g.DeactivatedItemData.ID == id)
11447 g.DeactivatedItemData.IsAlive = true;
11448}
11449
11450// Declare item bounding box for clipping and interaction.
11451// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
11452// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
11453// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
11454IM_MSVC_RUNTIME_CHECKS_OFF
11455bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
11456{
11457 ImGuiContext& g = *GImGui;
11458 ImGuiWindow* window = g.CurrentWindow;
11459
11460 // Set item data
11461 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
11462 g.LastItemData.ID = id;
11463 g.LastItemData.Rect = bb;
11464 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
11465 g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlagsSet | extra_flags;
11466 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
11467 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
11468
11469 if (id != 0)
11470 {
11471 KeepAliveID(id);
11472
11473 // Directional navigation processing
11474 // Runs prior to clipping early-out
11475 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
11476 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
11477 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
11478 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
11479 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
11480 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
11481 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
11482 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
11483 if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
11484 {
11485 // FIXME-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
11486 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
11487 if (g.NavId == id || g.NavAnyRequest)
11488 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
11489 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
11490 NavProcessItem();
11491 }
11492
11493 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
11494 ItemHandleShortcut(id);
11495 }
11496
11497 // Lightweight clear of SetNextItemXXX data.
11498 g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
11499 g.NextItemData.ItemFlagsSet = ImGuiItemFlags_None;
11500
11501#ifdef IMGUI_ENABLE_TEST_ENGINE
11502 if (id != 0)
11503 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
11504#endif
11505
11506 // Clipping test
11507 // (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')
11508 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
11509 const bool is_rect_visible = bb.Overlaps(window->ClipRect);
11510 if (!is_rect_visible)
11511 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
11512 if (!g.ItemUnclipByLog)
11513 return false;
11514
11515 // [DEBUG]
11516#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11517 if (id != 0)
11518 {
11519 if (id == g.DebugLocateId)
11520 DebugLocateItemResolveWithLastItem();
11521
11522 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
11523 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
11524 // READ THE FAQ: https://dearimgui.com/faq
11525 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!");
11526
11527 // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED.
11528 // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd().
11529#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
11530 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0)
11531 {
11532 int* p_alive = g.DebugDrawIdConflictsAliveCount.GetIntRef(id, -1); // Could halve lookups if we knew ImGuiStorage can store 64-bit, or by storing FrameCount as 30-bits + highlight as 2-bits. But the point is that we should not pretend that this is fast.
11533 int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1);
11534 if (*p_alive == g.FrameCount)
11535 *p_highlight = g.FrameCount;
11536 *p_alive = g.FrameCount;
11537 if (*p_highlight >= g.FrameCount - 1)
11538 window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, 2.0f);
11539 }
11540#endif
11541 }
11542 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
11543 //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
11544 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
11545#endif
11546
11547 if (id != 0 && g.DeactivatedItemData.ID == id)
11548 g.DeactivatedItemData.ElapseFrame = g.FrameCount;
11549
11550 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
11551 if (is_rect_visible)
11552 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
11553 if (IsMouseHoveringRect(bb.Min, bb.Max))
11554 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
11555 return true;
11556}
11557IM_MSVC_RUNTIME_CHECKS_RESTORE
11558
11559//-----------------------------------------------------------------------------
11560// [SECTION] LAYOUT
11561//-----------------------------------------------------------------------------
11562// - ItemSize()
11563// - SameLine()
11564// - GetCursorScreenPos()
11565// - SetCursorScreenPos()
11566// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
11567// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
11568// - GetCursorStartPos()
11569// - Indent()
11570// - Unindent()
11571// - SetNextItemWidth()
11572// - PushItemWidth()
11573// - PushMultiItemsWidths()
11574// - PopItemWidth()
11575// - CalcItemWidth()
11576// - CalcItemSize()
11577// - GetTextLineHeight()
11578// - GetTextLineHeightWithSpacing()
11579// - GetFrameHeight()
11580// - GetFrameHeightWithSpacing()
11581// - GetContentRegionMax()
11582// - GetContentRegionAvail(),
11583// - BeginGroup()
11584// - EndGroup()
11585// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11586//-----------------------------------------------------------------------------
11587
11588// Advance cursor given item size for layout.
11589// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11590// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11591// THIS IS IN THE PERFORMANCE CRITICAL PATH.
11592IM_MSVC_RUNTIME_CHECKS_OFF
11593void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11594{
11595 ImGuiContext& g = *GImGui;
11596 ImGuiWindow* window = g.CurrentWindow;
11597 if (window->SkipItems)
11598 return;
11599
11600 // We increase the height in this function to accommodate for baseline offset.
11601 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11602 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11603 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11604
11605 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11606 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);
11607
11608 // Always align ourselves on pixel boundaries
11609 //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]
11610 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11611 window->DC.CursorPosPrevLine.y = line_y1;
11612 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
11613 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
11614 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
11615 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11616 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11617
11618 window->DC.PrevLineSize.y = line_height;
11619 window->DC.CurrLineSize.y = 0.0f;
11620 window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
11621 window->DC.CurrLineTextBaseOffset = 0.0f;
11622 window->DC.IsSameLine = window->DC.IsSetPos = false;
11623
11624 // Horizontal layout mode
11625 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11626 SameLine();
11627}
11628IM_MSVC_RUNTIME_CHECKS_RESTORE
11629
11630// Gets back to previous line and continue with horizontal layout
11631// offset_from_start_x == 0 : follow right after previous item
11632// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11633// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11634// spacing_w >= 0 : enforce spacing amount
11635void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11636{
11637 ImGuiContext& g = *GImGui;
11638 ImGuiWindow* window = g.CurrentWindow;
11639 if (window->SkipItems)
11640 return;
11641
11642 if (offset_from_start_x != 0.0f)
11643 {
11644 if (spacing_w < 0.0f)
11645 spacing_w = 0.0f;
11646 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11647 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11648 }
11649 else
11650 {
11651 if (spacing_w < 0.0f)
11652 spacing_w = g.Style.ItemSpacing.x;
11653 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11654 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11655 }
11656 window->DC.CurrLineSize = window->DC.PrevLineSize;
11657 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11658 window->DC.IsSameLine = true;
11659}
11660
11661ImVec2 ImGui::GetCursorScreenPos()
11662{
11663 ImGuiWindow* window = GetCurrentWindowRead();
11664 return window->DC.CursorPos;
11665}
11666
11667void ImGui::SetCursorScreenPos(const ImVec2& pos)
11668{
11669 ImGuiWindow* window = GetCurrentWindow();
11670 window->DC.CursorPos = pos;
11671 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11672 window->DC.IsSetPos = true;
11673}
11674
11675// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11676// 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'.
11677ImVec2 ImGui::GetCursorPos()
11678{
11679 ImGuiWindow* window = GetCurrentWindowRead();
11680 return window->DC.CursorPos - window->Pos + window->Scroll;
11681}
11682
11683float ImGui::GetCursorPosX()
11684{
11685 ImGuiWindow* window = GetCurrentWindowRead();
11686 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11687}
11688
11689float ImGui::GetCursorPosY()
11690{
11691 ImGuiWindow* window = GetCurrentWindowRead();
11692 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11693}
11694
11695void ImGui::SetCursorPos(const ImVec2& local_pos)
11696{
11697 ImGuiWindow* window = GetCurrentWindow();
11698 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11699 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11700 window->DC.IsSetPos = true;
11701}
11702
11703void ImGui::SetCursorPosX(float x)
11704{
11705 ImGuiWindow* window = GetCurrentWindow();
11706 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11707 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11708 window->DC.IsSetPos = true;
11709}
11710
11711void ImGui::SetCursorPosY(float y)
11712{
11713 ImGuiWindow* window = GetCurrentWindow();
11714 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11715 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11716 window->DC.IsSetPos = true;
11717}
11718
11719ImVec2 ImGui::GetCursorStartPos()
11720{
11721 ImGuiWindow* window = GetCurrentWindowRead();
11722 return window->DC.CursorStartPos - window->Pos;
11723}
11724
11725void ImGui::Indent(float indent_w)
11726{
11727 ImGuiContext& g = *GImGui;
11728 ImGuiWindow* window = GetCurrentWindow();
11729 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11730 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11731}
11732
11733void ImGui::Unindent(float indent_w)
11734{
11735 ImGuiContext& g = *GImGui;
11736 ImGuiWindow* window = GetCurrentWindow();
11737 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11738 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11739}
11740
11741// Affect large frame+labels widgets only.
11742void ImGui::SetNextItemWidth(float item_width)
11743{
11744 ImGuiContext& g = *GImGui;
11745 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
11746 g.NextItemData.Width = item_width;
11747}
11748
11749// FIXME: Remove the == 0.0f behavior?
11750void ImGui::PushItemWidth(float item_width)
11751{
11752 ImGuiContext& g = *GImGui;
11753 ImGuiWindow* window = g.CurrentWindow;
11754 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11755 window->DC.ItemWidth = (item_width == 0.0f ? window->DC.ItemWidthDefault : item_width);
11756 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
11757}
11758
11759void ImGui::PushMultiItemsWidths(int components, float w_full)
11760{
11761 ImGuiContext& g = *GImGui;
11762 ImGuiWindow* window = g.CurrentWindow;
11763 IM_ASSERT(components > 0);
11764 const ImGuiStyle& style = g.Style;
11765 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11766 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11767 float prev_split = w_items;
11768 for (int i = components - 1; i > 0; i--)
11769 {
11770 float next_split = IM_TRUNC(w_items * i / components);
11771 window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11772 prev_split = next_split;
11773 }
11774 window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11775 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
11776}
11777
11778void ImGui::PopItemWidth()
11779{
11780 ImGuiContext& g = *GImGui;
11781 ImGuiWindow* window = g.CurrentWindow;
11782 if (window->DC.ItemWidthStack.Size <= 0)
11783 {
11784 IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
11785 return;
11786 }
11787 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11788 window->DC.ItemWidthStack.pop_back();
11789}
11790
11791// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11792// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11793float ImGui::CalcItemWidth()
11794{
11795 ImGuiContext& g = *GImGui;
11796 ImGuiWindow* window = g.CurrentWindow;
11797 float w;
11798 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
11799 w = g.NextItemData.Width;
11800 else
11801 w = window->DC.ItemWidth;
11802 if (w < 0.0f)
11803 {
11804 float region_avail_x = GetContentRegionAvail().x;
11805 w = ImMax(1.0f, region_avail_x + w);
11806 }
11807 w = IM_TRUNC(w);
11808 return w;
11809}
11810
11811// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11812// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11813// Note that only CalcItemWidth() is publicly exposed.
11814// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11815ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11816{
11817 ImVec2 avail;
11818 if (size.x < 0.0f || size.y < 0.0f)
11819 avail = GetContentRegionAvail();
11820
11821 if (size.x == 0.0f)
11822 size.x = default_w;
11823 else if (size.x < 0.0f)
11824 size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting
11825
11826 if (size.y == 0.0f)
11827 size.y = default_h;
11828 else if (size.y < 0.0f)
11829 size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting
11830
11831 return size;
11832}
11833
11834float ImGui::GetTextLineHeight()
11835{
11836 ImGuiContext& g = *GImGui;
11837 return g.FontSize;
11838}
11839
11840float ImGui::GetTextLineHeightWithSpacing()
11841{
11842 ImGuiContext& g = *GImGui;
11843 return g.FontSize + g.Style.ItemSpacing.y;
11844}
11845
11846float ImGui::GetFrameHeight()
11847{
11848 ImGuiContext& g = *GImGui;
11849 return g.FontSize + g.Style.FramePadding.y * 2.0f;
11850}
11851
11852float ImGui::GetFrameHeightWithSpacing()
11853{
11854 ImGuiContext& g = *GImGui;
11855 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11856}
11857
11858ImVec2 ImGui::GetContentRegionAvail()
11859{
11860 ImGuiContext& g = *GImGui;
11861 ImGuiWindow* window = g.CurrentWindow;
11862 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11863 return mx - window->DC.CursorPos;
11864}
11865
11866#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11867
11868// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
11869// They are bizarre local-coordinates which don't play well with scrolling.
11870ImVec2 ImGui::GetContentRegionMax()
11871{
11872 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
11873}
11874
11875ImVec2 ImGui::GetWindowContentRegionMin()
11876{
11877 ImGuiWindow* window = GImGui->CurrentWindow;
11878 return window->ContentRegionRect.Min - window->Pos;
11879}
11880
11881ImVec2 ImGui::GetWindowContentRegionMax()
11882{
11883 ImGuiWindow* window = GImGui->CurrentWindow;
11884 return window->ContentRegionRect.Max - window->Pos;
11885}
11886#endif
11887
11888// 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.)
11889// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11890// FIXME-OPT: Could we safely early out on ->SkipItems?
11891void ImGui::BeginGroup()
11892{
11893 ImGuiContext& g = *GImGui;
11894 ImGuiWindow* window = g.CurrentWindow;
11895
11896 g.GroupStack.resize(g.GroupStack.Size + 1);
11897 ImGuiGroupData& group_data = g.GroupStack.back();
11898 group_data.WindowID = window->ID;
11899 group_data.BackupCursorPos = window->DC.CursorPos;
11900 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11901 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11902 group_data.BackupIndent = window->DC.Indent;
11903 group_data.BackupGroupOffset = window->DC.GroupOffset;
11904 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11905 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11906 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11907 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11908 group_data.BackupIsSameLine = window->DC.IsSameLine;
11909 group_data.BackupAnyIdHasBeenEditedThisFrame = g.AnyIdHasBeenEditedThisFrame;
11910 group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive;
11911 group_data.EmitItem = true;
11912
11913 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11914 window->DC.Indent = window->DC.GroupOffset;
11915 window->DC.CursorMaxPos = window->DC.CursorPos;
11916 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11917 if (g.LogEnabled)
11918 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11919}
11920
11921void ImGui::EndGroup()
11922{
11923 ImGuiContext& g = *GImGui;
11924 ImGuiWindow* window = g.CurrentWindow;
11925 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11926
11927 ImGuiGroupData& group_data = g.GroupStack.back();
11928 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11929
11930 if (window->DC.IsSetPos)
11931 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11932
11933 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
11934 ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos));
11935 window->DC.CursorPos = group_data.BackupCursorPos;
11936 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11937 window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max);
11938 window->DC.Indent = group_data.BackupIndent;
11939 window->DC.GroupOffset = group_data.BackupGroupOffset;
11940 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11941 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11942 window->DC.IsSameLine = group_data.BackupIsSameLine;
11943 if (g.LogEnabled)
11944 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11945
11946 if (!group_data.EmitItem)
11947 {
11948 g.GroupStack.pop_back();
11949 return;
11950 }
11951
11952 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.
11953 ItemSize(group_bb.GetSize());
11954 ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11955
11956 // 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.
11957 // 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.
11958 // Also if you grep for LastItemId you'll notice it is only used in that context.
11959 // (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.)
11960 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11961 const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true);
11962 if (group_contains_curr_active_id)
11963 g.LastItemData.ID = g.ActiveId;
11964 else if (group_contains_deactivated_id)
11965 g.LastItemData.ID = g.DeactivatedItemData.ID;
11966 g.LastItemData.Rect = group_bb;
11967
11968 // Forward Hovered flag
11969 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11970 if (group_contains_curr_hovered_id)
11971 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11972
11973 // Forward Edited flag
11974 if (g.AnyIdHasBeenEditedThisFrame && !group_data.BackupAnyIdHasBeenEditedThisFrame)
11975 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11976
11977 // Forward Deactivated flag
11978 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11979 if (group_contains_deactivated_id)
11980 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11981
11982 g.GroupStack.pop_back();
11983 if (g.DebugShowGroupRects)
11984 window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
11985}
11986
11987
11988//-----------------------------------------------------------------------------
11989// [SECTION] SCROLLING
11990//-----------------------------------------------------------------------------
11991
11992// Helper to snap on edges when aiming at an item very close to the edge,
11993// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11994// When we refactor the scrolling API this may be configurable with a flag?
11995// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11996static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11997{
11998 if (target <= snap_min + snap_threshold)
11999 return ImLerp(snap_min, target, center_ratio);
12000 if (target >= snap_max - snap_threshold)
12001 return ImLerp(target, snap_max, center_ratio);
12002 return target;
12003}
12004
12005static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
12006{
12007 ImVec2 scroll = window->Scroll;
12008 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
12009 for (int axis = 0; axis < 2; axis++)
12010 {
12011 if (window->ScrollTarget[axis] < FLT_MAX)
12012 {
12013 float center_ratio = window->ScrollTargetCenterRatio[axis];
12014 float scroll_target = window->ScrollTarget[axis];
12015 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
12016 {
12017 float snap_min = 0.0f;
12018 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
12019 scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
12020 }
12021 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
12022 }
12023 scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f));
12024 if (!window->Collapsed && !window->SkipItems)
12025 scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
12026 }
12027 return scroll;
12028}
12029
12030void ImGui::ScrollToItem(ImGuiScrollFlags flags)
12031{
12032 ImGuiContext& g = *GImGui;
12033 ImGuiWindow* window = g.CurrentWindow;
12034 ScrollToRectEx(window, g.LastItemData.NavRect, flags);
12035}
12036
12037void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12038{
12039 ScrollToRectEx(window, item_rect, flags);
12040}
12041
12042// Scroll to keep newly navigated item fully into view
12043ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12044{
12045 ImGuiContext& g = *GImGui;
12046 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
12047 scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
12048 scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
12049 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
12050 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
12051
12052 // Check that only one behavior is selected per axis
12053 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
12054 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
12055
12056 // Defaults
12057 ImGuiScrollFlags in_flags = flags;
12058 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
12059 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
12060 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
12061 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
12062
12063 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
12064 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
12065 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;
12066 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;
12067
12068 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
12069 {
12070 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
12071 SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
12072 else if (item_rect.Max.x >= scroll_rect.Max.x)
12073 SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
12074 }
12075 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
12076 {
12077 if (can_be_fully_visible_x)
12078 SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
12079 else
12080 SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
12081 }
12082
12083 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
12084 {
12085 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
12086 SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
12087 else if (item_rect.Max.y >= scroll_rect.Max.y)
12088 SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
12089 }
12090 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
12091 {
12092 if (can_be_fully_visible_y)
12093 SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
12094 else
12095 SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
12096 }
12097
12098 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12099 ImVec2 delta_scroll = next_scroll - window->Scroll;
12100
12101 // Also scroll parent window to keep us into view if necessary
12102 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
12103 {
12104 // FIXME-SCROLL: May be an option?
12105 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
12106 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
12107 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
12108 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
12109 delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
12110 }
12111
12112 return delta_scroll;
12113}
12114
12115float ImGui::GetScrollX()
12116{
12117 ImGuiWindow* window = GImGui->CurrentWindow;
12118 return window->Scroll.x;
12119}
12120
12121float ImGui::GetScrollY()
12122{
12123 ImGuiWindow* window = GImGui->CurrentWindow;
12124 return window->Scroll.y;
12125}
12126
12127float ImGui::GetScrollMaxX()
12128{
12129 ImGuiWindow* window = GImGui->CurrentWindow;
12130 return window->ScrollMax.x;
12131}
12132
12133float ImGui::GetScrollMaxY()
12134{
12135 ImGuiWindow* window = GImGui->CurrentWindow;
12136 return window->ScrollMax.y;
12137}
12138
12139void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
12140{
12141 window->ScrollTarget.x = scroll_x;
12142 window->ScrollTargetCenterRatio.x = 0.0f;
12143 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12144}
12145
12146void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
12147{
12148 window->ScrollTarget.y = scroll_y;
12149 window->ScrollTargetCenterRatio.y = 0.0f;
12150 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12151}
12152
12153void ImGui::SetScrollX(float scroll_x)
12154{
12155 ImGuiContext& g = *GImGui;
12156 SetScrollX(g.CurrentWindow, scroll_x);
12157}
12158
12159void ImGui::SetScrollY(float scroll_y)
12160{
12161 ImGuiContext& g = *GImGui;
12162 SetScrollY(g.CurrentWindow, scroll_y);
12163}
12164
12165// Note that a local position will vary depending on initial scroll value,
12166// This is a little bit confusing so bear with us:
12167// - local_pos = (absolution_pos - window->Pos)
12168// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
12169// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
12170// - They mostly exist because of legacy API.
12171// Following the rules above, when trying to work with scrolling code, consider that:
12172// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
12173// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
12174// 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
12175void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
12176{
12177 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
12178 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
12179 window->ScrollTargetCenterRatio.x = center_x_ratio;
12180 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12181}
12182
12183void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
12184{
12185 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
12186 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
12187 window->ScrollTargetCenterRatio.y = center_y_ratio;
12188 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12189}
12190
12191void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
12192{
12193 ImGuiContext& g = *GImGui;
12194 SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
12195}
12196
12197void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
12198{
12199 ImGuiContext& g = *GImGui;
12200 SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
12201}
12202
12203// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
12204void ImGui::SetScrollHereX(float center_x_ratio)
12205{
12206 ImGuiContext& g = *GImGui;
12207 ImGuiWindow* window = g.CurrentWindow;
12208 float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
12209 float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
12210 SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
12211
12212 // Tweak: snap on edges when aiming at an item very close to the edge
12213 window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
12214}
12215
12216// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
12217void ImGui::SetScrollHereY(float center_y_ratio)
12218{
12219 ImGuiContext& g = *GImGui;
12220 ImGuiWindow* window = g.CurrentWindow;
12221 float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
12222 float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
12223 SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
12224
12225 // Tweak: snap on edges when aiming at an item very close to the edge
12226 window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
12227}
12228
12229//-----------------------------------------------------------------------------
12230// [SECTION] TOOLTIPS
12231//-----------------------------------------------------------------------------
12232
12233bool ImGui::BeginTooltip()
12234{
12235 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
12236}
12237
12238bool ImGui::BeginItemTooltip()
12239{
12240 if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12241 return false;
12242 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
12243}
12244
12245bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
12246{
12247 ImGuiContext& g = *GImGui;
12248
12249 const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
12250 if (is_dragdrop_tooltip)
12251 {
12252 // Drag and Drop tooltips are positioning differently than other tooltips:
12253 // - offset visibility to increase visibility around mouse.
12254 // - never clamp within outer viewport boundary.
12255 // We call SetNextWindowPos() to enforce position and disable clamping.
12256 // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones).
12257 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
12258 const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
12259 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12260 {
12261 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);
12262 ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
12263 SetNextWindowPos(tooltip_pos, ImGuiCond_None, tooltip_pivot);
12264 }
12265
12266 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
12267 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkerboard has issue with transparent colors :(
12268 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
12269 }
12270
12271 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
12272 if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active && !IsWindowInBeginStack(g.TooltipPreviousWindow))
12273 {
12274 //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
12275 SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
12276 g.TooltipOverrideCount++;
12277 }
12278
12279 const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
12280 char window_name[32];
12281 ImFormatString(window_name, IM_COUNTOF(window_name), window_name_template, g.TooltipOverrideCount);
12282 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
12283 Begin(window_name, NULL, flags | extra_window_flags);
12284 // 2023-03-09: Added bool return value to the API, but currently always returning true.
12285 // If this ever returns false we need to update BeginDragDropSource() accordingly.
12286 //if (!ret)
12287 // End();
12288 //return ret;
12289 return true;
12290}
12291
12292void ImGui::EndTooltip()
12293{
12294 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
12295 End();
12296}
12297
12298void ImGui::SetTooltip(const char* fmt, ...)
12299{
12300 va_list args;
12301 va_start(args, fmt);
12302 SetTooltipV(fmt, args);
12303 va_end(args);
12304}
12305
12306void ImGui::SetTooltipV(const char* fmt, va_list args)
12307{
12308 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
12309 return;
12310 TextV(fmt, args);
12311 EndTooltip();
12312}
12313
12314// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
12315// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
12316void ImGui::SetItemTooltip(const char* fmt, ...)
12317{
12318 va_list args;
12319 va_start(args, fmt);
12320 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12321 SetTooltipV(fmt, args);
12322 va_end(args);
12323}
12324
12325void ImGui::SetItemTooltipV(const char* fmt, va_list args)
12326{
12327 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12328 SetTooltipV(fmt, args);
12329}
12330
12331
12332//-----------------------------------------------------------------------------
12333// [SECTION] POPUPS
12334//-----------------------------------------------------------------------------
12335
12336// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
12337bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
12338{
12339 ImGuiContext& g = *GImGui;
12340 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
12341 {
12342 // Return true if any popup is open at the current BeginPopup() level of the popup stack
12343 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
12344 IM_ASSERT(id == 0);
12345 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12346 return g.OpenPopupStack.Size > 0;
12347 else
12348 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
12349 }
12350 else
12351 {
12352 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12353 {
12354 // Return true if the popup is open anywhere in the popup stack
12355 for (int n = 0; n < g.OpenPopupStack.Size; n++)
12356 if (g.OpenPopupStack[n].PopupId == id)
12357 return true;
12358 return false;
12359 }
12360 else
12361 {
12362 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
12363 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
12364 }
12365 }
12366}
12367
12368bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
12369{
12370 ImGuiContext& g = *GImGui;
12371 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
12372 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
12373 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
12374 return IsPopupOpen(id, popup_flags);
12375}
12376
12377// Also see FindBlockingModal(NULL)
12378ImGuiWindow* ImGui::GetTopMostPopupModal()
12379{
12380 ImGuiContext& g = *GImGui;
12381 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12382 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12383 if (popup->Flags & ImGuiWindowFlags_Modal)
12384 return popup;
12385 return NULL;
12386}
12387
12388// See Demo->Stacked Modal to confirm what this is for.
12389ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
12390{
12391 ImGuiContext& g = *GImGui;
12392 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12393 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12394 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
12395 return popup;
12396 return NULL;
12397}
12398
12399
12400// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
12401// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
12402// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
12403// - WindowA // FindBlockingModal() returns Modal1
12404// - WindowB // .. returns Modal1
12405// - Modal1 // .. returns Modal2
12406// - WindowC // .. returns Modal2
12407// - WindowD // .. returns Modal2
12408// - Modal2 // .. returns Modal2
12409// - WindowE // .. returns NULL
12410// Notes:
12411// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
12412// Only difference is here we check for ->Active/WasActive but it may be unnecessary.
12413ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
12414{
12415 ImGuiContext& g = *GImGui;
12416 if (g.OpenPopupStack.Size <= 0)
12417 return NULL;
12418
12419 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
12420 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12421 {
12422 ImGuiWindow* popup_window = popup_data.Window;
12423 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
12424 continue;
12425 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.
12426 continue;
12427 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
12428 return popup_window;
12429 if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
12430 continue;
12431 return popup_window; // Place window right below first block modal
12432 }
12433 return NULL;
12434}
12435
12436bool ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
12437{
12438 ImGuiContext& g = *GImGui;
12439 ImGuiID id = g.CurrentWindow->GetID(str_id);
12440 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
12441 return OpenPopupEx(id, popup_flags);
12442}
12443
12444bool ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
12445{
12446 return OpenPopupEx(id, popup_flags);
12447}
12448
12449// Mark popup as open (toggle toward open state).
12450// - Return true when the popup is toggled open, which allows you to capture local state if needed.
12451// You may also call IsWindowAppearing() inside the later BeginPopup() scope if you need to prepare/compute data for the popup.
12452// - Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
12453// - Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
12454// - One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL).
12455bool ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
12456{
12457 ImGuiContext& g = *GImGui;
12458 ImGuiWindow* parent_window = g.CurrentWindow;
12459 const int current_stack_size = g.BeginPopupStack.Size;
12460
12461 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
12462 if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
12463 return false;
12464
12465 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
12466 popup_ref.PopupId = id;
12467 popup_ref.Window = NULL;
12468 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
12469 popup_ref.OpenFrameCount = g.FrameCount;
12470 popup_ref.OpenParentId = parent_window->IDStack.back();
12471 popup_ref.OpenPopupPos = NavCalcPreferredRefPos(ImGuiWindowFlags_Popup);
12472 popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
12473
12474 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
12475 if (g.OpenPopupStack.Size < current_stack_size + 1)
12476 {
12477 g.OpenPopupStack.push_back(popup_ref);
12478 return true;
12479 }
12480 else
12481 {
12482 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
12483 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
12484 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
12485 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
12486 bool keep_existing = false;
12487 if (g.OpenPopupStack[current_stack_size].PopupId == id)
12488 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
12489 keep_existing = true;
12490 if (keep_existing)
12491 {
12492 // No reopen
12493 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
12494 }
12495 else
12496 {
12497 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
12498 ClosePopupToLevel(current_stack_size, true);
12499 g.OpenPopupStack.push_back(popup_ref);
12500 }
12501
12502 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
12503 // This is equivalent to what ClosePopupToLevel() does.
12504 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
12505 // FocusWindow(parent_window);
12506
12507 return !keep_existing;
12508 }
12509}
12510
12511// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
12512// This function closes any popups that are over 'ref_window'.
12513void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
12514{
12515 ImGuiContext& g = *GImGui;
12516 if (g.OpenPopupStack.Size == 0)
12517 return;
12518
12519 // Don't close our own child popup windows.
12520 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
12521 int popup_count_to_keep = 0;
12522 if (ref_window)
12523 {
12524 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
12525 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
12526 {
12527 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
12528 if (!popup.Window)
12529 continue;
12530 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
12531
12532 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
12533 // - Clicking/Focusing Window2 won't close Popup1:
12534 // Window -> Popup1 -> Window2(Ref)
12535 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
12536 // Window -> Popup1(Ref) -> Popup2 -> Popup3
12537 // - Each popups may contain child windows, which is why we compare ->RootWindow!
12538 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
12539 // We step through every popup from bottom to top to validate their position relative to reference window.
12540 bool ref_window_is_descendant_of_popup = false;
12541 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
12542 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
12543 if (IsWindowWithinBeginStackOf(ref_window, popup_window))
12544 {
12545 ref_window_is_descendant_of_popup = true;
12546 break;
12547 }
12548 if (!ref_window_is_descendant_of_popup)
12549 break;
12550 }
12551 }
12552 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
12553 {
12554 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
12555 ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
12556 }
12557}
12558
12559void ImGui::ClosePopupsExceptModals()
12560{
12561 ImGuiContext& g = *GImGui;
12562
12563 int popup_count_to_keep;
12564 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
12565 {
12566 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
12567 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
12568 break;
12569 }
12570 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
12571 ClosePopupToLevel(popup_count_to_keep, true);
12572}
12573
12574void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
12575{
12576 ImGuiContext& g = *GImGui;
12577 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
12578 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
12579 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)
12580 for (int n = remaining; n < g.OpenPopupStack.Size; n++)
12581 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);
12582
12583 // Trim open popup stack
12584 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
12585 g.OpenPopupStack.resize(remaining);
12586
12587 // 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)
12588 if (restore_focus_to_window_under_popup && prev_popup.Window)
12589 {
12590 ImGuiWindow* popup_window = prev_popup.Window;
12591 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
12592 if (focus_window && !focus_window->WasActive)
12593 FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
12594 else
12595 FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
12596 }
12597}
12598
12599// Close the popup we have begin-ed into.
12600void ImGui::CloseCurrentPopup()
12601{
12602 ImGuiContext& g = *GImGui;
12603 int popup_idx = g.BeginPopupStack.Size - 1;
12604 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
12605 return;
12606
12607 // Closing a menu closes its top-most parent popup (unless a modal)
12608 while (popup_idx > 0)
12609 {
12610 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
12611 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
12612 bool close_parent = false;
12613 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
12614 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
12615 close_parent = true;
12616 if (!close_parent)
12617 break;
12618 popup_idx--;
12619 }
12620 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
12621 ClosePopupToLevel(popup_idx, true);
12622
12623 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
12624 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
12625 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
12626 if (ImGuiWindow* window = g.NavWindow)
12627 window->DC.NavHideHighlightOneFrame = true;
12628}
12629
12630// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
12631bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
12632{
12633 ImGuiContext& g = *GImGui;
12634 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12635 {
12636 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12637 return false;
12638 }
12639
12640 char name[20];
12641 IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx()
12642 ImFormatString(name, IM_COUNTOF(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame
12643
12644 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup);
12645 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12646 EndPopup();
12647 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12648 return is_open;
12649}
12650
12651bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags)
12652{
12653 ImGuiContext& g = *GImGui;
12654 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12655 {
12656 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12657 return false;
12658 }
12659
12660 // As we bypass BeginChild(), set ImGuiChildFlags_AlwaysAutoResize as it is checked independently from ImGuiWindowFlags_AlwaysAutoResize for now (see #9355)
12661 // Ideally we should remove setting ImGuiWindowFlags_AlwaysAutoResize in BeginChild().
12662 if ((extra_window_flags & ImGuiWindowFlags_ChildWindow) && (extra_window_flags & ImGuiWindowFlags_AlwaysAutoResize))
12663 {
12664 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
12665 g.NextWindowData.ChildFlags |= ImGuiChildFlags_AlwaysAutoResize;
12666 else
12667 g.NextWindowData.ChildFlags = ImGuiChildFlags_AlwaysAutoResize;
12668 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
12669 }
12670
12671 char name[128];
12672 IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu);
12673 ImFormatString(name, IM_COUNTOF(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth
12674 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup);
12675 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12676 EndPopup();
12677 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12678 return is_open;
12679}
12680
12681bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12682{
12683 ImGuiContext& g = *GImGui;
12684 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12685 {
12686 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12687 return false;
12688 }
12689 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12690 ImGuiID id = g.CurrentWindow->GetID(str_id);
12691 return BeginPopupEx(id, flags);
12692}
12693
12694// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12695// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12696// - *p_open set back to false in BeginPopupModal() when popup is not open.
12697// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12698bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12699{
12700 ImGuiContext& g = *GImGui;
12701 ImGuiWindow* window = g.CurrentWindow;
12702 const ImGuiID id = window->GetID(name);
12703 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12704 {
12705 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12706 if (p_open && *p_open)
12707 *p_open = false;
12708 return false;
12709 }
12710
12711 // Center modal windows by default for increased visibility
12712 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12713 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12714 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12715 {
12716 const ImGuiViewport* viewport = GetMainViewport();
12717 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12718 }
12719
12720 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
12721 const bool is_open = Begin(name, p_open, flags);
12722 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12723 {
12724 EndPopup();
12725 if (is_open)
12726 ClosePopupToLevel(g.BeginPopupStack.Size, true);
12727 return false;
12728 }
12729 return is_open;
12730}
12731
12732void ImGui::EndPopup()
12733{
12734 ImGuiContext& g = *GImGui;
12735 ImGuiWindow* window = g.CurrentWindow;
12736 IM_ASSERT_USER_ERROR_RET((window->Flags & ImGuiWindowFlags_Popup) != 0 && g.BeginPopupStack.Size > 0, "Calling EndPopup() in wrong window!");
12737
12738 // 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)
12739 if (g.NavWindow == window)
12740 NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12741
12742 // Child-popups don't need to be laid out
12743 const ImGuiID backup_within_end_popup_id = g.WithinEndPopupID;
12744 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
12745 g.WithinEndPopupID = window->ID;
12746 if (window->Flags & ImGuiWindowFlags_ChildWindow)
12747 g.WithinEndChildID = window->ID;
12748 End();
12749 g.WithinEndPopupID = backup_within_end_popup_id;
12750 g.WithinEndChildID = backup_within_end_child_id;
12751}
12752
12753ImGuiMouseButton ImGui::GetMouseButtonFromPopupFlags(ImGuiPopupFlags flags)
12754{
12755#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
12756 if ((flags & ImGuiPopupFlags_InvalidMask_) != 0) // 1,2 --> ImGuiMouseButton_Right, ImGuiMouseButton_Middle
12757 return (flags & ImGuiPopupFlags_InvalidMask_);
12758#else
12759 IM_ASSERT((flags & ImGuiPopupFlags_InvalidMask_) == 0);
12760#endif
12761 if (flags & ImGuiPopupFlags_MouseButtonMask_)
12762 return ((flags & ImGuiPopupFlags_MouseButtonMask_) >> ImGuiPopupFlags_MouseButtonShift_) - 1;
12763 return ImGuiMouseButton_Right; // Default == 1
12764}
12765
12766bool ImGui::IsPopupOpenRequestForItem(ImGuiPopupFlags popup_flags, ImGuiID id)
12767{
12768 ImGuiContext& g = *GImGui;
12769 ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags);
12770 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12771 return true;
12772 if (g.NavOpenContextMenuItemId == id && (IsItemFocused() || id == g.CurrentWindow->MoveId))
12773 return true;
12774 return false;
12775}
12776
12777bool ImGui::IsPopupOpenRequestForWindow(ImGuiPopupFlags popup_flags)
12778{
12779 ImGuiContext& g = *GImGui;
12780 ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags);
12781 if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12782 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
12783 return true;
12784 if (g.NavOpenContextMenuWindowId && g.CurrentWindow->ID)
12785 if (IsWindowChildOf(g.NavWindow, g.CurrentWindow, false)) // This enable ordering to be used to disambiguate item vs window (#8803)
12786 return true;
12787 return false;
12788}
12789
12790// Helper to open a popup if mouse button is released over the item
12791// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12792bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12793{
12794 ImGuiContext& g = *GImGui;
12795 if (IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID))
12796 {
12797 ImGuiWindow* window = g.CurrentWindow;
12798 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!
12799 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12800 return OpenPopupEx(id, popup_flags);
12801 }
12802 return false;
12803}
12804
12805// This is a helper to handle the simplest case of associating one named popup to one given widget.
12806// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12807// - To create a popup with a specific identifier, pass it in str_id.
12808// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12809// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12810// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12811// This is essentially the same as:
12812// id = str_id ? GetID(str_id) : GetItemID();
12813// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12814// return BeginPopup(id);
12815// Which is essentially the same as:
12816// id = str_id ? GetID(str_id) : GetItemID();
12817// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12818// OpenPopup(id);
12819// return BeginPopup(id);
12820// The main difference being that this is tweaked to avoid computing the ID twice.
12821bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12822{
12823 ImGuiContext& g = *GImGui;
12824 ImGuiWindow* window = g.CurrentWindow;
12825 if (window->SkipItems)
12826 return false;
12827 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItem ID. Using LastItem ID as a Popup ID won't conflict!
12828 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12829 if (IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID))
12830 OpenPopupEx(id, popup_flags);
12831 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12832}
12833
12834bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
12835{
12836 ImGuiContext& g = *GImGui;
12837 ImGuiWindow* window = g.CurrentWindow;
12838 if (!str_id)
12839 str_id = "window_context";
12840 ImGuiID id = window->GetID(str_id);
12841 if (IsPopupOpenRequestForWindow(popup_flags))
12842 OpenPopupEx(id, popup_flags);
12843 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12844}
12845
12846bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
12847{
12848 ImGuiContext& g = *GImGui;
12849 ImGuiWindow* window = g.CurrentWindow;
12850 if (!str_id)
12851 str_id = "void_context";
12852 ImGuiID id = window->GetID(str_id);
12853 ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags);
12854 if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
12855 if (GetTopMostPopupModal() == NULL)
12856 OpenPopupEx(id, popup_flags);
12857 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12858}
12859
12860// 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.)
12861// 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.
12862// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
12863// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
12864// this allows us to have tooltips/popups displayed out of the parent viewport.)
12865ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12866{
12867 ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12868 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12869 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12870
12871 // Combo Box policy (we want a connecting edge)
12872 if (policy == ImGuiPopupPositionPolicy_ComboBox)
12873 {
12874 const ImGuiDir dir_preferred_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12875 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12876 {
12877 const ImGuiDir dir = (n == -1) ? *last_dir : dir_preferred_order[n];
12878 if (n != -1 && dir == *last_dir) // Already tried this direction?
12879 continue;
12880 ImVec2 pos;
12881 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
12882 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12883 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12884 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12885 if (!r_outer.Contains(ImRect(pos, pos + size)))
12886 continue;
12887 *last_dir = dir;
12888 return pos;
12889 }
12890 }
12891
12892 // Tooltip and Default popup policy
12893 // (Always first try the direction we used on the last frame, if any)
12894 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12895 {
12896 const ImGuiDir dir_preferred_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12897 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12898 {
12899 const ImGuiDir dir = (n == -1) ? *last_dir : dir_preferred_order[n];
12900 if (n != -1 && dir == *last_dir) // Already tried this direction?
12901 continue;
12902
12903 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);
12904 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);
12905
12906 // 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)
12907 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12908 continue;
12909 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12910 continue;
12911
12912 ImVec2 pos;
12913 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12914 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12915
12916 // Clamp top-left corner of popup
12917 pos.x = ImMax(pos.x, r_outer.Min.x);
12918 pos.y = ImMax(pos.y, r_outer.Min.y);
12919
12920 *last_dir = dir;
12921 return pos;
12922 }
12923 }
12924
12925 // Fallback when not enough room:
12926 *last_dir = ImGuiDir_None;
12927
12928 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12929 if (policy == ImGuiPopupPositionPolicy_Tooltip)
12930 return ref_pos + ImVec2(2, 2);
12931
12932 // Otherwise try to keep within display
12933 ImVec2 pos = ref_pos;
12934 pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12935 pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12936 return pos;
12937}
12938
12939// Note that this is used for popups, which can overlap the non work-area of individual viewports.
12940ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12941{
12942 ImGuiContext& g = *GImGui;
12943 IM_UNUSED(window);
12944 ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
12945 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12946 r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12947 return r_screen;
12948}
12949
12950ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12951{
12952 ImGuiContext& g = *GImGui;
12953
12954 ImRect r_outer = GetPopupAllowedExtentRect(window);
12955 if (window->Flags & ImGuiWindowFlags_ChildMenu)
12956 {
12957 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12958 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12959 IM_ASSERT(g.CurrentWindow == window);
12960 ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;
12961 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).
12962 ImRect r_avoid;
12963 if (parent_window->DC.MenuBarAppending)
12964 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
12965 else
12966 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);
12967 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12968 }
12969 if (window->Flags & ImGuiWindowFlags_Popup)
12970 {
12971 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12972 }
12973 if (window->Flags & ImGuiWindowFlags_Tooltip)
12974 {
12975 // Position tooltip (always follows mouse + clamp within outer boundaries)
12976 // FIXME:
12977 // - 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).
12978 // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
12979 // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
12980 // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
12981 IM_ASSERT(g.CurrentWindow == window);
12982 const float scale = g.Style.MouseCursorScale;
12983 const ImVec2 ref_pos = NavCalcPreferredRefPos(ImGuiWindowFlags_Tooltip);
12984
12985 if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource(ImGuiWindowFlags_Tooltip) == ImGuiInputSource_Mouse)
12986 {
12987 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
12988 if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
12989 return tooltip_pos;
12990 }
12991
12992 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
12993 ImRect r_avoid;
12994 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
12995 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12996 else
12997 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.
12998 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12999
13000 return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
13001 }
13002 IM_ASSERT(0);
13003 return window->Pos;
13004}
13005
13006//-----------------------------------------------------------------------------
13007// [SECTION] WINDOW FOCUS
13008//----------------------------------------------------------------------------
13009// - SetWindowFocus()
13010// - SetNextWindowFocus()
13011// - IsWindowFocused()
13012// - UpdateWindowInFocusOrderList() [Internal]
13013// - BringWindowToFocusFront() [Internal]
13014// - BringWindowToDisplayFront() [Internal]
13015// - BringWindowToDisplayBack() [Internal]
13016// - BringWindowToDisplayBehind() [Internal]
13017// - FindWindowDisplayIndex() [Internal]
13018// - FocusWindow() [Internal]
13019// - FocusTopMostWindowUnderOne() [Internal]
13020//-----------------------------------------------------------------------------
13021
13022void ImGui::SetWindowFocus()
13023{
13024 FocusWindow(GImGui->CurrentWindow);
13025}
13026
13027void ImGui::SetWindowFocus(const char* name)
13028{
13029 if (name)
13030 {
13031 if (ImGuiWindow* window = FindWindowByName(name))
13032 FocusWindow(window);
13033 }
13034 else
13035 {
13036 FocusWindow(NULL);
13037 }
13038}
13039
13040void ImGui::SetNextWindowFocus()
13041{
13042 ImGuiContext& g = *GImGui;
13043 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus;
13044}
13045
13046// Similar to IsWindowHovered()
13047bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
13048{
13049 ImGuiContext& g = *GImGui;
13050 ImGuiWindow* ref_window = g.NavWindow;
13051 ImGuiWindow* cur_window = g.CurrentWindow;
13052
13053 if (ref_window == NULL)
13054 return false;
13055 if (flags & ImGuiFocusedFlags_AnyWindow)
13056 return true;
13057
13058 IM_ASSERT(cur_window); // Not inside a Begin()/End()
13059 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
13060 if (flags & ImGuiFocusedFlags_RootWindow)
13061 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
13062
13063 if (flags & ImGuiFocusedFlags_ChildWindows)
13064 return IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
13065 else
13066 return ref_window == cur_window;
13067}
13068
13069static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13070{
13071 ImGuiContext& g = *GImGui;
13072 IM_UNUSED(g);
13073 int order = window->FocusOrder;
13074 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13075 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13076 return order;
13077}
13078
13079static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
13080{
13081 ImGuiContext& g = *GImGui;
13082
13083 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
13084 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
13085 if ((just_created || child_flag_changed) && !new_is_explicit_child)
13086 {
13087 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
13088 g.WindowsFocusOrder.push_back(window);
13089 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
13090 }
13091 else if (!just_created && child_flag_changed && new_is_explicit_child)
13092 {
13093 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
13094 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
13095 g.WindowsFocusOrder[n]->FocusOrder--;
13096 g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
13097 window->FocusOrder = -1;
13098 }
13099 window->IsExplicitChild = new_is_explicit_child;
13100}
13101
13102void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
13103{
13104 ImGuiContext& g = *GImGui;
13105 IM_ASSERT(window == window->RootWindow);
13106
13107 const int cur_order = window->FocusOrder;
13108 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
13109 if (g.WindowsFocusOrder.back() == window)
13110 return;
13111
13112 const int new_order = g.WindowsFocusOrder.Size - 1;
13113 for (int n = cur_order; n < new_order; n++)
13114 {
13115 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
13116 g.WindowsFocusOrder[n]->FocusOrder--;
13117 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
13118 }
13119 g.WindowsFocusOrder[new_order] = window;
13120 window->FocusOrder = (short)new_order;
13121}
13122
13123// Note technically focus related but rather adjacent and close to BringWindowToFocusFront()
13124// FIXME-FOCUS: Could opt-in/opt-out enable modal check like in FocusWindow().
13125void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
13126{
13127 ImGuiContext& g = *GImGui;
13128 ImGuiWindow* current_front_window = g.Windows.back();
13129 if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
13130 return;
13131 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
13132 if (g.Windows[i] == window)
13133 {
13134 memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
13135 g.Windows[g.Windows.Size - 1] = window;
13136 break;
13137 }
13138}
13139
13140void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
13141{
13142 ImGuiContext& g = *GImGui;
13143 if (g.Windows[0] == window)
13144 return;
13145 for (int i = 0; i < g.Windows.Size; i++)
13146 if (g.Windows[i] == window)
13147 {
13148 memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
13149 g.Windows[0] = window;
13150 break;
13151 }
13152}
13153
13154void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
13155{
13156 IM_ASSERT(window != NULL && behind_window != NULL);
13157 ImGuiContext& g = *GImGui;
13158 window = window->RootWindow;
13159 behind_window = behind_window->RootWindow;
13160 int pos_wnd = FindWindowDisplayIndex(window);
13161 int pos_beh = FindWindowDisplayIndex(behind_window);
13162 if (pos_wnd < pos_beh)
13163 {
13164 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
13165 memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
13166 g.Windows[pos_beh - 1] = window;
13167 }
13168 else
13169 {
13170 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
13171 memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
13172 g.Windows[pos_beh] = window;
13173 }
13174}
13175
13176int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
13177{
13178 ImGuiContext& g = *GImGui;
13179 return g.Windows.index_from_ptr(g.Windows.find(window));
13180}
13181
13182// Moving window to front of display and set focus (which happens to be back of our sorted list)
13183void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
13184{
13185 ImGuiContext& g = *GImGui;
13186
13187 // Modal check?
13188 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
13189 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
13190 {
13191 // This block would typically be reached in two situations:
13192 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
13193 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
13194 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
13195 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13196 BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
13197 ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
13198 return;
13199 }
13200
13201 // Find last focused child (if any) and focus it instead.
13202 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
13203 window = NavRestoreLastChildNavWindow(window);
13204
13205 // Apply focus
13206 if (g.NavWindow != window)
13207 {
13208 SetNavWindow(window);
13209 if (window && g.NavHighlightItemUnderNav)
13210 g.NavMousePosDirty = true;
13211 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
13212 g.NavLayer = ImGuiNavLayer_Main;
13213 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
13214 g.NavIdIsAlive = false;
13215 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13216
13217 // Close popups if any
13218 ClosePopupsOverWindow(window, false);
13219 }
13220
13221 // Move the root window to the top of the pile
13222 IM_ASSERT(window == NULL || window->RootWindow != NULL);
13223 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
13224 ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
13225
13226 // Steal active widgets. Some of the cases it triggers includes:
13227 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
13228 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
13229 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
13230 if (!g.ActiveIdNoClearOnFocusLoss)
13231 ClearActiveID();
13232
13233 // Passing NULL allow to disable keyboard focus
13234 if (!window)
13235 return;
13236
13237 // Bring to front
13238 BringWindowToFocusFront(focus_front_window);
13239 if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13240 BringWindowToDisplayFront(display_front_window);
13241}
13242
13243void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
13244{
13245 ImGuiContext& g = *GImGui;
13246 IM_UNUSED(filter_viewport); // Unused in master branch.
13247 int start_idx = g.WindowsFocusOrder.Size - 1;
13248 if (under_this_window != NULL)
13249 {
13250 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
13251 int offset = -1;
13252 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
13253 {
13254 under_this_window = under_this_window->ParentWindow;
13255 offset = 0;
13256 }
13257 start_idx = FindWindowFocusIndex(under_this_window) + offset;
13258 }
13259 for (int i = start_idx; i >= 0; i--)
13260 {
13261 // 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.
13262 ImGuiWindow* window = g.WindowsFocusOrder[i];
13263 if (window == ignore_window || !window->WasActive)
13264 continue;
13265 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
13266 {
13267 FocusWindow(window, flags);
13268 return;
13269 }
13270 }
13271 FocusWindow(NULL, flags);
13272}
13273
13274//-----------------------------------------------------------------------------
13275// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
13276//-----------------------------------------------------------------------------
13277
13278// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
13279// In our terminology those should be interchangeable, yet right now this is super confusing.
13280// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
13281
13282void ImGui::SetNavCursorVisible(bool visible)
13283{
13284 ImGuiContext& g = *GImGui;
13285 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13286 visible = false;
13287 else if (g.IO.ConfigNavCursorVisibleAlways)
13288 visible = true;
13289 g.NavCursorVisible = visible;
13290}
13291
13292// (was called NavRestoreHighlightAfterMove() before 1.91.4)
13293void ImGui::SetNavCursorVisibleAfterMove()
13294{
13295 ImGuiContext& g = *GImGui;
13296 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13297 g.NavCursorVisible = false;
13298 else if (g.NavInputSource == ImGuiInputSource_Keyboard && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) == 0)
13299 g.NavCursorVisible = false;
13300 else if (g.NavInputSource == ImGuiInputSource_Gamepad && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
13301 g.NavCursorVisible = false;
13302 else if (g.IO.ConfigNavCursorVisibleAuto)
13303 g.NavCursorVisible = true;
13304 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
13305}
13306
13307void ImGui::SetNavWindow(ImGuiWindow* window)
13308{
13309 ImGuiContext& g = *GImGui;
13310 if (g.NavWindow != window)
13311 {
13312 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
13313 g.NavWindow = window;
13314 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13315 }
13316 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13317 NavUpdateAnyRequestFlag();
13318}
13319
13320void ImGui::NavHighlightActivated(ImGuiID id)
13321{
13322 ImGuiContext& g = *GImGui;
13323 g.NavHighlightActivatedId = id;
13324 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
13325}
13326
13327void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
13328{
13329 ImGuiContext& g = *GImGui;
13330 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
13331}
13332
13333void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
13334{
13335 ImGuiContext& g = *GImGui;
13336 IM_ASSERT(g.NavWindow != NULL);
13337 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
13338 g.NavId = id;
13339 g.NavLayer = nav_layer;
13340 SetNavFocusScope(focus_scope_id);
13341 g.NavWindow->NavLastIds[nav_layer] = id;
13342 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
13343
13344 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13345 NavClearPreferredPosForAxis(ImGuiAxis_X);
13346 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13347}
13348
13349void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
13350{
13351 ImGuiContext& g = *GImGui;
13352 IM_ASSERT(id != 0);
13353
13354 if (g.NavWindow != window)
13355 SetNavWindow(window);
13356
13357 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
13358 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
13359 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
13360 g.NavId = id;
13361 g.NavLayer = nav_layer;
13362 SetNavFocusScope(g.CurrentFocusScopeId);
13363 window->NavLastIds[nav_layer] = id;
13364 if (g.LastItemData.ID == id)
13365 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
13366 g.NavIdItemFlags = (g.LastItemData.ID == id) ? g.LastItemData.ItemFlags : ImGuiItemFlags_None;
13367 if (id == g.ActiveIdIsAlive)
13368 g.NavIdIsAlive = true;
13369
13370 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
13371 g.NavHighlightItemUnderNav = true;
13372 else if (g.IO.ConfigNavCursorVisibleAuto)
13373 g.NavCursorVisible = false;
13374
13375 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13376 NavClearPreferredPosForAxis(ImGuiAxis_X);
13377 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13378}
13379
13380static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
13381{
13382 if (ImFabs(dx) > ImFabs(dy))
13383 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
13384 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
13385}
13386
13387static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
13388{
13389 if (cand_max < curr_min)
13390 return cand_max - curr_min;
13391 if (curr_max < cand_min)
13392 return cand_min - curr_max;
13393 return 0.0f;
13394}
13395
13396// Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
13397static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb)
13398{
13399 ImGuiContext& g = *GImGui;
13400 ImGuiWindow* window = g.CurrentWindow;
13401 if (g.NavLayer != window->DC.NavLayerCurrent)
13402 return false;
13403
13404 // FIXME: Those are not good variables names
13405 ImRect cand = nav_bb; // Current item nav rectangle
13406 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)
13407 g.NavScoringDebugCount++;
13408
13409 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
13410 if (window->ParentWindow == g.NavWindow)
13411 {
13412 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
13413 if (!window->ClipRect.Overlaps(cand))
13414 return false;
13415 cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
13416 }
13417
13418 // Compute distance between boxes
13419 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
13420 float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
13421 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
13422 if (dby != 0.0f && dbx != 0.0f)
13423 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
13424 float dist_box = ImFabs(dbx) + ImFabs(dby);
13425
13426 // 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)
13427 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
13428 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
13429 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
13430
13431 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
13432 ImGuiDir quadrant;
13433 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
13434 if (dbx != 0.0f || dby != 0.0f)
13435 {
13436 // For non-overlapping boxes, use distance between boxes
13437 // 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
13438 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
13439 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
13440 dax = dbx;
13441 day = dby;
13442 dist_axial = dist_box;
13443 quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
13444 }
13445 else if (dcx != 0.0f || dcy != 0.0f)
13446 {
13447 // For overlapping boxes with different centers, use distance between centers
13448 dax = dcx;
13449 day = dcy;
13450 dist_axial = dist_center;
13451 quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
13452 }
13453 else
13454 {
13455 // 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)
13456 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
13457 }
13458
13459 const ImGuiDir move_dir = g.NavMoveDir;
13460#if IMGUI_DEBUG_NAV_SCORING
13461 char buf[200];
13462 if (g.IO.KeyCtrl) // Hold Ctrl to preview score in matching quadrant. Ctrl+Arrow to rotate.
13463 {
13464 if (quadrant == move_dir)
13465 {
13466 ImFormatString(buf, IM_COUNTOF(buf), "%.0f/%.0f", dist_box, dist_center);
13467 ImDrawList* draw_list = GetForegroundDrawList(window);
13468 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
13469 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
13470 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
13471 }
13472 }
13473 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
13474 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
13475 if (debug_hovering || debug_tty)
13476 {
13477 ImFormatString(buf, IM_COUNTOF(buf),
13478 "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",
13479 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
13480 if (debug_hovering)
13481 {
13482 ImDrawList* draw_list = GetForegroundDrawList(window);
13483 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
13484 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
13485 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
13486 draw_list->AddText(cand.Max, ~0U, buf);
13487 }
13488 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
13489 }
13490#endif
13491
13492 // Is it in the quadrant we're interested in moving to?
13493 bool new_best = false;
13494 if (quadrant == move_dir)
13495 {
13496 // Does it beat the current best candidate?
13497 if (dist_box < result->DistBox)
13498 {
13499 result->DistBox = dist_box;
13500 result->DistCenter = dist_center;
13501 return true;
13502 }
13503 if (dist_box == result->DistBox)
13504 {
13505 // Try using distance between center points to break ties
13506 if (dist_center < result->DistCenter)
13507 {
13508 result->DistCenter = dist_center;
13509 new_best = true;
13510 }
13511 else if (dist_center == result->DistCenter)
13512 {
13513 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
13514 // (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),
13515 // 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.
13516 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
13517 new_best = true;
13518 }
13519 }
13520 }
13521
13522 // 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
13523 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
13524 // 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.
13525 // 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.
13526 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
13527 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
13528 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
13529 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))
13530 {
13531 result->DistAxial = dist_axial;
13532 new_best = true;
13533 }
13534
13535 return new_best;
13536}
13537
13538static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
13539{
13540 ImGuiContext& g = *GImGui;
13541 ImGuiWindow* window = g.CurrentWindow;
13542 result->Window = window;
13543 result->ID = g.LastItemData.ID;
13544 result->FocusScopeId = g.CurrentFocusScopeId;
13545 result->ItemFlags = g.LastItemData.ItemFlags;
13546 result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
13547 if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13548 {
13549 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13550 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13551 }
13552}
13553
13554// True when current work location may be scrolled horizontally when moving left / right.
13555// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
13556void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
13557{
13558 ImGuiContext& g = *GImGui;
13559 ImGuiWindow* window = g.CurrentWindow;
13560 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
13561}
13562
13563// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
13564// This is called after LastItemData is set, but NextItemData is also still valid.
13565static void ImGui::NavProcessItem()
13566{
13567 ImGuiContext& g = *GImGui;
13568 ImGuiWindow* window = g.CurrentWindow;
13569 const ImGuiID id = g.LastItemData.ID;
13570 const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
13571
13572 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816, #7994)
13573 ImRect nav_bb = g.LastItemData.NavRect;
13574 if (window->DC.NavIsScrollPushableX == false)
13575 {
13576 nav_bb.Min.x = ImClamp(nav_bb.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
13577 nav_bb.Max.x = ImClamp(nav_bb.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
13578 }
13579
13580 // Process Init Request
13581 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
13582 {
13583 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
13584 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
13585 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
13586 {
13587 NavApplyItemToResult(&g.NavInitResult);
13588 }
13589 if (candidate_for_nav_default_focus)
13590 {
13591 g.NavInitRequest = false; // Found a match, clear request
13592 NavUpdateAnyRequestFlag();
13593 }
13594 }
13595
13596 // Process Move Request (scoring for navigation)
13597 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
13598 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
13599 {
13600 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
13601 {
13602 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13603 if (is_tabbing)
13604 {
13605 NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
13606 }
13607 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
13608 {
13609 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
13610 if (NavScoreItem(result, nav_bb))
13611 NavApplyItemToResult(result);
13612
13613 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
13614 const float VISIBLE_RATIO = 0.70f;
13615 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13616 {
13617 const ImRect& r = window->InnerRect; // window->ClipRect
13618 if (r.Overlaps(nav_bb))
13619 if (ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
13620 if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb))
13621 NavApplyItemToResult(&g.NavMoveResultLocalVisible);
13622 }
13623 }
13624 }
13625 }
13626
13627 // Update information for currently focused/navigated item
13628 if (g.NavId == id)
13629 {
13630 if (g.NavWindow != window)
13631 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
13632 g.NavLayer = window->DC.NavLayerCurrent;
13633 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
13634 g.NavFocusScopeId = g.CurrentFocusScopeId;
13635 g.NavIdIsAlive = true;
13636 g.NavIdItemFlags = item_flags;
13637 if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13638 {
13639 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13640 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13641 }
13642 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
13643 }
13644}
13645
13646// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
13647// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
13648// - Case 1: no nav/active id: set result to first eligible item, stop storing.
13649// - Case 2: tab forward: on ref id set counter, on counter elapse store result
13650// - 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
13651// - Case 4: tab backward: store all results, on ref id pick prev, stop storing
13652// - 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
13653void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
13654{
13655 ImGuiContext& g = *GImGui;
13656
13657 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
13658 {
13659 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
13660 return;
13661 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
13662 return;
13663 }
13664
13665 // - Can always land on an item when using API call.
13666 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
13667 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
13668 bool can_stop;
13669 if (move_flags & ImGuiNavMoveFlags_FocusApi)
13670 can_stop = true;
13671 else
13672 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
13673
13674 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
13675 ImGuiNavItemData* result = &g.NavMoveResultLocal;
13676 if (g.NavTabbingDir == +1)
13677 {
13678 // Tab Forward or SetKeyboardFocusHere() with >= 0
13679 if (can_stop && g.NavTabbingResultFirst.ID == 0)
13680 NavApplyItemToResult(&g.NavTabbingResultFirst);
13681 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
13682 NavMoveRequestResolveWithLastItem(result);
13683 else if (g.NavId == id)
13684 g.NavTabbingCounter = 1;
13685 }
13686 else if (g.NavTabbingDir == -1)
13687 {
13688 // Tab Backward
13689 if (g.NavId == id)
13690 {
13691 if (result->ID)
13692 {
13693 g.NavMoveScoringItems = false;
13694 NavUpdateAnyRequestFlag();
13695 }
13696 }
13697 else if (can_stop)
13698 {
13699 // Keep applying until reaching NavId
13700 NavApplyItemToResult(result);
13701 }
13702 }
13703 else if (g.NavTabbingDir == 0)
13704 {
13705 if (can_stop && g.NavId == id)
13706 NavMoveRequestResolveWithLastItem(result);
13707 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
13708 NavApplyItemToResult(&g.NavTabbingResultFirst);
13709 }
13710}
13711
13712bool ImGui::NavMoveRequestButNoResultYet()
13713{
13714 ImGuiContext& g = *GImGui;
13715 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
13716}
13717
13718// FIXME: ScoringRect is not set
13719void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13720{
13721 ImGuiContext& g = *GImGui;
13722 IM_ASSERT(g.NavWindow != NULL);
13723 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
13724
13725 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
13726 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
13727
13728 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
13729 g.NavMoveDir = move_dir;
13730 g.NavMoveDirForDebug = move_dir;
13731 g.NavMoveClipDir = clip_dir;
13732 g.NavMoveFlags = move_flags;
13733 g.NavMoveScrollFlags = scroll_flags;
13734 g.NavMoveForwardToNextFrame = false;
13735 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
13736 g.NavMoveResultLocal.Clear();
13737 g.NavMoveResultLocalVisible.Clear();
13738 g.NavMoveResultOther.Clear();
13739 g.NavTabbingCounter = 0;
13740 g.NavTabbingResultFirst.Clear();
13741 NavUpdateAnyRequestFlag();
13742}
13743
13744void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
13745{
13746 ImGuiContext& g = *GImGui;
13747 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
13748 NavApplyItemToResult(result);
13749 NavUpdateAnyRequestFlag();
13750}
13751
13752// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent
13753void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data)
13754{
13755 ImGuiContext& g = *GImGui;
13756 g.NavMoveScoringItems = false;
13757 g.LastItemData.ID = tree_node_data->ID;
13758 g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
13759 g.LastItemData.NavRect = tree_node_data->NavRect;
13760 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
13761 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13762 NavUpdateAnyRequestFlag();
13763}
13764
13765void ImGui::NavMoveRequestCancel()
13766{
13767 ImGuiContext& g = *GImGui;
13768 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13769 NavUpdateAnyRequestFlag();
13770}
13771
13772// Forward will reuse the move request again on the next frame (generally with modifications done to it)
13773void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13774{
13775 ImGuiContext& g = *GImGui;
13776 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
13777 NavMoveRequestCancel();
13778 g.NavMoveForwardToNextFrame = true;
13779 g.NavMoveDir = move_dir;
13780 g.NavMoveClipDir = clip_dir;
13781 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
13782 g.NavMoveScrollFlags = scroll_flags;
13783}
13784
13785// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
13786// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
13787void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
13788{
13789 ImGuiContext& g = *GImGui;
13790 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
13791
13792 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
13793 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
13794 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == window->DC.NavLayerCurrent)
13795 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
13796}
13797
13798// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
13799// This way we could find the last focused window among our children. It would be much less confusing this way?
13800static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
13801{
13802 ImGuiWindow* parent = nav_window;
13803 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13804 parent = parent->ParentWindow;
13805 if (parent && parent != nav_window)
13806 parent->NavLastChildNavWindow = nav_window;
13807}
13808
13809// Restore the last focused child.
13810// Call when we are expected to land on the Main Layer (0) after FocusWindow()
13811static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
13812{
13813 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
13814 return window->NavLastChildNavWindow;
13815 return window;
13816}
13817
13818void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
13819{
13820 ImGuiContext& g = *GImGui;
13821 if (layer == ImGuiNavLayer_Main)
13822 {
13823 ImGuiWindow* prev_nav_window = g.NavWindow;
13824 g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
13825 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13826 if (prev_nav_window)
13827 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
13828 }
13829 ImGuiWindow* window = g.NavWindow;
13830 if (window->NavLastIds[layer] != 0)
13831 {
13832 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
13833 }
13834 else
13835 {
13836 g.NavLayer = layer;
13837 NavInitWindow(window, true);
13838 }
13839}
13840
13841static inline void ImGui::NavUpdateAnyRequestFlag()
13842{
13843 ImGuiContext& g = *GImGui;
13844 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
13845 if (g.NavAnyRequest)
13846 IM_ASSERT(g.NavWindow != NULL);
13847}
13848
13849// This needs to be called before we submit any widget (aka in or before Begin)
13850void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
13851{
13852 ImGuiContext& g = *GImGui;
13853 IM_ASSERT(window == g.NavWindow);
13854
13855 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
13856 {
13857 g.NavId = 0;
13858 SetNavFocusScope(window->NavRootFocusScopeId);
13859 return;
13860 }
13861
13862 bool init_for_nav = false;
13863 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
13864 init_for_nav = true;
13865 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
13866 if (init_for_nav)
13867 {
13868 SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
13869 g.NavInitRequest = true;
13870 g.NavInitRequestFromMove = false;
13871 g.NavInitResult.ID = 0;
13872 NavUpdateAnyRequestFlag();
13873 }
13874 else
13875 {
13876 g.NavId = window->NavLastIds[0];
13877 SetNavFocusScope(window->NavRootFocusScopeId);
13878 }
13879}
13880
13881// Positioning logic altered slightly for remote activation: for Popup we want to use item rect, for Tooltip we leave things alone. (#9138)
13882// When calling for ImGuiWindowFlags_Popup we use LastItemData.
13883static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource(ImGuiWindowFlags window_type)
13884{
13885 ImGuiContext& g = *GImGui;
13886 ImGuiWindow* window = g.NavWindow;
13887
13888 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
13889 if ((window_type & ImGuiWindowFlags_Popup) && activated_shortcut)
13890 return ImGuiInputSource_Keyboard;
13891
13892 if (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window)
13893 return ImGuiInputSource_Mouse;
13894 else
13895 return ImGuiInputSource_Keyboard; // or Nav in general
13896}
13897
13898static ImVec2 ImGui::NavCalcPreferredRefPos(ImGuiWindowFlags window_type)
13899{
13900 ImGuiContext& g = *GImGui;
13901 ImGuiWindow* window = g.NavWindow;
13902 ImGuiInputSource source = NavCalcPreferredRefPosSource(window_type);
13903
13904 if (source == ImGuiInputSource_Mouse)
13905 {
13906 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
13907 // 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.
13908 // In theory we could move that +1.0f offset in OpenPopupEx()
13909 ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
13910 return ImVec2(p.x + 1.0f, p.y);
13911 }
13912 else
13913 {
13914 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
13915 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
13916 ImRect ref_rect;
13917 if (activated_shortcut && (window_type & ImGuiWindowFlags_Popup))
13918 ref_rect = g.LastItemData.NavRect;
13919 else if (window != NULL)
13920 ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
13921
13922 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
13923 if (window != NULL && window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
13924 {
13925 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
13926 ref_rect.Translate(window->Scroll - next_scroll);
13927 }
13928 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()));
13929 ImGuiViewport* viewport = GetMainViewport();
13930 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.
13931 }
13932}
13933
13934float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
13935{
13936 ImGuiContext& g = *GImGui;
13937 float repeat_delay, repeat_rate;
13938 GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
13939
13940 ImGuiKey key_less, key_more;
13941 if (g.NavInputSource == ImGuiInputSource_Gamepad)
13942 {
13943 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
13944 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
13945 }
13946 else
13947 {
13948 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
13949 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
13950 }
13951 float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
13952 if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
13953 amount = 0.0f;
13954 return amount;
13955}
13956
13957static void ImGui::NavUpdate()
13958{
13959 ImGuiContext& g = *GImGui;
13960 ImGuiIO& io = g.IO;
13961
13962 io.WantSetMousePos = false;
13963 //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);
13964
13965 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
13966 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
13967 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13968 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
13969 if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_Gamepad)
13970 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
13971 if (IsKeyDown(key))
13972 g.NavInputSource = ImGuiInputSource_Gamepad;
13973 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13974 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
13975 if (nav_keyboard_active && g.NavInputSource != ImGuiInputSource_Keyboard)
13976 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
13977 if (IsKeyDown(key))
13978 g.NavInputSource = ImGuiInputSource_Keyboard;
13979
13980 // Process navigation init request (select first/default focus)
13981 g.NavJustMovedToId = 0;
13982 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
13983 if (g.NavInitResult.ID != 0)
13984 NavInitRequestApplyResult();
13985 g.NavInitRequest = false;
13986 g.NavInitRequestFromMove = false;
13987 g.NavInitResult.ID = 0;
13988
13989 // Process navigation move request
13990 if (g.NavMoveSubmitted)
13991 NavMoveRequestApplyResult();
13992 g.NavTabbingCounter = 0;
13993 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13994 if (g.NavCursorHideFrames > 0)
13995 if (--g.NavCursorHideFrames == 0)
13996 g.NavCursorVisible = true;
13997
13998 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
13999 bool set_mouse_pos = false;
14000 if (g.NavMousePosDirty && g.NavIdIsAlive)
14001 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
14002 set_mouse_pos = true;
14003 g.NavMousePosDirty = false;
14004 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
14005
14006 // 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
14007 if (g.NavWindow)
14008 NavSaveLastChildNavWindowIntoParent(g.NavWindow);
14009 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
14010 g.NavWindow->NavLastChildNavWindow = NULL;
14011
14012 // Update Ctrl+Tab and Windowing features (hold Square to move/resize/etc.)
14013 NavUpdateWindowing();
14014
14015 // Set output flags for user application
14016 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
14017 io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
14018
14019 // Process NavCancel input (to close a popup, get back to parent, clear focus)
14020 NavUpdateCancelRequest();
14021 NavUpdateContextMenuRequest();
14022
14023 // Process manual activation request
14024 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
14025 g.NavActivateFlags = ImGuiActivateFlags_None;
14026 if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14027 {
14028 const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
14029 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
14030 const bool input_pressed_keyboard = nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner));
14031 bool input_pressed_gamepad = false;
14032 if (activate_down && nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner) && (g.NavIdItemFlags & ImGuiItemFlags_Inputable)) // requires ImGuiItemFlags_Inputable to avoid retriggering regular buttons.
14033 if (GetKeyData(ImGuiKey_NavGamepadActivate)->DownDurationPrev < NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY && GetKeyData(ImGuiKey_NavGamepadActivate)->DownDuration >= NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY)
14034 input_pressed_gamepad = true;
14035
14036 if (g.ActiveId == 0 && activate_pressed)
14037 {
14038 g.NavActivateId = g.NavId;
14039 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
14040 }
14041 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (input_pressed_keyboard || input_pressed_gamepad))
14042 {
14043 g.NavActivateId = g.NavId;
14044 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
14045 }
14046 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_pressed_keyboard || input_pressed_gamepad)) // FIXME-NAV: Unsure why input_pressed_xxx (migrated from input_down which was already dubious)
14047 g.NavActivateDownId = g.NavId;
14048 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed_keyboard || input_pressed_gamepad))
14049 {
14050 g.NavActivatePressedId = g.NavId;
14051 NavHighlightActivated(g.NavId);
14052 }
14053 }
14054 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14055 g.NavCursorVisible = false;
14056 else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
14057 g.NavCursorVisible = true;
14058 if (g.NavActivateId != 0)
14059 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
14060
14061 // Highlight
14062 if (g.NavHighlightActivatedTimer > 0.0f)
14063 g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
14064 if (g.NavHighlightActivatedTimer == 0.0f)
14065 g.NavHighlightActivatedId = 0;
14066
14067 // Process programmatic activation request
14068 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
14069 if (g.NavNextActivateId != 0)
14070 {
14071 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
14072 g.NavActivateFlags = g.NavNextActivateFlags;
14073 }
14074 g.NavNextActivateId = 0;
14075
14076 // Process move requests
14077 NavUpdateCreateMoveRequest();
14078 if (g.NavMoveDir == ImGuiDir_None)
14079 NavUpdateCreateTabbingRequest();
14080 NavUpdateAnyRequestFlag();
14081 g.NavIdIsAlive = false;
14082
14083 // Scrolling
14084 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
14085 {
14086 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
14087 ImGuiWindow* window = g.NavWindow;
14088 const float scroll_speed = IM_ROUND(window->FontRefSize * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
14089 const ImGuiDir move_dir = g.NavMoveDir;
14090 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
14091 {
14092 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
14093 SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
14094 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
14095 SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
14096 }
14097
14098 // *Normal* Manual scroll with LStick
14099 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
14100 if (nav_gamepad_active)
14101 {
14102 const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
14103 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
14104 if (scroll_dir.x != 0.0f && window->ScrollbarX)
14105 SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
14106 if (scroll_dir.y != 0.0f)
14107 SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
14108 }
14109 }
14110
14111 // Always prioritize mouse highlight if navigation is disabled
14112 if (!nav_keyboard_active && !nav_gamepad_active)
14113 {
14114 g.NavCursorVisible = false;
14115 g.NavHighlightItemUnderNav = set_mouse_pos = false;
14116 }
14117
14118 // Update mouse position if requested
14119 // (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)
14120 if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
14121 TeleportMousePos(NavCalcPreferredRefPos(ImGuiWindowFlags_Popup));
14122
14123 // [DEBUG]
14124 g.NavScoringDebugCount = 0;
14125#if IMGUI_DEBUG_NAV_RECTS
14126 if (ImGuiWindow* debug_window = g.NavWindow)
14127 {
14128 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
14129 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)); }
14130 //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); }
14131 }
14132#endif
14133}
14134
14135void ImGui::NavInitRequestApplyResult()
14136{
14137 // 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)
14138 ImGuiContext& g = *GImGui;
14139 if (!g.NavWindow)
14140 return;
14141
14142 ImGuiNavItemData* result = &g.NavInitResult;
14143 if (g.NavId != result->ID)
14144 {
14145 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14146 g.NavJustMovedToId = result->ID;
14147 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14148 g.NavJustMovedToKeyMods = 0;
14149 g.NavJustMovedToIsTabbing = false;
14150 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14151 }
14152
14153 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
14154 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
14155 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14156 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
14157 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
14158 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14159 g.NavLastValidSelectionUserData = result->SelectionUserData;
14160 if (g.NavInitRequestFromMove)
14161 SetNavCursorVisibleAfterMove();
14162}
14163
14164// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
14165static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
14166{
14167 // Bias initial rect
14168 ImGuiContext& g = *GImGui;
14169 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
14170
14171 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
14172 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
14173 // - But each successful move sets new bias on one axis, only cleared when using mouse.
14174 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
14175 {
14176 if (preferred_pos_rel.x == FLT_MAX)
14177 preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
14178 if (preferred_pos_rel.y == FLT_MAX)
14179 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
14180 }
14181
14182 // Apply general bias on the other axis
14183 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
14184 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
14185 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
14186 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
14187}
14188
14189void ImGui::NavUpdateCreateMoveRequest()
14190{
14191 ImGuiContext& g = *GImGui;
14192 ImGuiIO& io = g.IO;
14193 ImGuiWindow* window = g.NavWindow;
14194 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14195 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14196
14197 if (g.NavMoveForwardToNextFrame && window != NULL)
14198 {
14199 // 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)
14200 // (preserve most state, which were already set by the NavMoveRequestForward() function)
14201 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
14202 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
14203 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
14204 }
14205 else
14206 {
14207 // Initiate directional inputs request
14208 g.NavMoveDir = ImGuiDir_None;
14209 g.NavMoveFlags = ImGuiNavMoveFlags_None;
14210 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
14211 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
14212 {
14213 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
14214 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; }
14215 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; }
14216 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; }
14217 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; }
14218 }
14219 g.NavMoveClipDir = g.NavMoveDir;
14220 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14221 }
14222
14223 // Update PageUp/PageDown/Home/End scroll
14224 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
14225 float scoring_page_offset_y = 0.0f;
14226 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
14227 scoring_page_offset_y = NavUpdatePageUpPageDown();
14228
14229 // [DEBUG] Always send a request when holding Ctrl. Hold Ctrl + Arrow change the direction.
14230#if IMGUI_DEBUG_NAV_SCORING
14231 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
14232 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
14233 if (io.KeyCtrl)
14234 {
14235 if (g.NavMoveDir == ImGuiDir_None)
14236 g.NavMoveDir = g.NavMoveDirForDebug;
14237 g.NavMoveClipDir = g.NavMoveDir;
14238 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
14239 }
14240#endif
14241
14242 // Submit
14243 g.NavMoveForwardToNextFrame = false;
14244 if (g.NavMoveDir != ImGuiDir_None)
14245 NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
14246
14247 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
14248 if (g.NavMoveSubmitted && g.NavId == 0)
14249 {
14250 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
14251 g.NavInitRequest = g.NavInitRequestFromMove = true;
14252 g.NavInitResult.ID = 0;
14253 if (g.IO.ConfigNavCursorVisibleAuto) // NO check for _NoNavInputs here as we assume MoveRequests cannot be created.
14254 g.NavCursorVisible = true;
14255 }
14256
14257 // When using gamepad, we project the reference nav bounding box into window visible area.
14258 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
14259 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
14260 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
14261 {
14262 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
14263 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
14264 ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
14265
14266 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
14267 // Otherwise 'inner_rect_rel' would be off on the move result frame.
14268 inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
14269
14270 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
14271 {
14272 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
14273 float pad_x = ImMin(inner_rect_rel.GetWidth(), window->FontRefSize * 0.5f);
14274 float pad_y = ImMin(inner_rect_rel.GetHeight(), window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
14275 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
14276 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
14277 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
14278 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
14279 window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
14280 g.NavId = 0;
14281 }
14282 }
14283
14284 // Prepare scoring rectangle.
14285 // 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)
14286 ImRect scoring_rect;
14287 if (window != NULL)
14288 {
14289 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
14290 scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
14291
14292 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)
14293 {
14294 // When we start from a visible location, score visible items and prioritize this result.
14295 if (window->InnerRect.Contains(scoring_rect))
14296 g.NavMoveFlags |= ImGuiNavMoveFlags_AlsoScoreVisibleSet;
14297 g.NavScoringNoClipRect = scoring_rect;
14298 scoring_rect.TranslateY(scoring_page_offset_y);
14299 g.NavScoringNoClipRect.Add(scoring_rect);
14300 }
14301
14302 //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Pre-bias
14303 if (g.NavMoveSubmitted)
14304 NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
14305 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
14306 //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Post-bias
14307 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRectFilled(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(100, 255, 0, 80)); } // [DEBUG]
14308 }
14309 g.NavScoringRect = scoring_rect;
14310 //g.NavScoringNoClipRect.Add(scoring_rect);
14311}
14312
14313void ImGui::NavUpdateCreateTabbingRequest()
14314{
14315 ImGuiContext& g = *GImGui;
14316 ImGuiWindow* window = g.NavWindow;
14317 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
14318 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs) || !g.ConfigNavEnableTabbing)
14319 return;
14320
14321 const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
14322 if (!tab_pressed)
14323 return;
14324
14325 // Initiate tabbing request
14326 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
14327 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
14328 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14329 if (nav_keyboard_active)
14330 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
14331 else
14332 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
14333 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
14334 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
14335 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
14336 NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
14337 g.NavTabbingCounter = -1;
14338}
14339
14340// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
14341void ImGui::NavMoveRequestApplyResult()
14342{
14343 ImGuiContext& g = *GImGui;
14344#if IMGUI_DEBUG_NAV_SCORING
14345 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
14346 return;
14347#endif
14348
14349 // Select which result to use
14350 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
14351
14352 // Tabbing forward wrap
14353 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
14354 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
14355 result = &g.NavTabbingResultFirst;
14356
14357 // 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)
14358 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14359 if (result == NULL)
14360 {
14361 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14362 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
14363 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14364 SetNavCursorVisibleAfterMove();
14365 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
14366 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
14367 return;
14368 }
14369
14370 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
14371 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
14372 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
14373 result = &g.NavMoveResultLocalVisible;
14374
14375 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
14376 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
14377 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
14378 result = &g.NavMoveResultOther;
14379 IM_ASSERT(g.NavWindow && result->Window);
14380
14381 // Scroll to keep newly navigated item fully into view.
14382 if (g.NavLayer == ImGuiNavLayer_Main)
14383 {
14384 ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
14385 ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
14386
14387 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
14388 {
14389 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
14390 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
14391 SetScrollY(result->Window, scroll_target);
14392 }
14393 }
14394
14395 if (g.NavWindow != result->Window)
14396 {
14397 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
14398 g.NavWindow = result->Window;
14399 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14400 }
14401
14402 // Clear active id unless requested not to
14403 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
14404 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
14405 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
14406 ClearActiveID();
14407
14408 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
14409 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
14410 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
14411 {
14412 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14413 g.NavJustMovedToId = result->ID;
14414 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14415 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
14416 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
14417 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14418 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
14419 }
14420
14421 // Apply new NavID/Focus
14422 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14423 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
14424 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
14425 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14426 g.NavLastValidSelectionUserData = result->SelectionUserData;
14427
14428 // Restore last preferred position for current axis
14429 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
14430 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
14431 {
14432 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
14433 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
14434 }
14435
14436 // Tabbing: Activates Inputable, otherwise only Focus
14437 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
14438 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
14439
14440 // Activate
14441 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
14442 {
14443 g.NavNextActivateId = result->ID;
14444 g.NavNextActivateFlags = ImGuiActivateFlags_None;
14445 if (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi)
14446 g.NavNextActivateFlags |= ImGuiActivateFlags_FromFocusApi;
14447 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14448 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
14449 }
14450
14451 // Make nav cursor visible
14452 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14453 SetNavCursorVisibleAfterMove();
14454}
14455
14456// Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
14457// FIXME: In order to support e.g. Escape to clear a selection we'll need:
14458// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
14459// - 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
14460static void ImGui::NavUpdateCancelRequest()
14461{
14462 ImGuiContext& g = *GImGui;
14463 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14464 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14465 if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
14466 return;
14467
14468 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
14469 if (g.ActiveId != 0)
14470 {
14471 ClearActiveID();
14472 }
14473 else if (g.NavLayer != ImGuiNavLayer_Main)
14474 {
14475 // Leave the "menu" layer
14476 NavRestoreLayer(ImGuiNavLayer_Main);
14477 SetNavCursorVisibleAfterMove();
14478 }
14479 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
14480 {
14481 // Exit child window
14482 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
14483 ImGuiWindow* parent_window = child_window->ParentWindow;
14484 IM_ASSERT(child_window->ChildId != 0);
14485 FocusWindow(parent_window);
14486 SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
14487 SetNavCursorVisibleAfterMove();
14488 }
14489 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
14490 {
14491 // Close open popup/menu
14492 ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
14493 }
14494 else
14495 {
14496 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
14497 // FIXME-NAV: This should happen on window appearing.
14498 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14499 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
14500 g.NavWindow->NavLastIds[0] = 0;
14501
14502 // Clear nav focus
14503 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14504 g.NavId = 0;
14505 if (g.IO.ConfigNavEscapeClearFocusWindow)
14506 FocusWindow(NULL);
14507 }
14508}
14509
14510static void ImGui::NavUpdateContextMenuRequest()
14511{
14512 ImGuiContext& g = *GImGui;
14513 g.NavOpenContextMenuItemId = g.NavOpenContextMenuWindowId = 0;
14514 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14515 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0;
14516 if ((!nav_keyboard_active && !nav_gamepad_active) || g.NavWindow == NULL)
14517 return;
14518
14519 bool request = false;
14520 request |= nav_keyboard_active && (IsKeyReleased(ImGuiKey_Menu, ImGuiKeyOwner_NoOwner) || (IsKeyPressed(ImGuiKey_F10, ImGuiInputFlags_None, ImGuiKeyOwner_NoOwner) && g.IO.KeyMods == ImGuiMod_Shift));
14521 request |= nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadContextMenu, ImGuiInputFlags_None, ImGuiKeyOwner_NoOwner);
14522 if (!request)
14523 return;
14524 g.NavOpenContextMenuItemId = g.NavId;
14525 g.NavOpenContextMenuWindowId = g.NavWindow->ID;
14526
14527 // Allow triggering for Begin()..BeginPopupContextItem(). A possible alternative would be to use g.NavLayer == ImGuiNavLayer_Menu.
14528 if (g.NavId == g.NavWindow->GetID("#CLOSE") || g.NavId == g.NavWindow->GetID("#COLLAPSE"))
14529 g.NavOpenContextMenuItemId = g.NavWindow->MoveId;
14530
14531 g.NavInputSource = ImGuiInputSource_Keyboard;
14532 SetNavCursorVisibleAfterMove();
14533}
14534
14535// Handle PageUp/PageDown/Home/End keys
14536// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
14537// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
14538// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
14539static float ImGui::NavUpdatePageUpPageDown()
14540{
14541 ImGuiContext& g = *GImGui;
14542 ImGuiWindow* window = g.NavWindow;
14543 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
14544 return 0.0f;
14545
14546 const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
14547 const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
14548 const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14549 const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14550 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
14551 return 0.0f;
14552
14553 if (g.NavLayer != ImGuiNavLayer_Main)
14554 NavRestoreLayer(ImGuiNavLayer_Main);
14555
14556 if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY)
14557 {
14558 // Fallback manual-scroll when window has no navigable item
14559 if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14560 SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
14561 else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14562 SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
14563 else if (home_pressed)
14564 SetScrollY(window, 0.0f);
14565 else if (end_pressed)
14566 SetScrollY(window, window->ScrollMax.y);
14567 }
14568 else
14569 {
14570 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
14571 const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight());
14572 float nav_scoring_rect_offset_y = 0.0f;
14573 if (IsKeyPressed(ImGuiKey_PageUp, true))
14574 {
14575 nav_scoring_rect_offset_y = -page_offset_y;
14576 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)
14577 g.NavMoveClipDir = ImGuiDir_Up;
14578 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_IsPageMove; // ImGuiNavMoveFlags_AlsoScoreVisibleSet may be added later
14579 }
14580 else if (IsKeyPressed(ImGuiKey_PageDown, true))
14581 {
14582 nav_scoring_rect_offset_y = +page_offset_y;
14583 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)
14584 g.NavMoveClipDir = ImGuiDir_Down;
14585 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_IsPageMove; // ImGuiNavMoveFlags_AlsoScoreVisibleSet may be added later
14586 }
14587 else if (home_pressed)
14588 {
14589 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
14590 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
14591 // Preserve current horizontal position if we have any.
14592 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
14593 if (nav_rect_rel.IsInverted())
14594 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14595 g.NavMoveDir = ImGuiDir_Down;
14596 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14597 // FIXME-NAV: MoveClipDir left to _None, intentional?
14598 }
14599 else if (end_pressed)
14600 {
14601 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
14602 if (nav_rect_rel.IsInverted())
14603 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14604 g.NavMoveDir = ImGuiDir_Up;
14605 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14606 // FIXME-NAV: MoveClipDir left to _None, intentional?
14607 }
14608 return nav_scoring_rect_offset_y;
14609 }
14610 return 0.0f;
14611}
14612
14613static void ImGui::NavEndFrame()
14614{
14615 ImGuiContext& g = *GImGui;
14616
14617 // Show Ctrl+Tab list window
14618 if (g.NavWindowingTarget != NULL)
14619 NavUpdateWindowingOverlay();
14620
14621 // Perform wrap-around in menus
14622 // 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.
14623 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
14624 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
14625 NavUpdateCreateWrappingRequest();
14626}
14627
14628static void ImGui::NavUpdateCreateWrappingRequest()
14629{
14630 ImGuiContext& g = *GImGui;
14631 ImGuiWindow* window = g.NavWindow;
14632
14633 bool do_forward = false;
14634 ImRect bb_rel = window->NavRectRel[g.NavLayer];
14635 ImGuiDir clip_dir = g.NavMoveDir;
14636
14637 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
14638 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14639
14640 // Menu layer does not maintain scrolling / content size (#9178)
14641 ImVec2 wrap_size = (g.NavLayer == ImGuiNavLayer_Menu) ? window->Size : window->ContentSize + window->WindowPadding;
14642
14643 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14644 {
14645 bb_rel.Min.x = bb_rel.Max.x = wrap_size.x;
14646 if (move_flags & ImGuiNavMoveFlags_WrapX)
14647 {
14648 bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
14649 clip_dir = ImGuiDir_Up;
14650 }
14651 do_forward = true;
14652 }
14653 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14654 {
14655 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
14656 if (move_flags & ImGuiNavMoveFlags_WrapX)
14657 {
14658 bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
14659 clip_dir = ImGuiDir_Down;
14660 }
14661 do_forward = true;
14662 }
14663 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14664 {
14665 bb_rel.Min.y = bb_rel.Max.y = wrap_size.y;
14666 if (move_flags & ImGuiNavMoveFlags_WrapY)
14667 {
14668 bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
14669 clip_dir = ImGuiDir_Left;
14670 }
14671 do_forward = true;
14672 }
14673 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14674 {
14675 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
14676 if (move_flags & ImGuiNavMoveFlags_WrapY)
14677 {
14678 bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
14679 clip_dir = ImGuiDir_Right;
14680 }
14681 do_forward = true;
14682 }
14683 if (!do_forward)
14684 return;
14685 window->NavRectRel[g.NavLayer] = bb_rel;
14686 NavClearPreferredPosForAxis(ImGuiAxis_X);
14687 NavClearPreferredPosForAxis(ImGuiAxis_Y);
14688 NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
14689}
14690
14691// Can we focus this window with Ctrl+Tab (or PadMenu + PadFocusPrev/PadFocusNext)
14692// Note that NoNavFocus makes the window not reachable with Ctrl+Tab but it can still be focused with mouse or programmatically.
14693// If you want a window to never be focused, you may use the e.g. NoInputs flag.
14694bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
14695{
14696 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
14697}
14698
14699static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
14700{
14701 ImGuiContext& g = *GImGui;
14702 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
14703 if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
14704 return g.WindowsFocusOrder[i];
14705 return NULL;
14706}
14707
14708static void NavUpdateWindowingTarget(int focus_change_dir)
14709{
14710 ImGuiContext& g = *GImGui;
14711 IM_ASSERT(g.NavWindowingTarget);
14712 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
14713 return;
14714
14715 const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
14716 ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
14717 if (!window_target)
14718 window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
14719 if (window_target) // Don't reset windowing target if there's a single window in the list
14720 {
14721 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
14722 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14723 }
14724 g.NavWindowingToggleLayer = false;
14725}
14726
14727// Apply focus and close overlay
14728static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window)
14729{
14730 ImGuiContext& g = *GImGui;
14731 if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)
14732 {
14733 ClearActiveID();
14734 SetNavCursorVisibleAfterMove();
14735 ClosePopupsOverWindow(apply_focus_window, false);
14736 FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
14737 IM_ASSERT(g.NavWindow != NULL);
14738 apply_focus_window = g.NavWindow;
14739 if (apply_focus_window->NavLastIds[0] == 0)
14740 NavInitWindow(apply_focus_window, false);
14741
14742 // If the window has ONLY a menu layer (no main layer), select it directly
14743 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
14744 // so Ctrl+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
14745 // the target window as already been previewed once.
14746 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
14747 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
14748 // won't be valid.
14749 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
14750 g.NavLayer = ImGuiNavLayer_Menu;
14751 }
14752 g.NavWindowingTarget = NULL;
14753}
14754
14755// Windowing management mode
14756// Keyboard: Ctrl+Tab (change focus/move/resize), Alt (toggle menu layer)
14757// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
14758static void ImGui::NavUpdateWindowing()
14759{
14760 ImGuiContext& g = *GImGui;
14761 ImGuiIO& io = g.IO;
14762
14763 ImGuiWindow* apply_focus_window = NULL;
14764 bool apply_toggle_layer = false;
14765
14766 ImGuiWindow* modal_window = GetTopMostPopupModal();
14767 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.
14768 if (!allow_windowing)
14769 g.NavWindowingTarget = NULL;
14770
14771 // Fade out
14772 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
14773 {
14774 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
14775 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
14776 g.NavWindowingTargetAnim = NULL;
14777 }
14778
14779 // Start Ctrl+Tab or Square+L/R window selection
14780 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
14781 const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing");
14782 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14783 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14784 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14785 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14786 const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id);
14787 const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad;
14788 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
14789 bool just_started_windowing_from_null_focus = false;
14790 if (start_toggling_with_gamepad)
14791 {
14792 g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer
14793 g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu;
14794 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad;
14795 }
14796 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
14797 if (ImGuiWindow* window = (g.NavWindow && IsWindowNavFocusable(g.NavWindow)) ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
14798 {
14799 if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad)
14800 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
14801 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
14802 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14803 g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
14804 if (g.NavWindow == NULL)
14805 just_started_windowing_from_null_focus = true;
14806
14807 // 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.
14808 if (keyboard_next_window || keyboard_prev_window)
14809 SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
14810 }
14811
14812 // Gamepad update
14813 if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad)
14814 {
14815 if (g.NavWindowingTarget != NULL)
14816 {
14817 // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise
14818 // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast.
14819 g.NavWindowingTimer += io.DeltaTime;
14820 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
14821
14822 // Select window to focus
14823 const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
14824 if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
14825 {
14826 NavUpdateWindowingTarget(focus_change_dir);
14827 g.NavWindowingHighlightAlpha = 1.0f;
14828 }
14829 }
14830
14831 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
14832 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
14833 {
14834 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
14835 if (g.NavWindowingToggleLayer && g.NavWindow)
14836 apply_toggle_layer = true;
14837 else if (!g.NavWindowingToggleLayer)
14838 apply_focus_window = g.NavWindowingTarget;
14839 g.NavWindowingTarget = NULL;
14840 g.NavWindowingToggleLayer = false;
14841 }
14842 }
14843
14844 // Keyboard: Focus
14845 if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
14846 {
14847 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast Ctrl+Tab doesn't add visual noise
14848 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
14849 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
14850 g.NavWindowingTimer += io.DeltaTime;
14851 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
14852 if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
14853 NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1);
14854 else if ((io.KeyMods & shared_mods) != shared_mods)
14855 apply_focus_window = g.NavWindowingTarget;
14856 }
14857
14858 // Keyboard: Press and Release Alt to toggle menu layer
14859 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
14860 bool windowing_toggle_layer_start = false;
14861 if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14862 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
14863 if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
14864 {
14865 windowing_toggle_layer_start = true;
14866 g.NavWindowingToggleLayer = true;
14867 g.NavWindowingToggleKey = windowing_toggle_key;
14868 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard;
14869 break;
14870 }
14871 if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
14872 {
14873 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
14874 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
14875 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
14876 // We cancel toggling nav layer if an owner has claimed the key.
14877 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
14878 g.NavWindowingToggleLayer = false;
14879 else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time)
14880 g.NavWindowingToggleLayer = false;
14881 else if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
14882 g.NavWindowingToggleLayer = false;
14883
14884 // Apply layer toggle on Alt release
14885 // 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.
14886 if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
14887 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
14888 if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
14889 apply_toggle_layer = true;
14890 if (!IsKeyDown(g.NavWindowingToggleKey))
14891 g.NavWindowingToggleLayer = false;
14892 }
14893
14894 // Move window
14895 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
14896 {
14897 ImVec2 nav_move_dir;
14898 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
14899 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
14900 if (g.NavInputSource == ImGuiInputSource_Gamepad)
14901 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
14902 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
14903 {
14904 const float NAV_MOVE_SPEED = 800.0f;
14905 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * GetScale();
14906 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
14907 g.NavHighlightItemUnderNav = true;
14908 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
14909 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
14910 {
14911 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
14912 SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
14913 g.NavWindowingAccumDeltaPos -= accum_floored;
14914 }
14915 }
14916 }
14917
14918 // Apply final focus
14919 if (apply_focus_window)
14920 NavUpdateWindowingApplyFocus(apply_focus_window);
14921
14922 // Apply menu/layer toggle
14923 if (apply_toggle_layer && g.NavWindow)
14924 {
14925 ClearActiveID();
14926
14927 // Move to parent menu if necessary
14928 ImGuiWindow* new_nav_window = g.NavWindow;
14929 while (new_nav_window->ParentWindow
14930 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
14931 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
14932 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
14933 new_nav_window = new_nav_window->ParentWindow;
14934 if (new_nav_window != g.NavWindow)
14935 {
14936 ImGuiWindow* old_nav_window = g.NavWindow;
14937 FocusWindow(new_nav_window);
14938 new_nav_window->NavLastChildNavWindow = old_nav_window;
14939 }
14940
14941 // Toggle layer
14942 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
14943 if (new_nav_layer != g.NavLayer)
14944 {
14945 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
14946 if (new_nav_layer == ImGuiNavLayer_Menu)
14947 g.NavWindow->NavLastIds[new_nav_layer] = 0;
14948 NavRestoreLayer(new_nav_layer);
14949 SetNavCursorVisibleAfterMove();
14950 }
14951 }
14952}
14953
14954// Window has already passed the IsWindowNavFocusable()
14955static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
14956{
14957 if (window->Flags & ImGuiWindowFlags_Popup)
14958 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
14959 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
14960 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
14961 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
14962}
14963
14964// Overlay displayed when using Ctrl+Tab. Called by EndFrame().
14965void ImGui::NavUpdateWindowingOverlay()
14966{
14967 ImGuiContext& g = *GImGui;
14968 IM_ASSERT(g.NavWindowingTarget != NULL);
14969
14970 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
14971 return;
14972
14973 const ImGuiViewport* viewport = GetMainViewport();
14974 SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
14975 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
14976 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
14977 Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
14978 g.NavWindowingListWindow = g.CurrentWindow;
14979 if (g.ContextName[0] != 0)
14980 SeparatorText(g.ContextName);
14981 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
14982 {
14983 ImGuiWindow* window = g.WindowsFocusOrder[n];
14984 IM_ASSERT(window != NULL); // Fix static analyzers
14985 if (!IsWindowNavFocusable(window))
14986 continue;
14987 const char* label = window->Name;
14988 if (label == FindRenderedTextEnd(label))
14989 label = GetFallbackWindowNameForWindowingList(window);
14990 Selectable(label, g.NavWindowingTarget == window);
14991 }
14992 End();
14993 PopStyleVar();
14994}
14995
14996//-----------------------------------------------------------------------------
14997// [SECTION] DRAG AND DROP
14998//-----------------------------------------------------------------------------
14999
15000bool ImGui::IsDragDropActive()
15001{
15002 ImGuiContext& g = *GImGui;
15003 return g.DragDropActive;
15004}
15005
15006void ImGui::ClearDragDrop()
15007{
15008 ImGuiContext& g = *GImGui;
15009 if (g.DragDropActive)
15010 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
15011 g.DragDropActive = false;
15012 g.DragDropPayload.Clear();
15013 g.DragDropAcceptFlagsCurr = ImGuiDragDropFlags_None;
15014 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
15015 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
15016 g.DragDropAcceptFrameCount = -1;
15017
15018 g.DragDropPayloadBufHeap.clear();
15019 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
15020}
15021
15022bool ImGui::BeginTooltipHidden()
15023{
15024 ImGuiContext& g = *GImGui;
15025 bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
15026 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
15027 return ret;
15028}
15029
15030// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
15031// If the item has an identifier:
15032// - This assume/require the item to be activated (typically via ButtonBehavior).
15033// - 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.
15034// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
15035// If the item has no identifier:
15036// - Currently always assume left mouse button.
15037bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
15038{
15039 ImGuiContext& g = *GImGui;
15040 ImGuiWindow* window = g.CurrentWindow;
15041
15042 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
15043 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
15044 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
15045
15046 bool source_drag_active = false;
15047 ImGuiID source_id = 0;
15048 ImGuiID source_parent_id = 0;
15049 if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
15050 {
15051 source_id = g.LastItemData.ID;
15052 if (source_id != 0)
15053 {
15054 // Common path: items with ID
15055 if (g.ActiveId != source_id)
15056 return false;
15057 if (g.ActiveIdMouseButton != -1)
15058 mouse_button = g.ActiveIdMouseButton;
15059 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15060 return false;
15061 g.ActiveIdAllowOverlap = false;
15062 }
15063 else
15064 {
15065 // Uncommon path: items without ID
15066 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15067 return false;
15068 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
15069 return false;
15070
15071 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
15072 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
15073 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
15074 {
15075 IM_ASSERT(0);
15076 return false;
15077 }
15078
15079 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
15080 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
15081 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
15082 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
15083 // Rely on keeping other window->LastItemXXX fields intact.
15084 source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
15085 KeepAliveID(source_id);
15086 bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.ItemFlags);
15087 if (is_hovered && g.IO.MouseClicked[mouse_button])
15088 {
15089 SetActiveID(source_id, window);
15090 FocusWindow(window);
15091 }
15092 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
15093 g.ActiveIdAllowOverlap = is_hovered;
15094 }
15095 if (g.ActiveId != source_id)
15096 return false;
15097 source_parent_id = window->IDStack.back();
15098 source_drag_active = IsMouseDragging(mouse_button);
15099
15100 // Disable navigation and key inputs while dragging + cancel existing request if any
15101 SetActiveIdUsingAllKeyboardKeys();
15102 }
15103 else
15104 {
15105 // When ImGuiDragDropFlags_SourceExtern is set:
15106 window = NULL;
15107 source_id = ImHashStr("#SourceExtern");
15108 source_drag_active = true;
15109 mouse_button = g.IO.MouseDown[0] ? 0 : -1;
15110 KeepAliveID(source_id);
15111 SetActiveID(source_id, NULL);
15112 }
15113
15114 IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15115 if (!source_drag_active)
15116 return false;
15117
15118 // Activate drag and drop
15119 if (!g.DragDropActive)
15120 {
15121 IM_ASSERT(source_id != 0);
15122 ClearDragDrop();
15123 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
15124 source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
15125 ImGuiPayload& payload = g.DragDropPayload;
15126 payload.SourceId = source_id;
15127 payload.SourceParentId = source_parent_id;
15128 g.DragDropActive = true;
15129 g.DragDropSourceFlags = flags;
15130 g.DragDropMouseButton = mouse_button;
15131 if (payload.SourceId == g.ActiveId)
15132 g.ActiveIdNoClearOnFocusLoss = true;
15133 }
15134 g.DragDropSourceFrameCount = g.FrameCount;
15135 g.DragDropWithinSource = true;
15136
15137 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15138 {
15139 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
15140 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
15141 bool ret;
15142 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlagsPrev & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
15143 ret = BeginTooltipHidden();
15144 else
15145 ret = BeginTooltip();
15146 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddenAndSkipItemsForCurrentFrame().
15147 IM_UNUSED(ret);
15148 }
15149
15150 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
15151 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
15152
15153 return true;
15154}
15155
15156void ImGui::EndDragDropSource()
15157{
15158 ImGuiContext& g = *GImGui;
15159 IM_ASSERT(g.DragDropActive);
15160 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
15161
15162 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15163 EndTooltip();
15164
15165 // Discard the drag if have not called SetDragDropPayload()
15166 if (g.DragDropPayload.DataFrameCount == -1)
15167 ClearDragDrop();
15168 g.DragDropWithinSource = false;
15169}
15170
15171// Use 'cond' to choose to submit payload on drag start or every frame
15172bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
15173{
15174 ImGuiContext& g = *GImGui;
15175 ImGuiPayload& payload = g.DragDropPayload;
15176 if (cond == 0)
15177 cond = ImGuiCond_Always;
15178
15179 IM_ASSERT(type != NULL);
15180 IM_ASSERT(ImStrlen(type) < IM_COUNTOF(payload.DataType) && "Payload type can be at most 32 characters long");
15181 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
15182 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
15183 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
15184
15185 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
15186 {
15187 // Copy payload
15188 ImStrncpy(payload.DataType, type, IM_COUNTOF(payload.DataType));
15189 g.DragDropPayloadBufHeap.resize(0);
15190 if (data_size > sizeof(g.DragDropPayloadBufLocal))
15191 {
15192 // Store in heap
15193 g.DragDropPayloadBufHeap.resize((int)data_size);
15194 payload.Data = g.DragDropPayloadBufHeap.Data;
15195 memcpy(payload.Data, data, (size_t)(int)data_size);
15196 }
15197 else if (data_size > 0)
15198 {
15199 // Store locally
15200 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
15201 payload.Data = g.DragDropPayloadBufLocal;
15202 memcpy(payload.Data, data, (size_t)(int)data_size);
15203 }
15204 else
15205 {
15206 payload.Data = NULL;
15207 }
15208 payload.DataSize = (int)data_size;
15209 }
15210 payload.DataFrameCount = g.FrameCount;
15211
15212 // Return whether the payload has been accepted
15213 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
15214}
15215
15216bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
15217{
15218 ImGuiContext& g = *GImGui;
15219 if (!g.DragDropActive)
15220 return false;
15221
15222 ImGuiWindow* window = g.CurrentWindow;
15223 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15224 if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
15225 return false;
15226 IM_ASSERT(id != 0);
15227 if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
15228 return false;
15229 if (window->SkipItems)
15230 return false;
15231
15232 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15233 g.DragDropTargetRect = bb;
15234 g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
15235 g.DragDropTargetId = id;
15236 g.DragDropTargetFullViewport = 0;
15237 g.DragDropWithinTarget = true;
15238 return true;
15239}
15240
15241// Typical usage would be:
15242// if (!ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
15243// if (ImGui::BeginDragDropTargetViewport(ImGui::GetMainViewport(), NULL))
15244// But we are leaving the hover test to the caller for maximum flexibility.
15245bool ImGui::BeginDragDropTargetViewport(ImGuiViewport* viewport, const ImRect* p_bb)
15246{
15247 ImGuiContext& g = *GImGui;
15248 if (!g.DragDropActive)
15249 return false;
15250
15251 ImRect bb = p_bb ? *p_bb : ((ImGuiViewportP*)viewport)->GetWorkRect();
15252 ImGuiID id = viewport->ID;
15253 if (!IsMouseHoveringRect(bb.Min, bb.Max, false) || (id == g.DragDropPayload.SourceId))
15254 return false;
15255
15256 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15257 g.DragDropTargetRect = bb;
15258 g.DragDropTargetClipRect = bb;
15259 g.DragDropTargetId = id;
15260 g.DragDropTargetFullViewport = id;
15261 g.DragDropWithinTarget = true;
15262 return true;
15263}
15264
15265// We don't use BeginDragDropTargetCustom() and duplicate its code because:
15266// 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.
15267// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
15268// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
15269bool ImGui::BeginDragDropTarget()
15270{
15271 ImGuiContext& g = *GImGui;
15272 if (!g.DragDropActive)
15273 return false;
15274
15275 ImGuiWindow* window = g.CurrentWindow;
15276 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
15277 return false;
15278 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15279 if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)
15280 return false;
15281
15282 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
15283 ImGuiID id = g.LastItemData.ID;
15284 if (id == 0)
15285 {
15286 id = window->GetIDFromRectangle(display_rect);
15287 KeepAliveID(id);
15288 }
15289 if (g.DragDropPayload.SourceId == id)
15290 return false;
15291
15292 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15293 g.DragDropTargetRect = display_rect;
15294 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
15295 g.DragDropTargetId = id;
15296 g.DragDropWithinTarget = true;
15297 return true;
15298}
15299
15300bool ImGui::IsDragDropPayloadBeingAccepted()
15301{
15302 ImGuiContext& g = *GImGui;
15303 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
15304}
15305
15306const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
15307{
15308 ImGuiContext& g = *GImGui;
15309 ImGuiPayload& payload = g.DragDropPayload;
15310 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
15311 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
15312 if (type != NULL && !payload.IsDataType(type))
15313 return NULL;
15314
15315 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
15316 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
15317 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
15318 ImRect r = g.DragDropTargetRect;
15319 float r_surface = r.GetWidth() * r.GetHeight();
15320 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
15321 return NULL;
15322
15323 g.DragDropAcceptFlagsCurr = flags;
15324 g.DragDropAcceptIdCurr = g.DragDropTargetId;
15325 g.DragDropAcceptIdCurrRectSurface = r_surface;
15326 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
15327
15328 // Render default drop visuals
15329 payload.Preview = was_accepted_previously;
15330 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
15331 const bool draw_target_rect = payload.Preview && !(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect);
15332 if (draw_target_rect && g.DragDropTargetFullViewport != 0)
15333 {
15334 ImRect bb = g.DragDropTargetRect;
15335 bb.Expand(-3.5f);
15336 RenderDragDropTargetRectEx(GetForegroundDrawList(), bb, g.Style.DragDropTargetRounding);
15337 }
15338 else if (draw_target_rect)
15339 {
15340 RenderDragDropTargetRectForItem(r);
15341 }
15342
15343 g.DragDropAcceptFrameCount = g.FrameCount;
15344 if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
15345 payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
15346 else
15347 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()
15348 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
15349 return NULL;
15350
15351 if (payload.Delivery)
15352 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
15353 return &payload;
15354}
15355
15356// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
15357void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb)
15358{
15359 ImGuiContext& g = *GImGui;
15360 ImGuiWindow* window = g.CurrentWindow;
15361 ImRect bb_display = bb;
15362 bb_display.ClipWith(g.DragDropTargetClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
15363 bb_display.Expand(g.Style.DragDropTargetPadding);
15364 bool push_clip_rect = !window->ClipRect.Contains(bb_display);
15365 if (push_clip_rect)
15366 window->DrawList->PushClipRectFullScreen();
15367 RenderDragDropTargetRectEx(window->DrawList, bb_display, g.Style.DragDropTargetRounding);
15368 if (push_clip_rect)
15369 window->DrawList->PopClipRect();
15370}
15371
15372void ImGui::RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb, float rounding)
15373{
15374 ImGuiContext& g = *GImGui;
15375 draw_list->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTargetBg), rounding, 0);
15376 draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), rounding, g.Style.DragDropTargetBorderSize);
15377}
15378
15379const ImGuiPayload* ImGui::GetDragDropPayload()
15380{
15381 ImGuiContext& g = *GImGui;
15382 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
15383}
15384
15385void ImGui::EndDragDropTarget()
15386{
15387 ImGuiContext& g = *GImGui;
15388 IM_ASSERT(g.DragDropActive);
15389 IM_ASSERT(g.DragDropWithinTarget);
15390 g.DragDropWithinTarget = false;
15391
15392 // Clear drag and drop state payload right after delivery
15393 if (g.DragDropPayload.Delivery)
15394 ClearDragDrop();
15395}
15396
15397//-----------------------------------------------------------------------------
15398// [SECTION] LOGGING/CAPTURING
15399//-----------------------------------------------------------------------------
15400// All text output from the interface can be captured into tty/file/clipboard.
15401// By default, tree nodes are automatically opened during logging.
15402//-----------------------------------------------------------------------------
15403
15404// Pass text data straight to log (without being displayed)
15405static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
15406{
15407 if (g.LogFile)
15408 {
15409 g.LogBuffer.Buf.resize(0);
15410 g.LogBuffer.appendfv(fmt, args);
15411 ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
15412 }
15413 else
15414 {
15415 g.LogBuffer.appendfv(fmt, args);
15416 }
15417}
15418
15419void ImGui::LogText(const char* fmt, ...)
15420{
15421 ImGuiContext& g = *GImGui;
15422 if (!g.LogEnabled)
15423 return;
15424
15425 va_list args;
15426 va_start(args, fmt);
15427 LogTextV(g, fmt, args);
15428 va_end(args);
15429}
15430
15431void ImGui::LogTextV(const char* fmt, va_list args)
15432{
15433 ImGuiContext& g = *GImGui;
15434 if (!g.LogEnabled)
15435 return;
15436
15437 LogTextV(g, fmt, args);
15438}
15439
15440// Internal version that takes a position to decide on newline placement and pad items according to their depth.
15441// We split text into individual lines to add current tree level padding
15442// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
15443void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
15444{
15445 ImGuiContext& g = *GImGui;
15446 ImGuiWindow* window = g.CurrentWindow;
15447
15448 const char* prefix = g.LogNextPrefix;
15449 const char* suffix = g.LogNextSuffix;
15450 g.LogNextPrefix = g.LogNextSuffix = NULL;
15451
15452 if (!text_end)
15453 text_end = FindRenderedTextEnd(text, text_end);
15454
15455 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + ImMax(g.Style.FramePadding.y, g.Style.ItemSpacing.y) + 1);
15456 if (ref_pos)
15457 g.LogLinePosY = ref_pos->y;
15458 if (log_new_line)
15459 {
15460 LogText(IM_NEWLINE);
15461 g.LogLineFirstItem = true;
15462 }
15463
15464 if (prefix)
15465 LogRenderedText(ref_pos, prefix, prefix + ImStrlen(prefix)); // Calculate end ourself to ensure "##" are included here.
15466
15467 // Re-adjust padding if we have popped out of our starting depth
15468 if (g.LogDepthRef > window->DC.TreeDepth)
15469 g.LogDepthRef = window->DC.TreeDepth;
15470 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
15471
15472 const char* text_remaining = text;
15473 for (;;)
15474 {
15475 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
15476 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
15477 const char* line_start = text_remaining;
15478 const char* line_end = ImStreolRange(line_start, text_end);
15479 const bool is_last_line = (line_end == text_end);
15480 if (line_start != line_end || !is_last_line)
15481 {
15482 const int line_length = (int)(line_end - line_start);
15483 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
15484 LogText("%*s%.*s", indentation, "", line_length, line_start);
15485 g.LogLineFirstItem = false;
15486 if (*line_end == '\n')
15487 {
15488 LogText(IM_NEWLINE);
15489 g.LogLineFirstItem = true;
15490 }
15491 }
15492 if (is_last_line)
15493 break;
15494 text_remaining = line_end + 1;
15495 }
15496
15497 if (suffix)
15498 LogRenderedText(ref_pos, suffix, suffix + ImStrlen(suffix));
15499}
15500
15501// Start logging/capturing text output
15502void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
15503{
15504 ImGuiContext& g = *GImGui;
15505 ImGuiWindow* window = g.CurrentWindow;
15506 IM_ASSERT(g.LogEnabled == false);
15507 IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
15508 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
15509
15510 g.LogEnabled = g.ItemUnclipByLog = true;
15511 g.LogFlags = flags;
15512 g.LogWindow = window;
15513 g.LogNextPrefix = g.LogNextSuffix = NULL;
15514 g.LogDepthRef = window->DC.TreeDepth;
15515 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
15516 g.LogLinePosY = FLT_MAX;
15517 g.LogLineFirstItem = true;
15518}
15519
15520// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
15521void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
15522{
15523 ImGuiContext& g = *GImGui;
15524 g.LogNextPrefix = prefix;
15525 g.LogNextSuffix = suffix;
15526}
15527
15528void ImGui::LogToTTY(int auto_open_depth)
15529{
15530 ImGuiContext& g = *GImGui;
15531 if (g.LogEnabled)
15532 return;
15533 IM_UNUSED(auto_open_depth);
15534#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15535 LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth);
15536 g.LogFile = stdout;
15537#endif
15538}
15539
15540// Start logging/capturing text output to given file
15541void ImGui::LogToFile(int auto_open_depth, const char* filename)
15542{
15543 ImGuiContext& g = *GImGui;
15544 if (g.LogEnabled)
15545 return;
15546
15547 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
15548 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
15549 // By opening the file in binary mode "ab" we have consistent output everywhere.
15550 if (!filename)
15551 filename = g.IO.LogFilename;
15552 if (!filename || !filename[0])
15553 return;
15554 ImFileHandle f = ImFileOpen(filename, "ab");
15555 if (!f)
15556 {
15557 IM_ASSERT(0);
15558 return;
15559 }
15560
15561 LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth);
15562 g.LogFile = f;
15563}
15564
15565// Start logging/capturing text output to clipboard
15566void ImGui::LogToClipboard(int auto_open_depth)
15567{
15568 ImGuiContext& g = *GImGui;
15569 if (g.LogEnabled)
15570 return;
15571 LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth);
15572}
15573
15574void ImGui::LogToBuffer(int auto_open_depth)
15575{
15576 ImGuiContext& g = *GImGui;
15577 if (g.LogEnabled)
15578 return;
15579 LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth);
15580}
15581
15582void ImGui::LogFinish()
15583{
15584 ImGuiContext& g = *GImGui;
15585 if (!g.LogEnabled)
15586 return;
15587
15588 LogText(IM_NEWLINE);
15589 switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
15590 {
15591 case ImGuiLogFlags_OutputTTY:
15592#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15593 fflush(g.LogFile);
15594#endif
15595 break;
15596 case ImGuiLogFlags_OutputFile:
15597 ImFileClose(g.LogFile);
15598 break;
15599 case ImGuiLogFlags_OutputBuffer:
15600 break;
15601 case ImGuiLogFlags_OutputClipboard:
15602 if (!g.LogBuffer.empty())
15603 SetClipboardText(g.LogBuffer.begin());
15604 break;
15605 default:
15606 IM_ASSERT(0);
15607 break;
15608 }
15609
15610 g.LogEnabled = g.ItemUnclipByLog = false;
15611 g.LogFlags = ImGuiLogFlags_None;
15612 g.LogFile = NULL;
15613 g.LogBuffer.clear();
15614}
15615
15616// Helper to display logging buttons
15617// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
15618void ImGui::LogButtons()
15619{
15620 ImGuiContext& g = *GImGui;
15621
15622 PushID("LogButtons");
15623#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15624 const bool log_to_tty = Button("Log To TTY"); SameLine();
15625#else
15626 const bool log_to_tty = false;
15627#endif
15628 const bool log_to_file = Button("Log To File"); SameLine();
15629 const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
15630 PushItemFlag(ImGuiItemFlags_NoTabStop, true);
15631 SetNextItemWidth(CalcTextSize("999").x);
15632 SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
15633 PopItemFlag();
15634 PopID();
15635
15636 // Start logging at the end of the function so that the buttons don't appear in the log
15637 if (log_to_tty)
15638 LogToTTY();
15639 if (log_to_file)
15640 LogToFile();
15641 if (log_to_clipboard)
15642 LogToClipboard();
15643}
15644
15645//-----------------------------------------------------------------------------
15646// [SECTION] SETTINGS
15647//-----------------------------------------------------------------------------
15648// - UpdateSettings() [Internal]
15649// - MarkIniSettingsDirty() [Internal]
15650// - FindSettingsHandler() [Internal]
15651// - ClearIniSettings() [Internal]
15652// - LoadIniSettingsFromDisk()
15653// - LoadIniSettingsFromMemory()
15654// - SaveIniSettingsToDisk()
15655// - SaveIniSettingsToMemory()
15656//-----------------------------------------------------------------------------
15657// - CreateNewWindowSettings() [Internal]
15658// - FindWindowSettingsByID() [Internal]
15659// - FindWindowSettingsByWindow() [Internal]
15660// - ClearWindowSettings() [Internal]
15661// - WindowSettingsHandler_***() [Internal]
15662//-----------------------------------------------------------------------------
15663
15664// Called by NewFrame()
15665void ImGui::UpdateSettings()
15666{
15667 // Load settings on first frame (if not explicitly loaded manually before)
15668 ImGuiContext& g = *GImGui;
15669 if (!g.SettingsLoaded)
15670 {
15671 IM_ASSERT(g.SettingsWindows.empty());
15672 if (g.IO.IniFilename)
15673 LoadIniSettingsFromDisk(g.IO.IniFilename);
15674 g.SettingsLoaded = true;
15675 }
15676
15677 // Save settings (with a delay after the last modification, so we don't spam disk too much)
15678 if (g.SettingsDirtyTimer > 0.0f)
15679 {
15680 g.SettingsDirtyTimer -= g.IO.DeltaTime;
15681 if (g.SettingsDirtyTimer <= 0.0f)
15682 {
15683 if (g.IO.IniFilename != NULL)
15684 SaveIniSettingsToDisk(g.IO.IniFilename);
15685 else
15686 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
15687 g.SettingsDirtyTimer = 0.0f;
15688 }
15689 }
15690}
15691
15692void ImGui::MarkIniSettingsDirty()
15693{
15694 ImGuiContext& g = *GImGui;
15695 if (g.SettingsDirtyTimer <= 0.0f)
15696 g.SettingsDirtyTimer = g.IO.IniSavingRate;
15697}
15698
15699void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
15700{
15701 ImGuiContext& g = *GImGui;
15702 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
15703 if (g.SettingsDirtyTimer <= 0.0f)
15704 g.SettingsDirtyTimer = g.IO.IniSavingRate;
15705}
15706
15707void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
15708{
15709 ImGuiContext& g = *GImGui;
15710 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
15711 g.SettingsHandlers.push_back(*handler);
15712}
15713
15714void ImGui::RemoveSettingsHandler(const char* type_name)
15715{
15716 ImGuiContext& g = *GImGui;
15717 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
15718 g.SettingsHandlers.erase(handler);
15719}
15720
15721ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
15722{
15723 ImGuiContext& g = *GImGui;
15724 const ImGuiID type_hash = ImHashStr(type_name);
15725 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15726 if (handler.TypeHash == type_hash)
15727 return &handler;
15728 return NULL;
15729}
15730
15731// Clear all settings (windows, tables, docking etc.)
15732void ImGui::ClearIniSettings()
15733{
15734 ImGuiContext& g = *GImGui;
15735 g.SettingsIniData.clear();
15736 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15737 if (handler.ClearAllFn != NULL)
15738 handler.ClearAllFn(&g, &handler);
15739}
15740
15741void ImGui::CleanupIniSettings(ImGuiSettingsCleanupArgs* args)
15742{
15743 ImGuiContext& g = *GImGui;
15744 if (args->DiscardAll)
15745 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15746 if (args->TypeHashFilter == 0 || handler.TypeHash == args->TypeHashFilter)
15747 if (handler.ClearAllFn != NULL)
15748 handler.ClearAllFn(&g, &handler);
15749 if (g.PlatformIO.Platform_SessionDate != 0 && args->DiscardOlderThanMonths != 0)
15750 {
15751 ImGuiPackedDate discard_older_than_date_p = g.PlatformIO.Platform_SessionDate;
15752 discard_older_than_date_p.SubtractMonths(args->DiscardOlderThanMonths);
15753 args->_DiscardOlderThanDate = discard_older_than_date_p.Unpack();
15754 }
15755 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15756 if (args->TypeHashFilter == 0 || handler.TypeHash == args->TypeHashFilter)
15757 if (handler.CleanupFn != NULL)
15758 handler.CleanupFn(&g, &handler, args);
15759}
15760
15761void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
15762{
15763 size_t file_data_size = 0;
15764 char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
15765 if (!file_data)
15766 return;
15767 if (file_data_size > 0)
15768 LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
15769 IM_FREE(file_data);
15770}
15771
15772// Zero-tolerance, no error reporting, cheap .ini parsing
15773// 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!
15774void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
15775{
15776 ImGuiContext& g = *GImGui;
15777 IM_ASSERT(g.Initialized);
15778 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
15779 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
15780
15781 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
15782 // 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..
15783 if (ini_size == 0)
15784 ini_size = ImStrlen(ini_data);
15785 g.SettingsIniData.Buf.resize((int)ini_size + 1);
15786 char* const buf = g.SettingsIniData.Buf.Data;
15787 char* const buf_end = buf + ini_size;
15788 memcpy(buf, ini_data, ini_size);
15789 buf_end[0] = 0;
15790
15791 // Call pre-read handlers
15792 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
15793 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15794 if (handler.ReadInitFn != NULL)
15795 handler.ReadInitFn(&g, &handler);
15796
15797 void* entry_data = NULL;
15798 ImGuiSettingsHandler* entry_handler = NULL;
15799
15800 char* line_end = NULL;
15801 for (char* line = buf; line < buf_end; line = line_end + 1)
15802 {
15803 // Skip new lines markers, then find end of the line
15804 while (*line == '\n' || *line == '\r')
15805 line++;
15806 line_end = line;
15807 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
15808 line_end++;
15809 line_end[0] = 0;
15810 if (line[0] == ';')
15811 continue;
15812 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
15813 {
15814 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
15815 line_end[-1] = 0;
15816 const char* name_end = line_end - 1;
15817 const char* type_start = line + 1;
15818 char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
15819 const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
15820 if (!type_end || !name_start)
15821 continue;
15822 *type_end = 0; // Overwrite first ']'
15823 name_start++; // Skip second '['
15824 entry_handler = FindSettingsHandler(type_start);
15825 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
15826 }
15827 else if (entry_handler != NULL && entry_data != NULL)
15828 {
15829 // Let type handler parse the line
15830 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
15831 }
15832 }
15833 g.SettingsLoaded = true;
15834
15835 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
15836 memcpy(buf, ini_data, ini_size);
15837
15838 // Call post-read handlers
15839 ImGuiSettingsCleanupArgs cleanup_args;
15840 if (g.IO.ConfigIniSettingsAutoDiscardMonths > 0)
15841 {
15842 cleanup_args.DiscardOlderThanMonths = g.IO.ConfigIniSettingsAutoDiscardMonths;
15843 CleanupIniSettings(&cleanup_args);
15844 }
15845 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15846 if (handler.ApplyAllFn != NULL)
15847 handler.ApplyAllFn(&g, &handler);
15848}
15849
15850void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
15851{
15852 ImGuiContext& g = *GImGui;
15853 g.SettingsDirtyTimer = 0.0f;
15854 if (!ini_filename)
15855 return;
15856
15857 size_t ini_data_size = 0;
15858 const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
15859 ImFileHandle f = ImFileOpen(ini_filename, "wt");
15860 if (!f)
15861 return;
15862 ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
15863 ImFileClose(f);
15864}
15865
15866// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
15867const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
15868{
15869 ImGuiContext& g = *GImGui;
15870 g.SettingsDirtyTimer = 0.0f;
15871 g.SettingsIniData.Buf.resize(0);
15872 g.SettingsIniData.Buf.push_back(0);
15873 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15874 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
15875 if (out_size)
15876 *out_size = (size_t)g.SettingsIniData.size();
15877 return g.SettingsIniData.c_str();
15878}
15879
15880ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
15881{
15882 ImGuiContext& g = *GImGui;
15883
15884 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
15885 if (g.IO.ConfigDebugIniSettings == false)
15886 name = ImHashSkipUncontributingPrefix(name);
15887 const size_t name_len = ImStrlen(name);
15888
15889 // Allocate chunk
15890 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
15891 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
15892 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
15893 settings->ID = ImHashStr(name, name_len);
15894 memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
15895
15896 return settings;
15897}
15898
15899// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
15900// This is called once per window .ini entry + once per newly instantiated window.
15901ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
15902{
15903 ImGuiContext& g = *GImGui;
15904 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15905 if (settings->ID == id && !settings->WantDelete)
15906 return settings;
15907 return NULL;
15908}
15909
15910// This is faster if you are holding on a Window already as we don't need to perform a search.
15911ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
15912{
15913 ImGuiContext& g = *GImGui;
15914 if (window->SettingsOffset != -1)
15915 return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
15916 return FindWindowSettingsByID(window->ID);
15917}
15918
15919// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
15920void ImGui::ClearWindowSettings(const char* name)
15921{
15922 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
15923 ImGuiWindow* window = FindWindowByName(name);
15924 if (window != NULL)
15925 {
15926 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
15927 InitOrLoadWindowSettings(window, NULL);
15928 }
15929 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
15930 settings->WantDelete = true;
15931}
15932
15933static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
15934{
15935 ImGuiContext& g = *ctx;
15936 for (ImGuiWindow* window : g.Windows)
15937 window->SettingsOffset = -1;
15938 g.SettingsWindows.clear();
15939}
15940
15941static void WindowSettingsHandler_Cleanup(ImGuiContext* ctx, ImGuiSettingsHandler*, ImGuiSettingsCleanupArgs* args)
15942{
15943 ImGuiContext& g = *ctx;
15944 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15945 {
15946 const bool is_valid = settings->LastUsedDate.IsValid();
15947 if ((args->_DiscardOlderThanDate != 0 && settings->LastUsedDate.Unpack() < args->_DiscardOlderThanDate) || (args->DiscardWhenMissingDate && !is_valid))
15948 settings->WantDelete = true;
15949 if (args->SetCurrentSessionDateToAll || (args->SetCurrentSessionDateWhenMissingDate && !is_valid))
15950 settings->LastUsedDate = g.SessionDate;
15951 }
15952}
15953
15954static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
15955{
15956 ImGuiID id = ImHashStr(name);
15957 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
15958 if (settings)
15959 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
15960 else
15961 settings = ImGui::CreateNewWindowSettings(name);
15962 settings->ID = id;
15963 settings->WantApply = true;
15964 return (void*)settings;
15965}
15966
15967static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
15968{
15969 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
15970 int x, y;
15971 int i;
15972 if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
15973 else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
15974 else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
15975 else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
15976 else if (sscanf(line, "LastUsed=%d", &i) == 1) { settings->LastUsedDate = i; return; }
15977}
15978
15979// Apply to existing windows (if any)
15980static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
15981{
15982 ImGuiContext& g = *ctx;
15983 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15984 if (settings->WantApply)
15985 {
15986 if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
15987 ApplyWindowSettings(window, settings);
15988 settings->WantApply = false;
15989 }
15990}
15991
15992static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
15993{
15994 // Gather data from windows that were active during this session
15995 // (if a window wasn't opened in this session we preserve its settings)
15996 ImGuiContext& g = *ctx;
15997 for (ImGuiWindow* window : g.Windows)
15998 {
15999 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
16000 continue;
16001
16002 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
16003 if (!settings)
16004 {
16005 settings = ImGui::CreateNewWindowSettings(window->Name);
16006 settings->LastUsedDate = g.SessionDate;
16007 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
16008 }
16009 IM_ASSERT(settings->ID == window->ID);
16010 settings->Pos = ImVec2ih(window->Pos);
16011 settings->Size = ImVec2ih(window->SizeFull);
16012 settings->IsChild = (window->Flags & ImGuiWindowFlags_ChildWindow) != 0;
16013 settings->Collapsed = window->Collapsed;
16014 settings->WantDelete = false;
16015 settings->LastUsedDate = g.SessionDate;
16016 }
16017
16018 // Write to text buffer
16019 buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
16020 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16021 {
16022 if (settings->WantDelete)
16023 continue;
16024 const char* settings_name = settings->GetName();
16025 buf->appendf("[%s][%s]\n", handler->TypeName, settings_name); // [Window][name]
16026 if (settings->IsChild)
16027 {
16028 buf->appendf("IsChild=1\n");
16029 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
16030 }
16031 else
16032 {
16033 buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
16034 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
16035 if (settings->Collapsed)
16036 buf->appendf("Collapsed=1\n");
16037 }
16038 if (g.IO.ConfigIniSettingsSaveLastUsedDate)
16039 if (int last_used_date = settings->LastUsedDate.Unpack())
16040 buf->appendf("LastUsed=%08d\n", last_used_date);
16041 buf->append("\n");
16042 }
16043}
16044
16045//-----------------------------------------------------------------------------
16046// [SECTION] LOCALIZATION
16047//-----------------------------------------------------------------------------
16048
16049void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
16050{
16051 ImGuiContext& g = *GImGui;
16052 for (int n = 0; n < count; n++)
16053 g.LocalizationTable[entries[n].Key] = entries[n].Text;
16054}
16055
16056//-----------------------------------------------------------------------------
16057// [SECTION] VIEWPORTS, PLATFORM WINDOWS
16058//-----------------------------------------------------------------------------
16059// - GetMainViewport()
16060// - SetWindowViewport() [Internal]
16061// - ScaleWindowsInViewport() [Internal]
16062// - UpdateViewportsNewFrame() [Internal]
16063// (this section is more complete in the 'docking' branch)
16064//-----------------------------------------------------------------------------
16065
16066void ImGuiPlatformIO::ClearPlatformHandlers()
16067{
16068 Platform_GetClipboardTextFn = NULL;
16069 Platform_SetClipboardTextFn = NULL;
16070 Platform_ClipboardUserData = NULL;
16071 Platform_OpenInShellFn = NULL;
16072 Platform_OpenInShellUserData = NULL;
16073 Platform_SetImeDataFn = NULL;
16074 Platform_ImeUserData = NULL;
16075}
16076
16077void ImGuiPlatformIO::ClearRendererHandlers()
16078{
16079 Renderer_TextureMaxWidth = Renderer_TextureMaxHeight = 0;
16080 Renderer_RenderState = NULL;
16081 DrawCallback_ResetRenderState = DrawCallback_SetSamplerLinear = DrawCallback_SetSamplerNearest = NULL;
16082}
16083
16084ImGuiViewport* ImGui::GetMainViewport()
16085{
16086 ImGuiContext& g = *GImGui;
16087 return g.Viewports[0];
16088}
16089
16090void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16091{
16092 window->Viewport = viewport;
16093}
16094
16095static void ScaleWindow(ImGuiWindow* window, float scale)
16096{
16097 ImVec2 origin = window->Viewport->Pos;
16098 window->Pos = ImFloor((window->Pos - origin) * scale + origin);
16099 window->Size = ImTrunc(window->Size * scale);
16100 window->SizeFull = ImTrunc(window->SizeFull * scale);
16101 window->ContentSize = ImTrunc(window->ContentSize * scale);
16102}
16103
16104// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
16105void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
16106{
16107 ImGuiContext& g = *GImGui;
16108 for (ImGuiWindow* window : g.Windows)
16109 if (window->Viewport == viewport)
16110 ScaleWindow(window, scale);
16111}
16112
16113// Update viewports and monitor infos
16114static void ImGui::UpdateViewportsNewFrame()
16115{
16116 ImGuiContext& g = *GImGui;
16117 IM_ASSERT(g.Viewports.Size == 1);
16118
16119 // Update main viewport with current platform position.
16120 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
16121 ImGuiViewportP* main_viewport = g.Viewports[0];
16122 main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
16123 main_viewport->Pos = ImVec2(0.0f, 0.0f);
16124 main_viewport->Size = g.IO.DisplaySize;
16125 main_viewport->FramebufferScale = g.IO.DisplayFramebufferScale;
16126 IM_ASSERT(main_viewport->FramebufferScale.x > 0.0f && main_viewport->FramebufferScale.y > 0.0f);
16127
16128 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
16129 for (ImGuiViewportP* viewport : g.Viewports)
16130 {
16131 // Lock down space taken by menu bars and status bars
16132 // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
16133 viewport->WorkInsetMin = viewport->BuildWorkInsetMin;
16134 viewport->WorkInsetMax = viewport->BuildWorkInsetMax;
16135 viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f);
16136 viewport->UpdateWorkRect();
16137
16138 // Garbage collect transient buffers of recently BG/FG drawlists
16139 for (int n = 0; n < IM_COUNTOF(viewport->BgFgDrawLists); n++)
16140 if (viewport->BgFgDrawListsLastTimeActive[n] < memory_compact_start_time && viewport->BgFgDrawLists[n] != NULL)
16141 {
16142 IM_DELETE(viewport->BgFgDrawLists[n]);
16143 viewport->BgFgDrawLists[n] = NULL;
16144 }
16145 }
16146}
16147
16148//-----------------------------------------------------------------------------
16149// [SECTION] DOCKING
16150//-----------------------------------------------------------------------------
16151
16152// (this section is filled in the 'docking' branch)
16153
16154
16155//-----------------------------------------------------------------------------
16156// [SECTION] PLATFORM DEPENDENT HELPERS
16157//-----------------------------------------------------------------------------
16158// - Default clipboard handlers
16159// - Default shell function handlers
16160// - Default IME handlers
16161//-----------------------------------------------------------------------------
16162
16163#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
16164
16165#ifdef _MSC_VER
16166#pragma comment(lib, "user32")
16167#pragma comment(lib, "kernel32")
16168#endif
16169
16170// Win32 clipboard implementation
16171// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
16172static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
16173{
16174 ImGuiContext& g = *ctx;
16175 g.ClipboardHandlerData.clear();
16176 if (!::OpenClipboard(NULL))
16177 return NULL;
16178 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
16179 if (wbuf_handle == NULL)
16180 {
16181 ::CloseClipboard();
16182 return NULL;
16183 }
16184 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
16185 {
16186 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
16187 g.ClipboardHandlerData.resize(buf_len);
16188 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
16189 }
16190 ::GlobalUnlock(wbuf_handle);
16191 ::CloseClipboard();
16192 return g.ClipboardHandlerData.Data;
16193}
16194
16195static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
16196{
16197 if (!::OpenClipboard(NULL))
16198 return;
16199 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
16200 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
16201 if (wbuf_handle == NULL)
16202 {
16203 ::CloseClipboard();
16204 return;
16205 }
16206 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
16207 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
16208 ::GlobalUnlock(wbuf_handle);
16209 ::EmptyClipboard();
16210 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
16211 ::GlobalFree(wbuf_handle);
16212 ::CloseClipboard();
16213}
16214
16215#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
16216
16217#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
16218static PasteboardRef main_clipboard = 0;
16219
16220// OSX clipboard implementation
16221// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
16222static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
16223{
16224 if (!main_clipboard)
16225 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
16226 PasteboardClear(main_clipboard);
16227 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text));
16228 if (cf_data)
16229 {
16230 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
16231 CFRelease(cf_data);
16232 }
16233}
16234
16235static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
16236{
16237 ImGuiContext& g = *ctx;
16238 if (!main_clipboard)
16239 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
16240 PasteboardSynchronize(main_clipboard);
16241
16242 ItemCount item_count = 0;
16243 PasteboardGetItemCount(main_clipboard, &item_count);
16244 for (ItemCount i = 0; i < item_count; i++)
16245 {
16246 PasteboardItemID item_id = 0;
16247 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
16248 CFArrayRef flavor_type_array = 0;
16249 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
16250 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
16251 {
16252 CFDataRef cf_data;
16253 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
16254 {
16255 g.ClipboardHandlerData.clear();
16256 int length = (int)CFDataGetLength(cf_data);
16257 g.ClipboardHandlerData.resize(length + 1);
16258 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
16259 g.ClipboardHandlerData[length] = 0;
16260 CFRelease(cf_data);
16261 return g.ClipboardHandlerData.Data;
16262 }
16263 }
16264 }
16265 return NULL;
16266}
16267
16268#else
16269
16270// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
16271static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
16272{
16273 ImGuiContext& g = *ctx;
16274 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
16275}
16276
16277static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text)
16278{
16279 ImGuiContext& g = *ctx;
16280 g.ClipboardHandlerData.clear();
16281 const char* text_end = text + ImStrlen(text);
16282 g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
16283 memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
16284 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
16285}
16286
16287#endif // Default clipboard handlers
16288
16289//-----------------------------------------------------------------------------
16290
16291#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
16292#if defined(__APPLE__) && TARGET_OS_IPHONE
16293#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
16294#endif
16295#if defined(__3DS__)
16296#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
16297#endif
16298#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
16299#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
16300#endif
16301#endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
16302
16303#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
16304#ifdef _WIN32
16305#include <shellapi.h> // ShellExecuteA()
16306#ifdef _MSC_VER
16307#pragma comment(lib, "shell32")
16308#endif
16309static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
16310{
16311 const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
16312 ImVector<wchar_t> path_wbuf;
16313 path_wbuf.resize(path_wsize);
16314 ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize);
16315 return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32;
16316}
16317#else
16318#include <sys/wait.h>
16319#include <unistd.h>
16320static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
16321{
16322#if defined(__APPLE__)
16323 const char* args[] { "open", "--", path, NULL };
16324#else
16325 const char* args[] { "xdg-open", path, NULL };
16326#endif
16327 pid_t pid = fork();
16328 if (pid < 0)
16329 return false;
16330 if (!pid)
16331 {
16332 execvp(args[0], const_cast<char **>(args));
16333 exit(-1);
16334 }
16335 else
16336 {
16337 int status;
16338 waitpid(pid, &status, 0);
16339 return WEXITSTATUS(status) == 0;
16340 }
16341}
16342#endif
16343#else
16344static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
16345#endif // Default shell handlers
16346
16347//-----------------------------------------------------------------------------
16348
16349// Win32 API IME support (for Asian languages, etc.)
16350#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
16351
16352#include <imm.h>
16353#ifdef _MSC_VER
16354#pragma comment(lib, "imm32")
16355#endif
16356
16357static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
16358{
16359 // Notify OS Input Method Editor of text input position
16360 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
16361 if (hwnd == 0)
16362 return;
16363
16364 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
16365 if (HIMC himc = ::ImmGetContext(hwnd))
16366 {
16367 COMPOSITIONFORM composition_form = {};
16368 composition_form.ptCurrentPos.x = (LONG)data->InputPos.x;
16369 composition_form.ptCurrentPos.y = (LONG)data->InputPos.y;
16370 composition_form.dwStyle = CFS_FORCE_POSITION;
16371 ::ImmSetCompositionWindow(himc, &composition_form);
16372 CANDIDATEFORM candidate_form = {};
16373 candidate_form.dwStyle = CFS_CANDIDATEPOS;
16374 candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x;
16375 candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y;
16376 ::ImmSetCandidateWindow(himc, &candidate_form);
16377 ::ImmReleaseContext(hwnd, himc);
16378 }
16379}
16380
16381#else
16382
16383static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
16384
16385#endif // Default IME handlers
16386
16387//-----------------------------------------------------------------------------
16388// [SECTION] METRICS/DEBUGGER WINDOW
16389//-----------------------------------------------------------------------------
16390// - MetricsHelpMarker() [Internal]
16391// - DebugRenderViewportThumbnail() [Internal]
16392// - RenderViewportsThumbnails() [Internal]
16393// - DebugRenderKeyboardPreview() [Internal]
16394// - DebugTextEncoding()
16395// - DebugFlashStyleColorStop() [Internal]
16396// - DebugFlashStyleColor()
16397// - UpdateDebugToolFlashStyleColor() [Internal]
16398// - ShowFontAtlas() [Internal but called by Demo!]
16399// - DebugNodeTexture() [Internal]
16400// - ShowMetricsWindow()
16401// - DebugNodeColumns() [Internal]
16402// - DebugNodeDrawList() [Internal]
16403// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
16404// - DebugNodeFont() [Internal]
16405// - DebugNodeFontGlyph() [Internal]
16406// - DebugNodeStorage() [Internal]
16407// - DebugNodeTabBar() [Internal]
16408// - DebugNodeViewport() [Internal]
16409// - DebugNodeWindow() [Internal]
16410// - DebugNodeWindowSettings() [Internal]
16411// - DebugNodeWindowsList() [Internal]
16412// - DebugNodeWindowsListByBeginStackParent() [Internal]
16413// - ShowFontSelector()
16414//-----------------------------------------------------------------------------
16415
16416#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
16417// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
16418static void MetricsHelpMarker(const char* desc)
16419{
16420 ImGui::TextDisabled("(?)");
16421 if (ImGui::BeginItemTooltip())
16422 {
16423 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
16424 ImGui::TextUnformatted(desc);
16425 ImGui::PopTextWrapPos();
16426 ImGui::EndTooltip();
16427 }
16428}
16429#endif
16430
16431#ifndef IMGUI_DISABLE_DEBUG_TOOLS
16432
16433void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
16434{
16435 ImGuiContext& g = *GImGui;
16436 ImGuiWindow* window = g.CurrentWindow;
16437
16438 ImVec2 scale = bb.GetSize() / viewport->Size;
16439 ImVec2 off = bb.Min - viewport->Pos * scale;
16440 float alpha_mul = 1.0f;
16441 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
16442 for (ImGuiWindow* thumb_window : g.Windows)
16443 {
16444 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
16445 continue;
16446
16447 ImRect thumb_r = thumb_window->Rect();
16448 ImRect title_r = thumb_window->TitleBarRect();
16449 thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale));
16450 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
16451 thumb_r.ClipWithFull(bb);
16452 title_r.ClipWithFull(bb);
16453 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
16454 window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
16455 window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
16456 window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
16457 window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
16458 }
16459 draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
16460 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
16461 window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
16462}
16463
16464static void RenderViewportsThumbnails()
16465{
16466 ImGuiContext& g = *GImGui;
16467 ImGuiWindow* window = g.CurrentWindow;
16468
16469 float SCALE = 1.0f / 8.0f;
16470 ImRect bb_full(g.Viewports[0]->Pos, g.Viewports[0]->Pos + g.Viewports[0]->Size);
16471 ImVec2 p = window->DC.CursorPos;
16472 ImVec2 off = p - bb_full.Min * SCALE;
16473
16474 // Draw viewports
16475 for (ImGuiViewportP* viewport : g.Viewports)
16476 {
16477 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
16478 ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
16479 }
16480 ImGui::Dummy(bb_full.GetSize() * SCALE);
16481}
16482
16483// Draw an arbitrary US keyboard layout to visualize translated keys
16484void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
16485{
16486 const float scale = ImGui::GetFontSize() / 13.0f;
16487 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
16488 const float key_rounding = 3.0f * scale;
16489 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
16490 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
16491 const float key_face_rounding = 2.0f * scale;
16492 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
16493 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
16494 const float key_row_offset = 9.0f * scale;
16495
16496 ImVec2 board_min = GetCursorScreenPos();
16497 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);
16498 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
16499
16500 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
16501 const KeyLayoutData keys_to_display[] =
16502 {
16503 { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
16504 { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
16505 { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
16506 };
16507
16508 // Elements rendered manually via ImDrawList API are not clipped automatically.
16509 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
16510 Dummy(board_max - board_min);
16511 if (!IsItemVisible())
16512 return;
16513 draw_list->PushClipRect(board_min, board_max, true);
16514 for (int n = 0; n < IM_COUNTOF(keys_to_display); n++)
16515 {
16516 const KeyLayoutData* key_data = &keys_to_display[n];
16517 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);
16518 ImVec2 key_max = key_min + key_size;
16519 draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
16520 draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
16521 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
16522 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
16523 draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, 2.0f);
16524 draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
16525 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
16526 draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
16527 if (IsKeyDown(key_data->Key))
16528 draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
16529 }
16530 draw_list->PopClipRect();
16531}
16532
16533// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
16534void ImGui::DebugTextEncoding(const char* str)
16535{
16536 Text("Text: \"%s\"", str);
16537 if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
16538 return;
16539 TableSetupColumn("Offset");
16540 TableSetupColumn("UTF-8");
16541 TableSetupColumn("Glyph");
16542 TableSetupColumn("Codepoint");
16543 TableHeadersRow();
16544 const char* str_end = str + strlen(str); // As we may receive malformed UTF-8, pass an explicit end instead of relying on ImTextCharFromUtf8() assuming enough space.
16545 for (const char* p = str; *p != 0; )
16546 {
16547 unsigned int c;
16548 const int c_utf8_len = ImTextCharFromUtf8(&c, p, str_end);
16549 TableNextColumn();
16550 Text("%d", (int)(p - str));
16551 TableNextColumn();
16552 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
16553 {
16554 if (byte_index > 0)
16555 SameLine();
16556 Text("0x%02X", (int)(unsigned char)p[byte_index]);
16557 }
16558 TableNextColumn();
16559 TextUnformatted(p, p + c_utf8_len);
16560 if (!GetFont()->IsGlyphInFont((ImWchar)c))
16561 {
16562 SameLine();
16563 TextUnformatted("[missing]");
16564 }
16565 TableNextColumn();
16566 Text("U+%04X", (int)c);
16567 p += c_utf8_len;
16568 }
16569 EndTable();
16570}
16571
16572static void DebugFlashStyleColorStop()
16573{
16574 ImGuiContext& g = *GImGui;
16575 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
16576 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
16577 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
16578}
16579
16580// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
16581void ImGui::DebugFlashStyleColor(ImGuiCol idx)
16582{
16583 ImGuiContext& g = *GImGui;
16584 DebugFlashStyleColorStop();
16585 g.DebugFlashStyleColorTime = 0.5f;
16586 g.DebugFlashStyleColorIdx = idx;
16587 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
16588}
16589
16590void ImGui::UpdateDebugToolFlashStyleColor()
16591{
16592 ImGuiContext& g = *GImGui;
16593 if (g.DebugFlashStyleColorTime <= 0.0f)
16594 return;
16595 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);
16596 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
16597 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
16598 DebugFlashStyleColorStop();
16599}
16600
16601ImU64 ImGui::DebugTextureIDToU64(ImTextureID tex_id)
16602{
16603 ImU64 v = 0;
16604 memcpy(&v, &tex_id, ImMin(sizeof(ImU64), sizeof(ImTextureID)));
16605 return v;
16606}
16607
16608static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref)
16609{
16610 char* buf_p = buf;
16611 char* buf_end = buf + buf_size;
16612 if (tex_ref._TexData != NULL)
16613 buf_p += ImFormatString(buf_p, buf_end - buf_p, "#%03d: ", tex_ref._TexData->UniqueID);
16614 ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID()));
16615 return buf;
16616}
16617
16618#ifdef IMGUI_ENABLE_FREETYPE
16619namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); }
16620#endif
16621
16622// [DEBUG] List fonts in a font atlas and display its texture
16623void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
16624{
16625 ImGuiContext& g = *GImGui;
16626 ImGuiIO& io = g.IO;
16627 ImGuiStyle& style = g.Style;
16628
16629 BeginDisabled();
16630 CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures);
16631 EndDisabled();
16632 ShowFontSelector("Font");
16633 //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0);
16634 if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f"))
16635 style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work.
16636 SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize());
16637 SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.");
16638 DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f);
16639 //BeginDisabled(io.ConfigDpiScaleFonts);
16640 DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f);
16641 //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.");
16642 //EndDisabled();
16643 if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
16644 {
16645 BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!");
16646 BulletText("For instructions, see:");
16647 SameLine();
16648 TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md");
16649 }
16650 BulletText("Load a nice font for better results!");
16651 BulletText("Please submit feedback:");
16652 SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465");
16653 BulletText("Read FAQ for more details:");
16654 SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/");
16655 //EndDisabled();
16656
16657 SeparatorText("Font List");
16658
16659 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
16660 Checkbox("Show font preview", &cfg->ShowFontPreview);
16661
16662 // Font loaders
16663 if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL"))
16664 {
16665 const ImFontLoader* loader_current = atlas->FontLoader;
16666 BeginDisabled(!atlas->RendererHasTextures);
16667#ifdef IMGUI_ENABLE_STB_TRUETYPE
16668 const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype();
16669 if (RadioButton("stb_truetype", loader_current == loader_stbtruetype))
16670 atlas->SetFontLoader(loader_stbtruetype);
16671#else
16672 BeginDisabled();
16673 RadioButton("stb_truetype", false);
16674 SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE");
16675 EndDisabled();
16676#endif
16677 SameLine();
16678#ifdef IMGUI_ENABLE_FREETYPE
16679 const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader();
16680 if (RadioButton("FreeType", loader_current == loader_freetype))
16681 atlas->SetFontLoader(loader_freetype);
16682 if (loader_current == loader_freetype)
16683 {
16684 unsigned int loader_flags = atlas->FontLoaderFlags;
16685 Text("Shared FreeType Loader Flags: 0x%08X", loader_flags);
16686 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
16687 {
16688 for (ImFont* font : atlas->Fonts)
16689 ImFontAtlasFontDestroyOutput(atlas, font);
16690 atlas->FontLoaderFlags = loader_flags;
16691 for (ImFont* font : atlas->Fonts)
16692 ImFontAtlasFontInitOutput(atlas, font);
16693 }
16694 }
16695#else
16696 BeginDisabled();
16697 RadioButton("FreeType", false);
16698 SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp.");
16699 EndDisabled();
16700#endif
16701 EndDisabled();
16702 TreePop();
16703 }
16704
16705 // Font list
16706 for (ImFont* font : atlas->Fonts)
16707 {
16708 PushID(font);
16709 DebugNodeFont(font);
16710 PopID();
16711 }
16712
16713 SeparatorText("Font Atlas");
16714 if (Button("Compact"))
16715 atlas->CompactCache();
16716 SameLine();
16717 if (Button("Grow"))
16718 ImFontAtlasTextureGrow(atlas);
16719 SameLine();
16720 if (Button("Clear All"))
16721 ImFontAtlasBuildClear(atlas);
16722 SetItemTooltip("Destroy cache and custom rectangles.");
16723
16724 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
16725 {
16726 ImTextureData* tex = atlas->TexList[tex_n];
16727 if (tex_n > 0)
16728 SameLine();
16729 Text("Tex: %dx%d", tex->Width, tex->Height);
16730 }
16731 const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface);
16732 const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface);
16733 Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt);
16734 Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt);
16735
16736 ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid;
16737 if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles
16738 {
16739 PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f);
16740 if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12)))
16741 {
16742 for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex)
16743 if (entry.IsUsed)
16744 {
16745 ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation);
16746 ImFontAtlasRect r = {};
16747 atlas->GetCustomRect(id, &r);
16748 const char* buf;
16749 ImFormatStringToTempBuffer(&buf, NULL, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y);
16750 TableNextColumn();
16751 Selectable(buf);
16752 if (IsItemHovered())
16753 highlight_r_id = id;
16754 TableNextColumn();
16755 Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
16756 }
16757 EndTable();
16758 }
16759 PopStyleVar();
16760 TreePop();
16761 }
16762
16763 // Texture list
16764 // (ensure the last texture always use the same ID, so we can keep it open neatly)
16765 ImFontAtlasRect highlight_r;
16766 if (highlight_r_id != ImFontAtlasRectId_Invalid)
16767 atlas->GetCustomRect(highlight_r_id, &highlight_r);
16768 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
16769 {
16770 if (tex_n == atlas->TexList.Size - 1)
16771 SetNextItemOpen(true, ImGuiCond_Once);
16772 DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL);
16773 }
16774}
16775
16776void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect)
16777{
16778 ImGuiContext& g = *GImGui;
16779 PushID(int_id);
16780 if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height))
16781 {
16782 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
16783 Checkbox("Show used rect", &cfg->ShowTextureUsedRect);
16784 PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize));
16785 ImVec2 p = GetCursorScreenPos();
16786 if (tex->WantDestroyNextFrame)
16787 Dummy(ImVec2((float)tex->Width, (float)tex->Height));
16788 else
16789 ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f));
16790 if (cfg->ShowTextureUsedRect)
16791 GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255));
16792 if (highlight_rect != NULL)
16793 {
16794 ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height);
16795 ImRect r_inner(p.x + highlight_rect->x, p.y + highlight_rect->y, p.x + highlight_rect->x + highlight_rect->w, p.y + highlight_rect->y + highlight_rect->h);
16796 RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f);
16797 GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255));
16798 }
16799 PopStyleVar();
16800
16801 char texref_desc[30];
16802 Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors);
16803 Text("TexRef = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texref_desc, IM_COUNTOF(texref_desc), tex->GetTexRef()), tex->BackendUserData);
16804 TreePop();
16805 }
16806 PopID();
16807}
16808
16809void ImGui::ShowMetricsWindow(bool* p_open)
16810{
16811 ImGuiContext& g = *GImGui;
16812 ImGuiIO& io = g.IO;
16813 ImGuiPlatformIO& platform_io = g.PlatformIO;
16814 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
16815 if (cfg->ShowDebugLog)
16816 ShowDebugLogWindow(&cfg->ShowDebugLog);
16817 if (cfg->ShowIDStackTool)
16818 ShowIDStackToolWindow(&cfg->ShowIDStackTool);
16819
16820 if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
16821 {
16822 End();
16823 return;
16824 }
16825
16826 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
16827 DebugBreakClearData();
16828
16829 // Basic info
16830 Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
16831 if (g.ContextName[0] != 0)
16832 {
16833 SameLine();
16834 Text("(Context Name: \"%s\")", g.ContextName);
16835 }
16836 Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
16837 Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
16838 Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
16839 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
16840
16841 Separator();
16842
16843 // Debugging enums
16844 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
16845 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
16846 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
16847 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
16848 if (cfg->ShowWindowsRectsType < 0)
16849 cfg->ShowWindowsRectsType = WRT_WorkRect;
16850 if (cfg->ShowTablesRectsType < 0)
16851 cfg->ShowTablesRectsType = TRT_WorkRect;
16852
16853 struct Funcs
16854 {
16855 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
16856 {
16857 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
16858 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
16859 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
16860 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
16861 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
16862 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
16863 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
16864 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); }
16865 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); }
16866 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
16867 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
16868 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); }
16869 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); }
16870 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); }
16871 IM_ASSERT(0);
16872 return ImRect();
16873 }
16874
16875 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
16876 {
16877 if (rect_type == WRT_OuterRect) { return window->Rect(); }
16878 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
16879 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
16880 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
16881 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
16882 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
16883 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
16884 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
16885 IM_ASSERT(0);
16886 return ImRect();
16887 }
16888 };
16889
16890#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
16891 TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
16892#endif
16893
16894 // Tools
16895 if (TreeNode("Tools"))
16896 {
16897 // Debug Break features
16898 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
16899 SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
16900 SameLine();
16901 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.");
16902 if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
16903 DebugStartItemPicker();
16904 Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
16905
16906 SeparatorText("Visualize");
16907
16908 Checkbox("Show Debug Log", &cfg->ShowDebugLog);
16909 SameLine();
16910 MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
16911
16912 Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
16913 SameLine();
16914 MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
16915
16916 Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
16917 Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
16918 SameLine();
16919 SetNextItemWidth(GetFontSize() * 12);
16920 cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
16921 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
16922 {
16923 BulletText("'%s':", g.NavWindow->Name);
16924 Indent();
16925 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
16926 {
16927 ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
16928 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]);
16929 }
16930 Unindent();
16931 }
16932
16933 Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
16934 SameLine();
16935 SetNextItemWidth(GetFontSize() * 12);
16936 cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
16937 if (cfg->ShowTablesRects && g.NavWindow != NULL)
16938 {
16939 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
16940 {
16941 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
16942 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
16943 continue;
16944
16945 BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
16946 if (IsItemHovered())
16947 GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 2.0f);
16948 Indent();
16949 char buf[128];
16950 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
16951 {
16952 if (rect_n >= TRT_ColumnsRect)
16953 {
16954 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
16955 continue;
16956 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
16957 {
16958 ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
16959 ImFormatString(buf, IM_COUNTOF(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]);
16960 Selectable(buf);
16961 if (IsItemHovered())
16962 GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 2.0f);
16963 }
16964 }
16965 else
16966 {
16967 ImRect r = Funcs::GetTableRect(table, rect_n, -1);
16968 ImFormatString(buf, IM_COUNTOF(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]);
16969 Selectable(buf);
16970 if (IsItemHovered())
16971 GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 2.0f);
16972 }
16973 }
16974 Unindent();
16975 }
16976 }
16977 Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
16978
16979 SeparatorText("Validate");
16980
16981 Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
16982 SameLine();
16983 MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
16984
16985 Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
16986 SameLine();
16987 MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
16988 if (cfg->ShowTextEncodingViewer)
16989 {
16990 static char buf[64] = "";
16991 SetNextItemWidth(-FLT_MIN);
16992 InputText("##DebugTextEncodingBuf", buf, IM_COUNTOF(buf));
16993 if (buf[0] != 0)
16994 DebugTextEncoding(buf);
16995 }
16996
16997 TreePop();
16998 }
16999
17000 // Windows
17001 if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
17002 {
17003 //SetNextItemOpen(true, ImGuiCond_Once);
17004 DebugNodeWindowsList(&g.Windows, "By display order");
17005 DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
17006 if (TreeNode("By submission order (begin stack)"))
17007 {
17008 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
17009 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
17010 temp_buffer.resize(0);
17011 for (ImGuiWindow* window : g.Windows)
17012 if (window->LastFrameActive + 1 >= g.FrameCount)
17013 temp_buffer.push_back(window);
17014 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); } };
17015 ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
17016 DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
17017 TreePop();
17018 }
17019
17020 TreePop();
17021 }
17022
17023 // DrawLists
17024 int drawlist_count = 0;
17025 for (ImGuiViewportP* viewport : g.Viewports)
17026 drawlist_count += viewport->DrawDataP.CmdLists.Size;
17027 if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
17028 {
17029 Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
17030 Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
17031 for (ImGuiViewportP* viewport : g.Viewports)
17032 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
17033 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
17034 TreePop();
17035 }
17036
17037 // Viewports
17038 if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
17039 {
17040 SetNextItemOpen(true, ImGuiCond_Once);
17041 if (TreeNode("Windows Minimap"))
17042 {
17043 RenderViewportsThumbnails();
17044 TreePop();
17045 }
17046 cfg->HighlightViewportID = 0;
17047
17048 for (ImGuiViewportP* viewport : g.Viewports)
17049 DebugNodeViewport(viewport);
17050 TreePop();
17051 }
17052
17053 // Details for Fonts
17054 for (ImFontAtlas* atlas : g.FontAtlases)
17055 if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size))
17056 {
17057 ShowFontAtlas(atlas);
17058 TreePop();
17059 }
17060
17061 // Details for Popups
17062 if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
17063 {
17064 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
17065 {
17066 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
17067 ImGuiWindow* window = popup_data.Window;
17068 BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
17069 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
17070 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
17071 }
17072 TreePop();
17073 }
17074
17075 // Details for TabBars
17076 if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
17077 {
17078 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
17079 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
17080 {
17081 PushID(tab_bar);
17082 DebugNodeTabBar(tab_bar, "TabBar");
17083 PopID();
17084 }
17085 TreePop();
17086 }
17087
17088 // Details for Tables
17089 if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
17090 {
17091 for (int n = 0; n < g.Tables.GetMapSize(); n++)
17092 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
17093 DebugNodeTable(table);
17094 TreePop();
17095 }
17096
17097 // Details for InputText
17098 if (TreeNode("InputText"))
17099 {
17100 DebugNodeInputTextState(&g.InputTextState);
17101 TreePop();
17102 }
17103
17104 // Details for TypingSelect
17105 if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
17106 {
17107 DebugNodeTypingSelectState(&g.TypingSelectState);
17108 TreePop();
17109 }
17110
17111 // Details for MultiSelect
17112 if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
17113 {
17114 ImGuiBoxSelectState* bs = &g.BoxSelectState;
17115 BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
17116 for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
17117 if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
17118 DebugNodeMultiSelectState(state);
17119 TreePop();
17120 }
17121
17122 // Details for Docking
17123#ifdef IMGUI_HAS_DOCK
17124 if (TreeNode("Docking"))
17125 {
17126 TreePop();
17127 }
17128#endif // #ifdef IMGUI_HAS_DOCK
17129
17130 // Settings
17131 if (TreeNode("Settings"))
17132 {
17133 if (SmallButton("Clear"))
17134 ClearIniSettings();
17135 SameLine();
17136 if (SmallButton("Save to memory"))
17137 SaveIniSettingsToMemory();
17138 SameLine();
17139 if (SmallButton("Save to disk"))
17140 SaveIniSettingsToDisk(g.IO.IniFilename);
17141 SameLine();
17142 if (g.IO.IniFilename)
17143 Text("\"%s\"", g.IO.IniFilename);
17144 else
17145 TextUnformatted("<NULL>");
17146 Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
17147
17148 int highlight_older_than_date = 0;
17149 Text("SessionDate: %d", platform_io.Platform_SessionDate);
17150 BeginDisabled(platform_io.Platform_SessionDate == 0);
17151 Checkbox("Highlight Entries Older Than", &cfg->SettingsHighlightOldEntries);
17152 SetNextItemWidth(GetFontSize() * 8);
17153 SameLine();
17154 SliderInt("Months", &cfg->SettingsDiscardMonths, 1, 24);
17155 if (cfg->SettingsHighlightOldEntries && cfg->SettingsDiscardMonths > 0)
17156 {
17157 ImGuiPackedDate cutoff_date = platform_io.Platform_SessionDate;
17158 cutoff_date.SubtractMonths(cfg->SettingsDiscardMonths);
17159 highlight_older_than_date = cutoff_date.Unpack();
17160 SameLine();
17161 ImGuiSettingsCleanupArgs cleanup_args;
17162 cleanup_args.DiscardOlderThanMonths = cfg->SettingsDiscardMonths;
17163 if (Button("Discard"))
17164 CleanupIniSettings(&cleanup_args);
17165 }
17166 EndDisabled();
17167 Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
17168
17169 struct ScopedHighlightOlderThan
17170 {
17171 bool Highlight;
17172 ScopedHighlightOlderThan(int cutoff_date, ImGuiPackedDate in_date) { Highlight = cutoff_date != 0 && in_date.Unpack() < cutoff_date; if (Highlight) PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); }
17173 ~ScopedHighlightOlderThan() { if (Highlight) PopStyleColor(); }
17174 };
17175
17176 if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
17177 {
17178 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
17179 BulletText("\"%s\"", handler.TypeName);
17180 TreePop();
17181 }
17182 if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
17183 {
17184 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17185 {
17186 ScopedHighlightOlderThan scoped_highlight(highlight_older_than_date, settings->LastUsedDate);
17187 DebugNodeWindowSettings(settings);
17188 }
17189 TreePop();
17190 }
17191
17192 if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
17193 {
17194 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
17195 {
17196 ScopedHighlightOlderThan scoped_highlight(highlight_older_than_date, settings->LastUsedDate);
17197 DebugNodeTableSettings(settings, NULL);
17198 }
17199 TreePop();
17200 }
17201
17202#ifdef IMGUI_HAS_DOCK
17203#endif // #ifdef IMGUI_HAS_DOCK
17204
17205 if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
17206 {
17207 InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
17208 TreePop();
17209 }
17210 TreePop();
17211 }
17212
17213 // Settings
17214 if (TreeNode("Memory allocations"))
17215 {
17216 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
17217 Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
17218 Text("Releasing selected unused buffers after: %.2f secs", g.IO.ConfigMemoryCompactTimer);
17219 if (SmallButton("GC now")) { g.GcCompactAll = true; }
17220 Text("Recent frames with allocations:");
17221 int buf_size = IM_COUNTOF(info->LastEntriesBuf);
17222 for (int n = buf_size - 1; n >= 0; n--)
17223 {
17224 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
17225 BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
17226 if (n == 0)
17227 {
17228 SameLine();
17229 Text("<- %d frames ago", g.FrameCount - entry->FrameCount);
17230 }
17231 }
17232 TreePop();
17233 }
17234
17235 if (TreeNode("Inputs"))
17236 {
17237 Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
17238 {
17239 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
17240 Indent();
17241 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); }
17242 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); }
17243 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); }
17244 Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "Ctrl " : "", io.KeyShift ? "Shift " : "", io.KeyAlt ? "Alt " : "", io.KeySuper ? "Super " : "");
17245 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.
17246 DebugRenderKeyboardPreview(GetWindowDrawList());
17247 Unindent();
17248 }
17249
17250 Text("MOUSE STATE");
17251 {
17252 Indent();
17253 if (IsMousePosValid())
17254 Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
17255 else
17256 Text("Mouse pos: <INVALID>");
17257 Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
17258 int count = IM_COUNTOF(io.MouseDown);
17259 Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
17260 Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
17261 Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
17262 Text("Mouse wheel: %.1f", io.MouseWheel);
17263 Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
17264 Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
17265 Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
17266 Unindent();
17267 }
17268
17269 Text("MOUSE WHEELING");
17270 {
17271 Indent();
17272 Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
17273 Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
17274 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>");
17275 Unindent();
17276 }
17277
17278 Text("KEY OWNERS");
17279 {
17280 Indent();
17281 if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
17282 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
17283 {
17284 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
17285 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
17286 continue;
17287 Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
17288 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
17289 DebugLocateItemOnHover(owner_data->OwnerCurr);
17290 }
17291 EndChild();
17292 Unindent();
17293 }
17294 Text("SHORTCUT ROUTING");
17295 SameLine();
17296 MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
17297 {
17298 Indent();
17299 if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
17300 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
17301 {
17302 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
17303 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
17304 {
17305 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
17306 ImGuiKeyChord key_chord = key | routing_data->Mods;
17307 Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
17308 DebugLocateItemOnHover(routing_data->RoutingCurr);
17309 if (g.IO.ConfigDebugIsDebuggerPresent)
17310 {
17311 SameLine();
17312 if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
17313 g.DebugBreakInShortcutRouting = key_chord;
17314 }
17315 idx = routing_data->NextEntryIndex;
17316 }
17317 }
17318 EndChild();
17319 Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
17320 Unindent();
17321 }
17322 TreePop();
17323 }
17324
17325 if (TreeNode("Internal state"))
17326 {
17327 Text("WINDOWING");
17328 Indent();
17329 Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
17330 Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
17331 Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
17332 Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
17333 Unindent();
17334
17335 Text("ITEMS");
17336 Indent();
17337 Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
17338 DebugLocateItemOnHover(g.ActiveId);
17339 Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
17340 Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
17341 Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
17342 Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
17343 Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
17344 DebugLocateItemOnHover(g.DragDropPayload.SourceId);
17345 Unindent();
17346
17347 Text("NAV,FOCUS");
17348 Indent();
17349 Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
17350 Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
17351 DebugLocateItemOnHover(g.NavId);
17352 Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
17353 Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
17354 Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
17355 Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
17356 Text("NavActivateFlags: %04X", g.NavActivateFlags);
17357 Text("NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav);
17358 Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
17359 Text("NavFocusRoute[] = ");
17360 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
17361 {
17362 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
17363 SameLine(0.0f, 0.0f);
17364 Text("0x%08X/", focus_scope.ID);
17365 SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
17366 }
17367 Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
17368 Unindent();
17369
17370 TreePop();
17371 }
17372
17373 // Overlay: Display windows Rectangles and Begin Order
17374 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
17375 {
17376 for (ImGuiWindow* window : g.Windows)
17377 {
17378 if (!window->WasActive)
17379 continue;
17380 ImDrawList* draw_list = GetForegroundDrawList(window);
17381 if (cfg->ShowWindowsRects)
17382 {
17383 ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
17384 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
17385 }
17386 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
17387 {
17388 char buf[32];
17389 ImFormatString(buf, IM_COUNTOF(buf), "%d", window->BeginOrderWithinContext);
17390 float font_size = GetFontSize();
17391 draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
17392 draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
17393 }
17394 }
17395 }
17396
17397 // Overlay: Display Tables Rectangles
17398 if (cfg->ShowTablesRects)
17399 {
17400 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
17401 {
17402 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
17403 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
17404 continue;
17405 ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
17406 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
17407 {
17408 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
17409 {
17410 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
17411 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
17412 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
17413 draw_list->AddRect(r.Min, r.Max, col, 0.0f, thickness);
17414 }
17415 }
17416 else
17417 {
17418 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
17419 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
17420 }
17421 }
17422 }
17423
17424#ifdef IMGUI_HAS_DOCK
17425 // Overlay: Display Docking info
17426 if (show_docking_nodes && g.IO.KeyCtrl)
17427 {
17428 }
17429#endif // #ifdef IMGUI_HAS_DOCK
17430
17431 End();
17432}
17433
17434void ImGui::DebugBreakClearData()
17435{
17436 // Those fields are scattered in their respective subsystem to stay in hot-data locations
17437 ImGuiContext& g = *GImGui;
17438 g.DebugBreakInWindow = 0;
17439 g.DebugBreakInTable = 0;
17440 g.DebugBreakInShortcutRouting = ImGuiKey_None;
17441}
17442
17443void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
17444{
17445 if (!BeginItemTooltip())
17446 return;
17447 Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
17448 Separator();
17449 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.");
17450 Separator();
17451 TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
17452 EndTooltip();
17453}
17454
17455// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
17456// In order to reduce interferences with the contents we are trying to debug into.
17457bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
17458{
17459 ImGuiWindow* window = GetCurrentWindow();
17460 if (window->SkipItems)
17461 return false;
17462
17463 ImGuiContext& g = *GImGui;
17464 const ImGuiID id = window->GetID(label);
17465 const ImVec2 label_size = CalcTextSize(label, NULL, true);
17466 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
17467 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
17468
17469 const ImRect bb(pos, pos + size);
17470 ItemSize(size, 0.0f);
17471 if (!ItemAdd(bb, id))
17472 return false;
17473
17474 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
17475 bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
17476 bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
17477 DebugBreakButtonTooltip(false, description_of_location);
17478
17479 ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
17480 ImVec4 hsv;
17481 ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
17482 ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
17483
17484 RenderNavCursor(bb, id);
17485 RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
17486 RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
17487
17488 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
17489 return pressed;
17490}
17491
17492// [DEBUG] Display contents of Columns
17493void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
17494{
17495 if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
17496 return;
17497 BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
17498 for (ImGuiOldColumnData& column : columns->Columns)
17499 BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
17500 TreePop();
17501}
17502
17503// [DEBUG] Display contents of ImDrawList
17504void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
17505{
17506 ImGuiContext& g = *GImGui;
17507 IM_UNUSED(viewport); // Used in docking branch
17508 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
17509 int cmd_count = draw_list->CmdBuffer.Size;
17510 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
17511 cmd_count--;
17512 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);
17513 if (draw_list == GetWindowDrawList())
17514 {
17515 SameLine();
17516 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)
17517 if (node_open)
17518 TreePop();
17519 return;
17520 }
17521
17522 ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
17523 if (window && IsItemHovered() && fg_draw_list)
17524 fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
17525 if (!node_open)
17526 return;
17527
17528 if (window && !window->WasActive)
17529 TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
17530
17531 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
17532 {
17533 if (pcmd->UserCallback)
17534 {
17535 BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
17536 continue;
17537 }
17538
17539 char texid_desc[30];
17540 FormatTextureRefForDebugDisplay(texid_desc, IM_COUNTOF(texid_desc), pcmd->TexRef);
17541 char buf[300];
17542 ImFormatString(buf, IM_COUNTOF(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
17543 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
17544 bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
17545 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
17546 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
17547 if (!pcmd_node_open)
17548 continue;
17549
17550 // Calculate approximate coverage area (touched pixel count)
17551 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
17552 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
17553 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
17554 float total_area = 0.0f;
17555 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
17556 {
17557 ImVec2 triangle[3];
17558 for (int n = 0; n < 3; n++, idx_n++)
17559 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
17560 total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
17561 }
17562
17563 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
17564 ImFormatString(buf, IM_COUNTOF(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
17565 Selectable(buf);
17566 if (IsItemHovered() && fg_draw_list)
17567 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
17568
17569 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
17570 ImGuiListClipper clipper;
17571 clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
17572 while (clipper.Step())
17573 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
17574 {
17575 char* buf_p = buf, * buf_end = buf + IM_COUNTOF(buf);
17576 ImVec2 triangle[3];
17577 for (int n = 0; n < 3; n++, idx_i++)
17578 {
17579 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
17580 triangle[n] = v.pos;
17581 buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
17582 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
17583 }
17584
17585 Selectable(buf, false);
17586 if (fg_draw_list && IsItemHovered())
17587 {
17588 ImDrawListFlags backup_flags = fg_draw_list->Flags;
17589 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
17590 fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), 1.0f, ImDrawFlags_Closed);
17591 fg_draw_list->Flags = backup_flags;
17592 }
17593 }
17594 TreePop();
17595 }
17596 TreePop();
17597}
17598
17599// [DEBUG] Display mesh/aabb of a ImDrawCmd
17600void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
17601{
17602 IM_ASSERT(show_mesh || show_aabb);
17603
17604 // Draw wire-frame version of all triangles
17605 ImRect clip_rect = draw_cmd->ClipRect;
17606 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
17607 ImDrawListFlags backup_flags = out_draw_list->Flags;
17608 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
17609 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
17610 {
17611 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
17612 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
17613
17614 ImVec2 triangle[3];
17615 for (int n = 0; n < 3; n++, idx_n++)
17616 vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
17617 if (show_mesh)
17618 out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), 1.0f, ImDrawFlags_Closed); // In yellow: mesh triangles
17619 }
17620 // Draw bounding boxes
17621 if (show_aabb)
17622 {
17623 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
17624 out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
17625 }
17626 out_draw_list->Flags = backup_flags;
17627}
17628
17629// [DEBUG] Compute mask of inputs with the same codepoint.
17630static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint)
17631{
17632 int mask = 0, count = 0;
17633 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
17634 {
17635 ImFontConfig* src = font->Sources[src_n];
17636 if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint))
17637 continue;
17638 mask |= (1 << src_n);
17639 count++;
17640 }
17641 return count > 1 ? mask : 0;
17642}
17643
17644// [DEBUG] Display details for a single font, called by ShowStyleEditor().
17645void ImGui::DebugNodeFont(ImFont* font)
17646{
17647 ImGuiContext& g = *GImGui;
17648 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
17649 ImFontAtlas* atlas = font->OwnerAtlas;
17650 bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size);
17651
17652 // Display preview text
17653 if (!opened)
17654 Indent();
17655 Indent();
17656 if (cfg->ShowFontPreview)
17657 {
17658 PushFont(font, 0.0f);
17659 Text("The quick brown fox jumps over the lazy dog");
17660 PopFont();
17661 }
17662 if (!opened)
17663 {
17664 Unindent();
17665 Unindent();
17666 return;
17667 }
17668 if (SmallButton("Set as default"))
17669 GetIO().FontDefault = font;
17670 SameLine();
17671 BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked);
17672 if (SmallButton("Remove"))
17673 atlas->RemoveFont(font);
17674 EndDisabled();
17675 SameLine();
17676 if (SmallButton("Clear bakes"))
17677 ImFontAtlasFontDiscardBakes(atlas, font, 0);
17678 SameLine();
17679 if (SmallButton("Clear unused"))
17680 ImFontAtlasFontDiscardBakes(atlas, font, 2);
17681
17682 // Display details
17683#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
17684 SetNextItemWidth(GetFontSize() * 8);
17685 DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
17686 /*SameLine(); MetricsHelpMarker(
17687 "Note that the default embedded font is NOT meant to be scaled.\n\n"
17688 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
17689 "You may oversample them to get some flexibility with scaling. "
17690 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
17691 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/
17692#endif
17693
17694 char c_str[5];
17695 ImTextCharToUtf8(c_str, font->FallbackChar);
17696 Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar);
17697 ImTextCharToUtf8(c_str, font->EllipsisChar);
17698 Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar);
17699
17700 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
17701 {
17702 ImFontConfig* src = font->Sources[src_n];
17703 if (TreeNode(src, "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)",
17704 src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y))
17705 {
17706 const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
17707 Text("Loader: '%s'", loader->Name ? loader->Name : "N/A");
17708
17709 //if (DragFloat("ExtraSizeScale", &src->ExtraSizeScale, 0.01f, 0.10f, 2.0f))
17710 // ImFontAtlasFontRebuildOutput(atlas, font);
17711#ifdef IMGUI_ENABLE_FREETYPE
17712 if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0)
17713 {
17714 unsigned int loader_flags = src->FontLoaderFlags;
17715 Text("FreeType Loader Flags: 0x%08X", loader_flags);
17716 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
17717 {
17718 ImFontAtlasFontDestroyOutput(atlas, font);
17719 src->FontLoaderFlags = loader_flags;
17720 ImFontAtlasFontInitOutput(atlas, font);
17721 }
17722 }
17723#endif
17724 TreePop();
17725 }
17726 }
17727 if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool"))
17728 {
17729 TextWrapped("- First Input that contains the glyph is used.\n"
17730 "- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- Prefer using a small number of ranges as the list is scanned every time a new glyph is loaded,\n - e.g. GlyphExcludeRanges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };\n- This tool doesn't cache results and is slow, don't keep it open!");
17731 if (BeginTable("table", 2))
17732 {
17733 for (unsigned int c = 0; c < 0x10000; c++)
17734 if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c))
17735 {
17736 unsigned int c_end = c + 1;
17737 while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask)
17738 c_end++;
17739 if (TableNextColumn() && TreeNode((void*)(intptr_t)c, "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(overlap_mask)))
17740 {
17741 char utf8_buf[5];
17742 for (unsigned int n = c; n < c_end; n++)
17743 {
17744 ImTextCharToUtf8(utf8_buf, n);
17745 BulletText("Codepoint U+%04X (%s)", n, utf8_buf);
17746 }
17747 TreePop();
17748 }
17749 TableNextColumn();
17750 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
17751 if (overlap_mask & (1 << src_n))
17752 {
17753 Text("%d ", src_n);
17754 SameLine();
17755 }
17756 c = c_end - 1;
17757 }
17758 EndTable();
17759 }
17760 TreePop();
17761 }
17762
17763 // Display all glyphs of the fonts in separate pages of 256 characters
17764 for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++)
17765 {
17766 ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n];
17767 if (baked->OwnerFont != font)
17768 continue;
17769 PushID(baked->BakedId);
17770 if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : ""))
17771 {
17772 if (SmallButton("Load all"))
17773 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++)
17774 baked->FindGlyph((ImWchar)base);
17775
17776 const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface);
17777 Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent);
17778 Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt);
17779 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
17780 {
17781 ImFontConfig* src = font->Sources[src_n];
17782 int oversample_h, oversample_v;
17783 ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v);
17784 BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
17785 src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y);
17786 }
17787
17788 DebugNodeFontGlyphsForSrcMask(font, baked, ~0);
17789 TreePop();
17790 }
17791 PopID();
17792 }
17793 TreePop();
17794 Unindent();
17795}
17796
17797void ImGui::DebugNodeFontGlyphsForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask)
17798{
17799 ImDrawList* draw_list = GetWindowDrawList();
17800 const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
17801 const float cell_size = baked->Size * 1;
17802 const float cell_spacing = GetStyle().ItemSpacing.y;
17803 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
17804 {
17805 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
17806 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
17807 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
17808 if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191))
17809 {
17810 base += 8192 - 256;
17811 continue;
17812 }
17813
17814 int count = 0;
17815 for (unsigned int n = 0; n < 256; n++)
17816 if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL)
17817 if (src_mask & (1 << glyph->SourceIdx))
17818 count++;
17819 if (count <= 0)
17820 continue;
17821 if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
17822 continue;
17823
17824 // Draw a 16x16 grid of glyphs
17825 ImVec2 base_pos = GetCursorScreenPos();
17826 for (unsigned int n = 0; n < 256; n++)
17827 {
17828 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
17829 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
17830 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
17831 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
17832 const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL;
17833 draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
17834 if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0)
17835 continue;
17836 font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
17837 if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
17838 {
17839 DebugNodeFontGlyph(font, glyph);
17840 EndTooltip();
17841 }
17842 }
17843 Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
17844 TreePop();
17845 }
17846}
17847
17848void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph)
17849{
17850 Text("Codepoint: U+%04X", glyph->Codepoint);
17851 Separator();
17852 Text("Visible: %d", glyph->Visible);
17853 Text("AdvanceX: %.1f", glyph->AdvanceX);
17854 Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
17855 Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
17856 if (glyph->PackId >= 0)
17857 {
17858 ImTextureRect* r = ImFontAtlasPackGetRect(font->OwnerAtlas, glyph->PackId);
17859 Text("PackId: 0x%X (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);
17860 }
17861 Text("SourceIdx: %d", glyph->SourceIdx);
17862}
17863
17864// [DEBUG] Display contents of ImGuiStorage
17865void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
17866{
17867 if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
17868 return;
17869 for (const ImGuiStoragePair& p : storage->Data)
17870 {
17871 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.
17872 DebugLocateItemOnHover(p.key);
17873 }
17874 TreePop();
17875}
17876
17877// [DEBUG] Display contents of ImGuiTabBar
17878void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
17879{
17880 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
17881 char buf[256];
17882 char* p = buf;
17883 const char* buf_end = buf + IM_COUNTOF(buf);
17884 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
17885 p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
17886 for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
17887 {
17888 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17889 p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
17890 }
17891 p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
17892 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
17893 bool open = TreeNode(label, "%s", buf);
17894 if (!is_active) { PopStyleColor(); }
17895 if (is_active && IsItemHovered())
17896 {
17897 ImDrawList* draw_list = GetForegroundDrawList(tab_bar->Window);
17898 draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
17899 draw_list->AddLineV(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y, tab_bar->BarRect.Max.y, IM_COL32(0, 255, 0, 255));
17900 draw_list->AddLineV(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y, tab_bar->BarRect.Max.y, IM_COL32(0, 255, 0, 255));
17901 }
17902 if (open)
17903 {
17904 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17905 {
17906 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17907 PushID(tab);
17908 if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
17909 if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
17910 Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
17911 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
17912 PopID();
17913 }
17914 TreePop();
17915 }
17916}
17917
17918void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
17919{
17920 ImGuiContext& g = *GImGui;
17921 SetNextItemOpen(true, ImGuiCond_Once);
17922 bool open = TreeNode("viewport0", "Viewport #%d", 0);
17923 if (IsItemHovered())
17924 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
17925 if (open)
17926 {
17927 ImGuiWindowFlags flags = viewport->Flags;
17928 BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
17929 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
17930 viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y);
17931 BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags,
17932 (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "",
17933 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
17934 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "");
17935 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
17936 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
17937 TreePop();
17938 }
17939}
17940
17941void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
17942{
17943 if (window == NULL)
17944 {
17945 BulletText("%s: NULL", label);
17946 return;
17947 }
17948
17949 ImGuiContext& g = *GImGui;
17950 const bool is_active = window->WasActive;
17951 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
17952 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
17953 const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
17954 if (!is_active) { PopStyleColor(); }
17955 if (IsItemHovered() && is_active)
17956 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
17957 if (!open)
17958 return;
17959
17960 if (window->MemoryCompacted)
17961 TextDisabled("Note: some memory buffers have been compacted/freed.");
17962
17963 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
17964 g.DebugBreakInWindow = window->ID;
17965
17966 ImGuiWindowFlags flags = window->Flags;
17967 DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
17968 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);
17969 BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
17970 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
17971 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
17972 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
17973 if (flags & ImGuiWindowFlags_ChildWindow)
17974 BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
17975 (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "",
17976 (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
17977 (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
17978 (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
17979 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" : "");
17980 BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
17981 BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
17982 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
17983 {
17984 ImRect r = window->NavRectRel[layer];
17985 if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
17986 BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
17987 else
17988 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);
17989 DebugLocateItemOnHover(window->NavLastIds[layer]);
17990 }
17991 const ImVec2* pr = window->NavPreferredScoringPosRel;
17992 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
17993 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.
17994 BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
17995 if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
17996 if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
17997 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
17998 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
17999 if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
18000 {
18001 for (ImGuiOldColumns& columns : window->ColumnsStorage)
18002 DebugNodeColumns(&columns);
18003 TreePop();
18004 }
18005 DebugNodeStorage(&window->StateStorage, "Storage");
18006 TreePop();
18007}
18008
18009void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
18010{
18011 if (settings->WantDelete)
18012 BeginDisabled();
18013 BulletText("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
18014 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
18015 if (settings->WantDelete)
18016 EndDisabled();
18017}
18018
18019void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
18020{
18021 if (!TreeNode(label, "%s (%d)", label, windows->Size))
18022 return;
18023 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
18024 {
18025 PushID((*windows)[i]);
18026 DebugNodeWindow((*windows)[i], "Window");
18027 PopID();
18028 }
18029 TreePop();
18030}
18031
18032// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
18033void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
18034{
18035 for (int i = 0; i < windows_size; i++)
18036 {
18037 ImGuiWindow* window = windows[i];
18038 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
18039 continue;
18040 char buf[20];
18041 ImFormatString(buf, IM_COUNTOF(buf), "[%04d] Window", window->BeginOrderWithinContext);
18042 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
18043 DebugNodeWindow(window, buf);
18044 TreePush(buf);
18045 DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
18046 TreePop();
18047 }
18048}
18049
18050//-----------------------------------------------------------------------------
18051// [SECTION] DEBUG LOG WINDOW
18052//-----------------------------------------------------------------------------
18053
18054void ImGui::DebugLog(const char* fmt, ...)
18055{
18056 va_list args;
18057 va_start(args, fmt);
18058 DebugLogV(fmt, args);
18059 va_end(args);
18060}
18061
18062void ImGui::DebugLogV(const char* fmt, va_list args)
18063{
18064 ImGuiContext& g = *GImGui;
18065 const int old_size = g.DebugLogBuf.size();
18066 if (g.ContextName[0] != 0)
18067 g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
18068 else
18069 g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
18070 g.DebugLogBuf.appendfv(fmt, args);
18071 g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
18072
18073 const char* str = g.DebugLogBuf.begin() + old_size;
18074 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
18075 IMGUI_DEBUG_PRINTF("%s", str);
18076#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
18077 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToDebugger)
18078 {
18079 ::OutputDebugStringA("[imgui] ");
18080 ::OutputDebugStringA(str);
18081 }
18082#endif
18083#ifdef IMGUI_ENABLE_TEST_ENGINE
18084 // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
18085 const int new_size = g.DebugLogBuf.size();
18086 const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
18087 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
18088 IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), str);
18089#endif
18090}
18091
18092// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
18093static void SameLineOrWrap(const ImVec2& size)
18094{
18095 ImGuiContext& g = *GImGui;
18096 ImGuiWindow* window = g.CurrentWindow;
18097 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
18098 if (window->WorkRect.Contains(ImRect(pos, pos + size)))
18099 ImGui::SameLine();
18100}
18101
18102static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
18103{
18104 ImGuiContext& g = *GImGui;
18105 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
18106 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
18107
18108 bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0);
18109 if (highlight_errors)
18110 ImGui::PushStyleColor(ImGuiCol_Text, ImLerp(g.Style.Colors[ImGuiCol_Text], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.30f));
18111 if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
18112 {
18113 g.DebugLogAutoDisableFrames = 2;
18114 g.DebugLogAutoDisableFlags |= flags;
18115 }
18116 if (highlight_errors)
18117 {
18118 ImGui::PopStyleColor();
18119 ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors);
18120 }
18121 else
18122 {
18123 ImGui::SetItemTooltip("Hold Shift when clicking to enable for 2 frames only (useful for spammy log entries)");
18124 }
18125}
18126
18127void ImGui::ShowDebugLogWindow(bool* p_open)
18128{
18129 ImGuiContext& g = *GImGui;
18130 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
18131 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
18132 if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
18133 {
18134 End();
18135 return;
18136 }
18137
18138 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
18139 CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
18140 SetItemTooltip("(except InputRouting which is spammy)");
18141
18142 ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError);
18143 ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
18144 ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
18145 ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
18146 ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
18147 ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont);
18148 ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
18149 ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
18150 ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
18151 ShowDebugLogFlag("Table", ImGuiDebugLogFlags_EventTable);
18152 ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
18153
18154 if (SmallButton("Clear"))
18155 {
18156 g.DebugLogBuf.clear();
18157 g.DebugLogIndex.clear();
18158 g.DebugLogSkippedErrors = 0;
18159 }
18160 SameLine();
18161 if (SmallButton("Copy"))
18162 SetClipboardText(g.DebugLogBuf.c_str());
18163 SameLine();
18164 if (SmallButton("Configure Outputs.."))
18165 OpenPopup("Outputs");
18166 if (BeginPopup("Outputs"))
18167 {
18168 CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
18169 CheckboxFlags("OutputToDebugger", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToDebugger);
18170#ifndef IMGUI_ENABLE_TEST_ENGINE
18171 BeginDisabled();
18172#endif
18173 CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
18174#ifndef IMGUI_ENABLE_TEST_ENGINE
18175 EndDisabled();
18176#endif
18177 EndPopup();
18178 }
18179
18180 BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
18181
18182 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
18183 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
18184
18185 ImGuiListClipper clipper;
18186 clipper.Begin(g.DebugLogIndex.size());
18187 while (clipper.Step())
18188 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
18189 DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
18190 g.DebugLogFlags = backup_log_flags;
18191 if (GetScrollY() >= GetScrollMaxY())
18192 SetScrollHereY(1.0f);
18193 EndChild();
18194
18195 End();
18196}
18197
18198// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
18199void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
18200{
18201 TextUnformatted(line_begin, line_end);
18202 if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
18203 return;
18204 ImGuiContext& g = *GImGui;
18205 ImRect text_rect = g.LastItemData.Rect;
18206 for (const char* p = line_begin; p <= line_end - 10; p++)
18207 {
18208 ImGuiID id = 0;
18209 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10]))
18210 continue;
18211 ImVec2 p0 = CalcTextSize(line_begin, p);
18212 ImVec2 p1 = CalcTextSize(p, p + 10);
18213 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
18214 if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
18215 DebugLocateItemOnHover(id);
18216 p += 10;
18217 }
18218}
18219
18220//-----------------------------------------------------------------------------
18221// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
18222//-----------------------------------------------------------------------------
18223
18224// Draw a small cross at current CursorPos in current window's DrawList
18225void ImGui::DebugDrawCursorPos(ImU32 col)
18226{
18227 ImGuiContext& g = *GImGui;
18228 ImGuiWindow* window = g.CurrentWindow;
18229 ImVec2 pos = window->DC.CursorPos;
18230 window->DrawList->AddLineV(pos.x, pos.y - 3.0f, pos.y + 4.0f, col, 1.0f);
18231 window->DrawList->AddLineH(pos.x - 3.0f, pos.x + 4.0f, pos.y, col, 1.0f);
18232}
18233
18234// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
18235void ImGui::DebugDrawLineExtents(ImU32 col)
18236{
18237 ImGuiContext& g = *GImGui;
18238 ImGuiWindow* window = g.CurrentWindow;
18239 float curr_x = window->DC.CursorPos.x;
18240 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
18241 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
18242 window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y1, col, 1.0f);
18243 window->DrawList->AddLineV(curr_x - 0.5f, line_y1, line_y2, col, 1.0f);
18244 window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y2, col, 1.0f);
18245}
18246
18247// Draw last item rect in ForegroundDrawList (so it is always visible)
18248void ImGui::DebugDrawItemRect(ImU32 col)
18249{
18250 ImGuiContext& g = *GImGui;
18251 ImGuiWindow* window = g.CurrentWindow;
18252 GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
18253}
18254
18255// [DEBUG] Locate item position/rectangle given an ID.
18256static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
18257
18258void ImGui::DebugLocateItem(ImGuiID target_id)
18259{
18260 ImGuiContext& g = *GImGui;
18261 g.DebugLocateId = target_id;
18262 g.DebugLocateFrames = 2;
18263 g.DebugBreakInLocateId = false;
18264}
18265
18266// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
18267void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
18268{
18269 if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
18270 return;
18271 ImGuiContext& g = *GImGui;
18272 DebugLocateItem(target_id);
18273 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);
18274
18275 // Can't easily use a context menu here because it will mess with focus, active id etc.
18276 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
18277 {
18278 DebugBreakButtonTooltip(false, "in ItemAdd()");
18279 if (IsKeyChordPressed(g.DebugBreakKeyChord))
18280 g.DebugBreakInLocateId = true;
18281 }
18282}
18283
18284void ImGui::DebugLocateItemResolveWithLastItem()
18285{
18286 ImGuiContext& g = *GImGui;
18287
18288 // [DEBUG] Debug break requested by user
18289 if (g.DebugBreakInLocateId)
18290 IM_DEBUG_BREAK();
18291
18292 ImGuiLastItemData item_data = g.LastItemData;
18293 g.DebugLocateId = 0;
18294 ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
18295 ImRect r = item_data.Rect;
18296 r.Expand(3.0f);
18297 ImVec2 p1 = g.IO.MousePos;
18298 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);
18299 draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
18300 draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
18301}
18302
18303void ImGui::DebugStartItemPicker()
18304{
18305 ImGuiContext& g = *GImGui;
18306 g.DebugItemPickerActive = true;
18307}
18308
18309// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
18310void ImGui::UpdateDebugToolItemPicker()
18311{
18312 ImGuiContext& g = *GImGui;
18313 g.DebugItemPickerBreakId = 0;
18314 if (!g.DebugItemPickerActive)
18315 return;
18316
18317 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
18318 SetMouseCursor(ImGuiMouseCursor_Hand);
18319 if (IsKeyPressed(ImGuiKey_Escape))
18320 g.DebugItemPickerActive = false;
18321 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
18322 if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
18323 {
18324 g.DebugItemPickerBreakId = hovered_id;
18325 g.DebugItemPickerActive = false;
18326 }
18327 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
18328 if (change_mapping && IsMouseClicked(mouse_button))
18329 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
18330 SetNextWindowBgAlpha(0.70f);
18331 if (!BeginTooltip())
18332 return;
18333 Text("HoveredId: 0x%08X", hovered_id);
18334 Text("Press ESC to abort picking.");
18335 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
18336 if (change_mapping)
18337 Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
18338 else
18339 TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
18340 EndTooltip();
18341}
18342
18343// Update queries. The steps are: -1: query Stack, >= 0: query each stack item
18344// We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
18345static ImGuiID DebugItemPathQuery_UpdateAndGetHookId(ImGuiDebugItemPathQuery* query, ImGuiID id)
18346{
18347 // Update query. Clear hook when no active query
18348 if (query->MainID != id)
18349 {
18350 query->MainID = id;
18351 query->Step = -1;
18352 query->Complete = false;
18353 query->Results.resize(0);
18354 query->ResultsDescBuf.resize(0);
18355 }
18356 query->Active = false;
18357 if (id == 0)
18358 return 0;
18359
18360 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
18361 if (query->Step >= 0 && query->Step < query->Results.Size)
18362 if (query->Results[query->Step].QuerySuccess || query->Results[query->Step].QueryFrameCount > 2)
18363 query->Step++;
18364
18365 // Update status and hook
18366 query->Complete = (query->Step == query->Results.Size);
18367 if (query->Step == -1)
18368 {
18369 query->Active = true;
18370 return id;
18371 }
18372 else if (query->Step >= 0 && query->Step < query->Results.Size)
18373 {
18374 query->Results[query->Step].QueryFrameCount++;
18375 query->Active = true;
18376 return query->Results[query->Step].ID;
18377 }
18378 return 0;
18379}
18380
18381// [DEBUG] ID Stack Tool: update query. Called by NewFrame()
18382void ImGui::UpdateDebugToolItemPathQuery()
18383{
18384 ImGuiContext& g = *GImGui;
18385 ImGuiID id = 0;
18386 if (g.DebugIDStackTool.LastActiveFrame + 1 == g.FrameCount)
18387 id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
18388 g.DebugHookIdInfoId = DebugItemPathQuery_UpdateAndGetHookId(&g.DebugItemPathQuery, id);
18389}
18390
18391// [DEBUG] ID Stack tool: hooks called by GetID() family functions
18392void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
18393{
18394 ImGuiContext& g = *GImGui;
18395 ImGuiDebugItemPathQuery* query = &g.DebugItemPathQuery;
18396 if (query->Active == false)
18397 {
18398 IM_ASSERT(id == 0);
18399 return;
18400 }
18401 ImGuiWindow* window = g.CurrentWindow;
18402
18403 // Step -1: stack query
18404 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
18405 if (query->Step == -1)
18406 {
18407 IM_ASSERT(query->Results.Size == 0);
18408 query->Step++;
18409 query->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
18410 for (int n = 0; n < window->IDStack.Size + 1; n++)
18411 query->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
18412 return;
18413 }
18414
18415 // Step 0+: query for individual level
18416 IM_ASSERT(query->Step >= 0);
18417 if (query->Step != window->IDStack.Size)
18418 return;
18419 ImGuiStackLevelInfo* info = &query->Results[query->Step];
18420 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
18421
18422 if (info->DescOffset == -1)
18423 {
18424 const char* result = NULL;
18425 const char* result_end = NULL;
18426 switch (data_type)
18427 {
18428 case ImGuiDataType_S32:
18429 ImFormatStringToTempBuffer(&result, &result_end, "%d", (int)(intptr_t)data_id);
18430 break;
18431 case ImGuiDataType_String:
18432 ImFormatStringToTempBuffer(&result, &result_end, "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id);
18433 break;
18434 case ImGuiDataType_Pointer:
18435 ImFormatStringToTempBuffer(&result, &result_end, "(void*)0x%p", data_id);
18436 break;
18437 case ImGuiDataType_ID:
18438 // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
18439 ImFormatStringToTempBuffer(&result, &result_end, "0x%08X [override]", id);
18440 break;
18441 default:
18442 IM_ASSERT(0);
18443 }
18444 info->DescOffset = query->ResultsDescBuf.size();
18445 query->ResultsDescBuf.append(result, result_end + 1); // Include zero terminator
18446 }
18447 info->QuerySuccess = true;
18448 if (info->DataType == -1)
18449 info->DataType = (ImS8)data_type;
18450}
18451
18452static int DebugItemPathQuery_FormatLevelInfo(ImGuiDebugItemPathQuery* query, int n, bool format_for_ui, char* buf, size_t buf_size)
18453{
18454 ImGuiStackLevelInfo* info = &query->Results[n];
18455 ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
18456 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
18457 return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name));
18458 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
18459 return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&query->ResultsDescBuf.Buf[info->DescOffset]));
18460 if (query->Step < query->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
18461 return (*buf = 0);
18462#ifdef IMGUI_ENABLE_TEST_ENGINE
18463 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
18464 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", ImHashSkipUncontributingPrefix(label));
18465#endif
18466 return ImFormatString(buf, buf_size, "???");
18467}
18468
18469static const char* DebugItemPathQuery_GetResultAsPath(ImGuiDebugItemPathQuery* query, bool hex_encode_non_ascii_chars)
18470{
18471 ImGuiTextBuffer* buf = &query->ResultPathBuf;
18472 buf->resize(0);
18473 for (int stack_n = 0; stack_n < query->Results.Size; stack_n++)
18474 {
18475 char level_desc[256];
18476 DebugItemPathQuery_FormatLevelInfo(query, stack_n, false, level_desc, IM_COUNTOF(level_desc));
18477 buf->append(stack_n == 0 ? "//" : "/");
18478 for (const char* p = level_desc; *p != 0; )
18479 {
18480 unsigned int c;
18481 const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL);
18482 if (c == '/')
18483 buf->append("\\");
18484 if (c < 256 || !hex_encode_non_ascii_chars)
18485 buf->append(p, p_next);
18486 else for (; p < p_next; p++)
18487 buf->appendf("\\x%02x", (unsigned char)*p);
18488 p = p_next;
18489 }
18490 }
18491 return buf->c_str();
18492}
18493
18494// ID Stack Tool: Display UI
18495void ImGui::ShowIDStackToolWindow(bool* p_open)
18496{
18497 ImGuiContext& g = *GImGui;
18498 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
18499 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
18500 if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
18501 {
18502 End();
18503 return;
18504 }
18505
18506 ImGuiDebugItemPathQuery* query = &g.DebugItemPathQuery;
18507 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
18508 tool->LastActiveFrame = g.FrameCount;
18509 const char* result_path = DebugItemPathQuery_GetResultAsPath(query, tool->OptHexEncodeNonAsciiChars);
18510 Text("0x%08X", query->MainID);
18511 SameLine();
18512 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.");
18513
18514 // Ctrl+C to copy path
18515 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
18516 PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f);
18517 Checkbox("Hex-encode non-ASCII", &tool->OptHexEncodeNonAsciiChars);
18518 SameLine();
18519 Checkbox("Ctrl+C: copy path", &tool->OptCopyToClipboardOnCtrlC);
18520 PopStyleVar();
18521 SameLine();
18522 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*");
18523 if (tool->OptCopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
18524 {
18525 tool->CopyToClipboardLastTime = (float)g.Time;
18526 SetClipboardText(result_path);
18527 }
18528
18529 Text("- Path \"%s\"", query->Complete ? result_path : "");
18530#ifdef IMGUI_ENABLE_TEST_ENGINE
18531 Text("- Label \"%s\"", query->MainID ? ImGuiTestEngine_FindItemDebugLabel(&g, query->MainID) : "");
18532#endif
18533 Separator();
18534
18535 // Display decorated stack
18536 if (query->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
18537 {
18538 const float id_width = CalcTextSize("0xDDDDDDDD").x;
18539 TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
18540 TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
18541 TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
18542 TableHeadersRow();
18543 for (int n = 0; n < query->Results.Size; n++)
18544 {
18545 ImGuiStackLevelInfo* info = &query->Results[n];
18546 TableNextColumn();
18547 Text("0x%08X", (n > 0) ? query->Results[n - 1].ID : 0);
18548 TableNextColumn();
18549 DebugItemPathQuery_FormatLevelInfo(query, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
18550 TextUnformatted(g.TempBuffer.Data);
18551 TableNextColumn();
18552 Text("0x%08X", info->ID);
18553 if (n == query->Results.Size - 1)
18554 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
18555 }
18556 EndTable();
18557 }
18558 End();
18559}
18560
18561#else
18562
18563void ImGui::ShowMetricsWindow(bool*) {}
18564void ImGui::ShowFontAtlas(ImFontAtlas*) {}
18565void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
18566void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
18567void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
18568void ImGui::DebugNodeFont(ImFont*) {}
18569void ImGui::DebugNodeFontGlyphsForSrcMask(ImFont*, ImFontBaked*, int) {}
18570void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
18571void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
18572void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
18573void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
18574void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
18575void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
18576
18577void ImGui::ShowDebugLogWindow(bool*) {}
18578void ImGui::ShowIDStackToolWindow(bool*) {}
18579void ImGui::DebugStartItemPicker() {}
18580void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
18581
18582#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
18583
18584#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
18585// Demo helper function to select among loaded fonts.
18586// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.
18587void ImGui::ShowFontSelector(const char* label)
18588{
18589 ImGuiIO& io = GetIO();
18590 ImFont* font_current = GetFont();
18591 if (BeginCombo(label, font_current->GetDebugName()))
18592 {
18593 for (ImFont* font : io.Fonts->Fonts)
18594 {
18595 PushID((void*)font);
18596 if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav))
18597 io.FontDefault = font;
18598 if (font == font_current)
18599 SetItemDefaultFocus();
18600 PopID();
18601 }
18602 EndCombo();
18603 }
18604 SameLine();
18605 if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
18606 MetricsHelpMarker(
18607 "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
18608 "- Read FAQ and docs/FONTS.md for more details.");
18609 else
18610 MetricsHelpMarker(
18611 "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
18612 "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
18613 "- Read FAQ and docs/FONTS.md for more details.\n"
18614 "- Legacy backend: if you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
18615}
18616#endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
18617
18618//-----------------------------------------------------------------------------
18619
18620// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
18621// 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.
18622#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
18623#include "imgui_user.inl"
18624#endif
18625
18626//-----------------------------------------------------------------------------
18627
18628#endif // #ifndef IMGUI_DISABLE