1// dear imgui, v1.92.2b
2// (main code and documentation)
3
4// Help:
5// - See links below.
6// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7// - Read top of imgui.cpp for more details, links and comments.
8
9// Resources:
10// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11// - Homepage ................... https://github.com/ocornut/imgui
12// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!)
14// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21// - Issues & support ........... https://github.com/ocornut/imgui/issues
22// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24// For first-time users having issues compiling/linking/running:
25// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27// Since 1.92, we encourage font loading questions to also be posted in 'Issues'.
28
29// Copyright (c) 2014-2025 Omar Cornut
30// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
31// See LICENSE.txt for copyright and licensing details (standard MIT License).
32// This library is free but needs your support to sustain development and maintenance.
33// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
34// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
35// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
36
37// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
38// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
39// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
40// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
41// to a better solution or official support for them.
42
43/*
44
45Index of this file:
46
47DOCUMENTATION
48
49- MISSION STATEMENT
50- CONTROLS GUIDE
51- PROGRAMMER GUIDE
52 - READ FIRST
53 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
54 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
55 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
56 - USING CUSTOM BACKEND / CUSTOM ENGINE
57- API BREAKING CHANGES (read me when you update!)
58- FREQUENTLY ASKED QUESTIONS (FAQ)
59 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
60
61CODE
62(search for "[SECTION]" in the code to find them)
63
64// [SECTION] INCLUDES
65// [SECTION] FORWARD DECLARATIONS
66// [SECTION] CONTEXT AND MEMORY ALLOCATORS
67// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
68// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
69// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
70// [SECTION] MISC HELPERS/UTILITIES (File functions)
71// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
72// [SECTION] MISC HELPERS/UTILITIES (Color functions)
73// [SECTION] ImGuiStorage
74// [SECTION] ImGuiTextFilter
75// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
76// [SECTION] ImGuiListClipper
77// [SECTION] STYLING
78// [SECTION] RENDER HELPERS
79// [SECTION] INITIALIZATION, SHUTDOWN
80// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
81// [SECTION] FONTS, TEXTURES
82// [SECTION] ID STACK
83// [SECTION] INPUTS
84// [SECTION] ERROR CHECKING, STATE RECOVERY
85// [SECTION] ITEM SUBMISSION
86// [SECTION] LAYOUT
87// [SECTION] SCROLLING
88// [SECTION] TOOLTIPS
89// [SECTION] POPUPS
90// [SECTION] WINDOW FOCUS
91// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
92// [SECTION] DRAG AND DROP
93// [SECTION] LOGGING/CAPTURING
94// [SECTION] SETTINGS
95// [SECTION] LOCALIZATION
96// [SECTION] VIEWPORTS, PLATFORM WINDOWS
97// [SECTION] DOCKING
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.
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 OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
152
153 - KEYBOARD CONTROLS
154 - Basic:
155 - Tab, SHIFT+Tab Cycle through text editable fields.
156 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
157 - CTRL+Click Input text into a Slider or Drag widget.
158 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
159 - Tab, SHIFT+Tab: Cycle through every items.
160 - Arrow keys Move through items using directional navigation. Tweak value.
161 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
162 - Enter Activate item (prefer text input when possible).
163 - Space Activate item (prefer tweaking with arrows when possible).
164 - Escape Deactivate item, leave child window, close popup.
165 - Page Up, Page Down Previous page, next page.
166 - Home, End Scroll to top, scroll to bottom.
167 - Alt Toggle between scrolling layer and menu layer.
168 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
169 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
170 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
171 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
172 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
173
174 - GAMEPAD CONTROLS
175 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
176 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
177 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
178 - Backend support: backend needs to:
179 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
180 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
181 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.).
182 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
183 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
184
185 - REMOTE INPUTS SHARING & MOUSE EMULATION
186 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
187 - 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)
188 in order to share your PC mouse/keyboard.
189 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
190 - 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.
191 Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
192 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.
193 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.
194 (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!)
195 (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
196 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
197
198
199 PROGRAMMER GUIDE
200 ================
201
202 READ FIRST
203 ----------
204 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
205 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
206 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
207 data retention on your side, less state duplication, less state synchronization, fewer bugs.
208 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
209 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
210 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
211 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
212 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
213 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
214 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,
215 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
216 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
217 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
218 If you get an assert, read the messages and comments around the assert.
219 - This codebase aims to be highly optimized:
220 - A typical idle frame should never call malloc/free.
221 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
222 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
223 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
224 - This codebase aims to be both highly opinionated and highly flexible:
225 - This code works because of the things it choose to solve or not solve.
226 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
227 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
228 This is to increase compatibility, increase maintainability and facilitate use from other languages.
229 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
230 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
231 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
232 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
233 (so don't use ImVector in your code or at our own risk!).
234 - Building: We don't use nor mandate a build system for the main library.
235 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
236 This is also because providing a build system for the main library would be of little-value.
237 The build problems are almost never coming from the main library but from specific backends.
238
239
240 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
241 ----------------------------------------------
242 - Update submodule or copy/overwrite every file.
243 - About imconfig.h:
244 - You may modify your copy of imconfig.h, in this case don't overwrite it.
245 - or you may locally branch to modify imconfig.h and merge/rebase latest.
246 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
247 specify a custom path for your imconfig.h file and instead not have to modify the default one.
248
249 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
250 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
251 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
252 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
253 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
254 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
255 likely be a comment about it. Please report any issue to the GitHub page!
256 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
257 - Try to keep your copy of Dear ImGui reasonably up to date!
258
259
260 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
261 ---------------------------------------------------------------
262 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
263 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
264 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
265 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
266 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
267 - 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.
268 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
269 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
270 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
271 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
272 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
273 - 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.
274
275
276 HOW A SIMPLE APPLICATION MAY LOOK LIKE
277 --------------------------------------
278
279 USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
280 The sub-folders in examples/ contain examples applications following this structure.
281
282 // Application init: create a dear imgui context, setup some options, load fonts
283 ImGui::CreateContext();
284 ImGuiIO& io = ImGui::GetIO();
285 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
286 // TODO: Fill optional fields of the io structure later.
287 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
288
289 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
290 ImGui_ImplWin32_Init(hwnd);
291 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
292
293 // Application main loop
294 while (true)
295 {
296 // Feed inputs to dear imgui, start new frame
297 ImGui_ImplDX11_NewFrame();
298 ImGui_ImplWin32_NewFrame();
299 ImGui::NewFrame();
300
301 // Any application code here
302 ImGui::Text("Hello, world!");
303
304 // Render dear imgui into framebuffer
305 ImGui::Render();
306 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
307 g_pSwapChain->Present(1, 0);
308 }
309
310 // Shutdown
311 ImGui_ImplDX11_Shutdown();
312 ImGui_ImplWin32_Shutdown();
313 ImGui::DestroyContext();
314
315 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
316 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
317 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
318
319
320USING CUSTOM BACKEND / CUSTOM ENGINE
321------------------------------------
322
323IMPLEMENTING YOUR PLATFORM BACKEND:
324 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions.
325 -> the Platform backends in impl_impl_XXX.cpp files contain many implementations.
326
327IMPLEMENTING YOUR RenderDrawData() function:
328 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
329 -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function.
330
331IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures:
332 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
333 -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function.
334
335 Basic application/backend skeleton:
336
337 // Application init: create a Dear ImGui context, setup some options, load fonts
338 ImGui::CreateContext();
339 ImGuiIO& io = ImGui::GetIO();
340 // TODO: set io.ConfigXXX values, e.g.
341 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls
342
343 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
344 io.Fonts->AddFontFromFileTTF("NotoSans.ttf");
345
346 // Application main loop
347 while (true)
348 {
349 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
350 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
351 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
352 io.DisplaySize.x = 1920.0f; // set the current display width
353 io.DisplaySize.y = 1280.0f; // set the current display height here
354 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
355 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
356 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
357
358 // Call NewFrame(), after this point you can use ImGui::* functions anytime
359 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
360 ImGui::NewFrame();
361
362 // Most of your application code here
363 ImGui::Text("Hello, world!");
364 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
365 MyGameRender(); // may use any Dear ImGui functions as well!
366
367 // End the dear imgui frame
368 // (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)
369 ImGui::EndFrame(); // this is automatically called by Render(), but available
370 ImGui::Render();
371
372 // Update textures
373 ImDrawData* draw_data = ImGui::GetDrawData();
374 for (ImTextureData* tex : *draw_data->Textures)
375 if (tex->Status != ImTextureStatus_OK)
376 MyImGuiBackend_UpdateTexture(tex);
377
378 // Render dear imgui contents, swap buffers
379 MyImGuiBackend_RenderDrawData(draw_data);
380 SwapBuffers();
381 }
382
383 // Shutdown
384 ImGui::DestroyContext();
385
386
387
388 API BREAKING CHANGES
389 ====================
390
391 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
392 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.
393 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.
394 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
395
396(Docking/Viewport Branch)
397 - 2025/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
398 - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
399 you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
400 - likewise io.MousePos and GetMousePos() will use OS coordinates.
401 If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
402
403 - 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)
404 - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete).
405 - 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
406 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)
407 - Incorrect way to make a window content size 200x200:
408 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
409 - Correct ways to make a window content size 200x200:
410 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
411 Begin(...) + Dummy(ImVec2(200,200)) + End();
412 - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries.
413 - 2025/06/11 (1.92.0) - Renamed/moved ImGuiConfigFlags_DpiEnableScaleFonts -> bool io.ConfigDpiScaleFonts.
414 - Renamed/moved ImGuiConfigFlags_DpiEnableScaleViewports -> bool io.ConfigDpiScaleViewports. **Neither of those flags are very useful in current code. They will be useful once we merge font changes.**
415 - 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.
416 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/
417 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+).
418 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.
419 - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this!
420 - 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):
421 This WILL NOT map correctly to the new system! Because font will rasterize as requested size.
422 - 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.
423 - 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.
424 - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized.
425 - PushFont() API now has a REQUIRED size parameter.
426 - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize).
427 - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value.
428 - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site.
429 - Kept inline single parameter function. Will obsolete.
430 - Fonts: **IMPORTANT** on Font Merging:
431 - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph.
432 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.
433 - 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!
434 - 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.
435 After the update and when using a new backend, those glyphs may now loaded from Font Source 1!
436 - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source:
437 // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
438 static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
439 ImFontConfig cfg1;
440 cfg1.GlyphExcludeRanges = exclude_ranges;
441 io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
442 // Add Font Source 2, which expects to use the range above
443 ImFontConfig cfg2;
444 cfg2.MergeMode = true;
445 io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
446 - 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 unde
447 - Fonts: **IMPORTANT** on Thread Safety:
448 - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded.
449 - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont().
450 - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font".
451 - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'.
452 - 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().
453 - 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).
454 - 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.
455 - 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().
456 - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327)
457 - 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.
458 - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors.
459 - Fonts: obsoleted ImFont::Scale which is not useful anymore.
460 - 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:
461 - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef.
462 - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef.
463 - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]
464 - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount.
465 - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size.
466 - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance().
467 - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels().
468 - 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.)
469 - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags.
470 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().
471 - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()
472 - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader()
473 - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1]
474 - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV().
475 - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h.
476 - old:
477 const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id);
478 ImVec2 uv0, uv1;
479 atlas->GetCustomRectUV(r, &uv0, &uv1);
480 ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1);
481 - new;
482 ImFontAtlasRect r;
483 atlas->GetCustomRect(custom_rect_id, &r);
484 ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
485 - 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.
486 - 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.
487 - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
488 - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture().
489 - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more.
490 - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition()
491 - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....);
492 - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....);
493 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.
494 - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete).
495 - 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)
496 - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead.
497 - 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.
498 - 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)
499 - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238)
500 - 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));
501 - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1));
502 - 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));
503 - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton().
504 - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize.
505 - 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.
506 - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified.
507 - 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().
508 - 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.
509 - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX.
510 - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior.
511 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.
512 the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls:
513 - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937)
514 - 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.
515 As a result, old .ini data may be partially lost (docking and tables information particularly).
516 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.
517 - 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)
518 - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
519 - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
520 - pre-1.87 backends are not supported:
521 - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
522 - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
523 - for more reference:
524 - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
525 - read https://github.com/ocornut/imgui/issues/4921
526 - 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.
527 - 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?
528 - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
529 - 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).
530 - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
531 moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
532 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!
533 - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
534 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.
535 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().
536 in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
537 - May warn: ImGui::Image((void*)MyTextureData, ...);
538 - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
539 - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
540 - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
541 - 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)
542 - 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).
543 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)
544 - 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)
545 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()
546 - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
547 - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
548 - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
549 - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line.
550 - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660)
551 - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
552 - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278)
553 - access those via GetPlatformIO() instead of GetIO().
554 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.
555 - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder:
556 - 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)
557 - new ImageButton() since 1.89 requires an explicit 'const char* str_id'
558 - old ImageButton() before 1.89 had frame_padding' override argument.
559 - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar().
560 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
561 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
562 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
563 - you can use: GetContentRegionAvail().x
564 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
565 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
566 - instead of: GetContentRegionMax()
567 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
568 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
569 - you can use: GetContentRegionAvail() // when called from left edge of window
570 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
571 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
572 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
573 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
574 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
575 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
576 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
577 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
578 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
579 - 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.
580 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
581 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
582 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
583 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
584 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
585 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
586 - 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.
587 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
588 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
589 - old: CaptureKeyboardFromApp(bool)
590 - new: SetNextFrameWantCaptureKeyboard(bool)
591 - old: CaptureMouseFromApp(bool)
592 - new: SetNextFrameWantCaptureMouse(bool)
593 - 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).
594 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
595 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
596 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
597 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
598 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
599 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
600 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
601 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
602 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
603 for various reasons those changes makes sense. They are being made because making some of those API public.
604 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.
605 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
606 - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
607 - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
608 - 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.
609 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
610 - 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)
611 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
612 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
613 - 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).
614 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
615 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
616 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.
617 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
618 - 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)
619 - 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)
620 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
621 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
622 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
623 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
624 - 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.
625 - 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.
626 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
627 - 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).
628 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.
629 - 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.
630 - old: BeginChild("Name", size, true)
631 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
632 - old: BeginChild("Name", size, false)
633 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
634 **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'**
635 - 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.
636 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
637 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
638 - 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).
639 - 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)
640 - 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).
641 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
642 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
643 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
644 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
645 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
646 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
647 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
648 - 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
649 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
650 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
651 - 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).
652 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
653 - 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.
654 - 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)
655 - 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.
656 - 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.
657 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
658 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
659 - ListBoxFooter() -> use EndListBox()
660 - 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().
661 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
662 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
663 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
664 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
665 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
666 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
667 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
668 - 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.
669 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
670 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
671 it has been frequently requested by people to use our own. We had an opt-in define which was
672 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
673 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
674 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
675 - 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.
676 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
677 - 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.
678 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
679 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
680 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
681 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
682 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
683 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
684 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
685 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.
686 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
687 this will require uses of legacy backend-dependent indices to be casted, e.g.
688 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
689 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
690 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
691 - 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);
692 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
693 - 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.
694 - 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.
695 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
696 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
697 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
698 - previously this would make the window content size ~200x200:
699 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
700 - instead, please submit an item:
701 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
702 - alternative:
703 Begin(...) + Dummy(ImVec2(200,200)) + End();
704 - content size is now only extended when submitting an item!
705 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
706 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
707 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
708 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
709 - 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));
710 - 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.
711 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
712 - 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));
713 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
714 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
715 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
716 - Official backends from 1.87+ -> no issue.
717 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
718 - Custom backends not writing to io.NavInputs[] -> no issue.
719 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
720 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
721 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
722 - 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.
723 - 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.
724 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
725 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
726 - 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).
727 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
728 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
729 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
730 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
731 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
732 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
733 read https://github.com/ocornut/imgui/issues/4921 for details.
734 - 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.
735 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
736 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
737 - 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).
738 - 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.*
739 - 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.
740 - 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.
741 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
742 - 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'.
743 - 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)
744 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
745 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
746 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
747 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
748 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
749 - 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
750 - 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.
751 - 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.
752 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
753 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
754 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
755 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
756 - if you are using official backends from the source tree: you have nothing to do.
757 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
758 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
759 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
760 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
761 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
762 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
763 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
764 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
765 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
766 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
767 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
768 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
769 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.
770 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).
771 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
772 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
773 - 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.
774 - 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.
775 - 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'.
776 - 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.
777 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
778 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
779 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
780 - 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.
781 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
782 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
783 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
784 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
785 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
786 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
787 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
788 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
789 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
790 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
791 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
792 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
793 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
794 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
795 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
796 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
797 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
798 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
799 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
800 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
801 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
802 - 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).
803 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
804 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
805 - 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.
806 - 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.
807 - 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!
808 - 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().
809 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
810 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
811 - if you omitted the 'power' parameter (likely!), you are not affected.
812 - 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.
813 - 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.
814 see https://github.com/ocornut/imgui/issues/3361 for all details.
815 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.
816 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
817 - 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.
818 - 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.
819 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
820 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
821 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
822 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
823 - 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.
824 - 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.
825 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
826 - ShowTestWindow() -> use ShowDemoWindow()
827 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
828 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
829 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
830 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
831 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
832 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
833 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
834 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
835 - 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.
836 - 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).
837 - 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.
838 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
839 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
840 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
841 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
842 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
843 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
844 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
845 - ImFont::Glyph -> use ImFontGlyph
846 - 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.
847 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.
848 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).
849 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
850 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
851 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
852 - 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.
853 - 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
854 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.
855 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.
856 Please reach out if you are affected.
857 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
858 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
859 - 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.
860 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
861 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
862 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
863 - 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!
864 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
865 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
866 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
867 - 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.
868 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
869 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
870 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
871 - 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.
872 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
873 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
874 - 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.
875 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
876 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
877 - 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).
878 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
879 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
880 - 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.
881 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
882 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
883 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
884 - 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.).
885 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
886 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
887 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
888 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
889 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
890 - 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.
891 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
892 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.
893 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.
894 - 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",
895 consistent with other functions. Kept redirection functions (will obsolete).
896 - 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.
897 - 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).
898 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
899 - 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.
900 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
901 - 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.
902 - 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.
903 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
904 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
905 - removed Shutdown() function, as DestroyContext() serve this purpose.
906 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
907 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
908 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
909 - 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.
910 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
911 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
912 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
913 - 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.
914 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
915 - 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
916 - 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.
917 - 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.
918 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
919 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
920 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
921 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
922 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
923 - 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.
924 - 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.
925 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.
926 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
927 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
928 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
929 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
930 - 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.
931 - 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.
932 - 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.
933 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
934 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
935 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
936 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
937 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
938 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
939 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
940 - 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).
941 - 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)".
942 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
943 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
944 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
945 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
946 - 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.
947 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
948 - 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.
949 - 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).
950 - 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).
951 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
952 - 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.
953 - 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.
954 - 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))'
955 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
956 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
957 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
958 - 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().
959 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
960 - 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.
961 - 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.
962 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
963 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.
964 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:
965 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); }
966 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.
967 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
968 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
969 - 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).
970 - 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.
971 - 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).
972 - 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)
973 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
974 - 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.
975 - 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.
976 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
977 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
978 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
979 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.
980 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!
981 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
982 - 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.
983 - 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
984 - 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.
985 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
986 - 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.
987 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
988 - 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.
989 - the signature of the io.RenderDrawListsFn handler has changed!
990 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
991 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
992 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
993 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
994 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
995 - 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.
996 - 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!
997 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
998 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
999 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
1000 - 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.
1001 - 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
1002 - 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!
1003 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
1004 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
1005 - 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.
1006 - 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.
1007 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
1008 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
1009 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
1010 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
1011 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
1012 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
1013 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
1014 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
1015 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
1016 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
1017 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
1018 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
1019 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
1020 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
1021 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
1022 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
1023 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
1024 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
1025 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
1026 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
1027 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.
1028 - 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()
1029 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
1030 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
1031 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
1032 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
1033 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
1034 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
1035 - 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)
1036 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
1037 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
1038 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
1039 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
1040 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
1041 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
1042
1043
1044 FREQUENTLY ASKED QUESTIONS (FAQ)
1045 ================================
1046
1047 Read all answers online:
1048 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
1049 Read all answers locally (with a text editor or ideally a Markdown viewer):
1050 docs/FAQ.md
1051 Some answers are copied down here to facilitate searching in code.
1052
1053 Q&A: Basics
1054 ===========
1055
1056 Q: Where is the documentation?
1057 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
1058 - Run the examples/ applications and explore them.
1059 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
1060 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
1061 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
1062 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
1063 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
1064 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
1065 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
1066 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
1067 - Your programming IDE is your friend, find the type or function declaration to find comments
1068 associated with it.
1069
1070 Q: What is this library called?
1071 Q: Which version should I get?
1072 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
1073 >> See https://www.dearimgui.com/faq for details.
1074
1075 Q&A: Integration
1076 ================
1077
1078 Q: How to get started?
1079 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
1080
1081 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
1082 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
1083 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
1084
1085 Q. How can I enable keyboard or gamepad controls?
1086 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
1087 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
1088 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
1089 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
1090 >> See https://www.dearimgui.com/faq
1091
1092 Q&A: Usage
1093 ----------
1094
1095 Q: About the ID Stack system..
1096 - Why is my widget not reacting when I click on it?
1097 - How can I have widgets with an empty label?
1098 - How can I have multiple widgets with the same label?
1099 - How can I have multiple windows with the same label?
1100 Q: How can I display an image? What is ImTextureID, how does it work?
1101 Q: How can I use my own math types instead of ImVec2?
1102 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
1103 Q: How can I display custom shapes? (using low-level ImDrawList API)
1104 >> See https://www.dearimgui.com/faq
1105
1106 Q&A: Fonts, Text
1107 ================
1108
1109 Q: How should I handle DPI in my application?
1110 Q: How can I load a different font than the default?
1111 Q: How can I easily use icons in my application?
1112 Q: How can I load multiple fonts?
1113 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
1114 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
1115
1116 Q&A: Concerns
1117 =============
1118
1119 Q: Who uses Dear ImGui?
1120 Q: Can you create elaborate/serious tools with Dear ImGui?
1121 Q: Can you reskin the look of Dear ImGui?
1122 Q: Why using C++ (as opposed to C)?
1123 >> See https://www.dearimgui.com/faq
1124
1125 Q&A: Community
1126 ==============
1127
1128 Q: How can I help?
1129 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1130 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1131 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1132 >>> See https://github.com/ocornut/imgui/wiki/Funding
1133 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1134 - 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!
1135 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1136 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1137 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1138 - 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).
1139
1140*/
1141
1142//-------------------------------------------------------------------------
1143// [SECTION] INCLUDES
1144//-------------------------------------------------------------------------
1145
1146#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1147#define _CRT_SECURE_NO_WARNINGS
1148#endif
1149
1150#ifndef IMGUI_DEFINE_MATH_OPERATORS
1151#define IMGUI_DEFINE_MATH_OPERATORS
1152#endif
1153
1154#include "imgui.h"
1155#ifndef IMGUI_DISABLE
1156#include "imgui_internal.h"
1157
1158// System includes
1159#include <stdio.h> // vsnprintf, sscanf, printf
1160#include <stdint.h> // intptr_t
1161
1162// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1163#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1164#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1165#endif
1166
1167// [Windows] OS specific includes (optional)
1168#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)
1169#define IMGUI_DISABLE_WIN32_FUNCTIONS
1170#endif
1171#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1172#ifndef WIN32_LEAN_AND_MEAN
1173#define WIN32_LEAN_AND_MEAN
1174#endif
1175#ifndef NOMINMAX
1176#define NOMINMAX
1177#endif
1178#ifndef __MINGW32__
1179#include <Windows.h> // _wfopen, OpenClipboard
1180#else
1181#include <windows.h>
1182#endif
1183#if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
1184// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1185#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1186#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1187#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1188#endif
1189#endif
1190
1191// [Apple] OS specific includes
1192#if defined(__APPLE__)
1193#include <TargetConditionals.h>
1194#endif
1195
1196// Visual Studio warnings
1197#ifdef _MSC_VER
1198#pragma warning (disable: 4127) // condition expression is constant
1199#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1200#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1201#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1202#endif
1203#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).
1204#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1205#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1206#endif
1207
1208// Clang/GCC warnings with -Weverything
1209#if defined(__clang__)
1210#if __has_warning("-Wunknown-warning-option")
1211#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!
1212#endif
1213#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1214#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1215#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.
1216#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int'
1217#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.
1218#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.
1219#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.
1220#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1221#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1222#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1223#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1224#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.
1225#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1226#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1227#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
1228#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
1229#elif defined(__GNUC__)
1230// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1231#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1232#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1233#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1234#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
1235#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
1236#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1237#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1238#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1239#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1240#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
1241#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
1242#endif
1243
1244// Debug options
1245#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.
1246#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1247
1248// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls.
1249static const float FONT_DEFAULT_SIZE = 20.0f;
1250
1251// 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.
1252static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1253static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1254static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1255static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1256static 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.
1257
1258// Tooltip offset
1259static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1260static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale
1261static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale
1262
1263// Docking
1264static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1265
1266//-------------------------------------------------------------------------
1267// [SECTION] FORWARD DECLARATIONS
1268//-------------------------------------------------------------------------
1269
1270static void SetCurrentWindow(ImGuiWindow* window);
1271static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1272static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1273
1274static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1275
1276// Settings
1277static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1278static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1279static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1280static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1281static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1282
1283// Platform Dependents default implementation for ImGuiPlatformIO functions
1284static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx);
1285static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text);
1286static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1287static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1288
1289namespace ImGui
1290{
1291// Item
1292static void ItemHandleShortcut(ImGuiID id);
1293
1294// Window Focus
1295static int FindWindowFocusIndex(ImGuiWindow* window);
1296static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags);
1297
1298// Navigation
1299static void NavUpdate();
1300static void NavUpdateWindowing();
1301static void NavUpdateWindowingApplyFocus(ImGuiWindow* window);
1302static void NavUpdateWindowingOverlay();
1303static void NavUpdateCancelRequest();
1304static void NavUpdateCreateMoveRequest();
1305static void NavUpdateCreateTabbingRequest();
1306static float NavUpdatePageUpPageDown();
1307static inline void NavUpdateAnyRequestFlag();
1308static void NavUpdateCreateWrappingRequest();
1309static void NavEndFrame();
1310static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb);
1311static void NavApplyItemToResult(ImGuiNavItemData* result);
1312static void NavProcessItem();
1313static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1314static ImGuiInputSource NavCalcPreferredRefPosSource();
1315static ImVec2 NavCalcPreferredRefPos();
1316static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1317static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1318static void NavRestoreLayer(ImGuiNavLayer layer);
1319
1320// Error Checking and Debug Tools
1321static void ErrorCheckNewFrameSanityChecks();
1322static void ErrorCheckEndFrameSanityChecks();
1323#ifndef IMGUI_DISABLE_DEBUG_TOOLS
1324static void UpdateDebugToolItemPicker();
1325static void UpdateDebugToolStackQueries();
1326static void UpdateDebugToolFlashStyleColor();
1327#endif
1328
1329// Inputs
1330static void UpdateKeyboardInputs();
1331static void UpdateMouseInputs();
1332static void UpdateMouseWheel();
1333static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1334
1335// Misc
1336static void UpdateFontsNewFrame();
1337static void UpdateFontsEndFrame();
1338static void UpdateTexturesNewFrame();
1339static void UpdateTexturesEndFrame();
1340static void UpdateSettings();
1341static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1342static void RenderWindowOuterBorders(ImGuiWindow* window);
1343static 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);
1344static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1345static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1346static void RenderDimmedBackgrounds();
1347static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1348static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect);
1349
1350// Viewports
1351const 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.
1352static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1353static void DestroyViewport(ImGuiViewportP* viewport);
1354static void UpdateViewportsNewFrame();
1355static void UpdateViewportsEndFrame();
1356static void WindowSelectViewport(ImGuiWindow* window);
1357static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1358static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1359static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1360static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1361static int FindPlatformMonitorForPos(const ImVec2& pos);
1362static int FindPlatformMonitorForRect(const ImRect& r);
1363static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1364
1365}
1366
1367//-----------------------------------------------------------------------------
1368// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1369//-----------------------------------------------------------------------------
1370
1371// DLL users:
1372// - Heaps and globals are not shared across DLL boundaries!
1373// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1374// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1375// - 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.
1376// - 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).
1377
1378// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1379// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1380// Change to a different context by calling ImGui::SetCurrentContext().
1381// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1382// If you want thread-safety to allow N threads to access N different contexts:
1383// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1384// struct ImGuiContext;
1385// extern thread_local ImGuiContext* MyImGuiTLS;
1386// #define GImGui MyImGuiTLS
1387// 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.
1388// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1389// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1390// - DLL users: read comments above.
1391#ifndef GImGui
1392ImGuiContext* GImGui = NULL;
1393#endif
1394
1395// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1396// - 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.
1397// - DLL users: read comments above.
1398#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1399static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size: size); }
1400static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr: ptr); }
1401#else
1402static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1403static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1404#endif
1405static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1406static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1407static void* GImAllocatorUserData = NULL;
1408
1409//-----------------------------------------------------------------------------
1410// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
1411//-----------------------------------------------------------------------------
1412
1413ImGuiStyle::ImGuiStyle()
1414{
1415 FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame.
1416 FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user.
1417 FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
1418
1419 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1420 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1421 WindowPadding = ImVec2(8,8); // Padding within a window
1422 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.
1423 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1424 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.
1425 WindowMinSize = ImVec2(32,32); // Minimum window size
1426 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1427 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1428 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1429 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1430 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1431 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1432 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1433 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1434 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1435 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1436 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1437 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1438 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!
1439 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1440 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1441 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1442 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1443 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1444 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1445 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1446 ImageBorderSize = 0.0f; // Thickness of border around tabs.
1447 TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1448 TabBorderSize = 0.0f; // Thickness of border around tabs.
1449 TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
1450 TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy.
1451 TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
1452 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.
1453 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1454 TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1455 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1456 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1457 TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone;
1458 TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
1459 TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line.
1460 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1461 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1462 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.
1463 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText()
1464 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1465 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.
1466 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.
1467 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.
1468 DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
1469 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1470 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1471 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1472 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1473 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.
1474 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.
1475
1476 // Behaviors
1477 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1478 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1479 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1480 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1481 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1482
1483 // [Internal]
1484 _MainScale = 1.0f;
1485 _NextFrameFontSizeBase = 0.0f;
1486
1487 // Default theme
1488 ImGui::StyleColorsDark(dst: this);
1489}
1490
1491
1492// Scale all spacing/padding/thickness values. Do not scale fonts.
1493// 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.
1494void ImGuiStyle::ScaleAllSizes(float scale_factor)
1495{
1496 _MainScale *= scale_factor;
1497 WindowPadding = ImTrunc(v: WindowPadding * scale_factor);
1498 WindowRounding = ImTrunc(f: WindowRounding * scale_factor);
1499 WindowMinSize = ImTrunc(v: WindowMinSize * scale_factor);
1500 WindowBorderHoverPadding = ImTrunc(f: WindowBorderHoverPadding * scale_factor);
1501 ChildRounding = ImTrunc(f: ChildRounding * scale_factor);
1502 PopupRounding = ImTrunc(f: PopupRounding * scale_factor);
1503 FramePadding = ImTrunc(v: FramePadding * scale_factor);
1504 FrameRounding = ImTrunc(f: FrameRounding * scale_factor);
1505 ItemSpacing = ImTrunc(v: ItemSpacing * scale_factor);
1506 ItemInnerSpacing = ImTrunc(v: ItemInnerSpacing * scale_factor);
1507 CellPadding = ImTrunc(v: CellPadding * scale_factor);
1508 TouchExtraPadding = ImTrunc(v: TouchExtraPadding * scale_factor);
1509 IndentSpacing = ImTrunc(f: IndentSpacing * scale_factor);
1510 ColumnsMinSpacing = ImTrunc(f: ColumnsMinSpacing * scale_factor);
1511 ScrollbarSize = ImTrunc(f: ScrollbarSize * scale_factor);
1512 ScrollbarRounding = ImTrunc(f: ScrollbarRounding * scale_factor);
1513 GrabMinSize = ImTrunc(f: GrabMinSize * scale_factor);
1514 GrabRounding = ImTrunc(f: GrabRounding * scale_factor);
1515 LogSliderDeadzone = ImTrunc(f: LogSliderDeadzone * scale_factor);
1516 ImageBorderSize = ImTrunc(f: ImageBorderSize * scale_factor);
1517 TabRounding = ImTrunc(f: TabRounding * scale_factor);
1518 TabMinWidthBase = ImTrunc(f: TabMinWidthBase * scale_factor);
1519 TabMinWidthShrink = ImTrunc(f: TabMinWidthShrink * scale_factor);
1520 TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(f: TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected;
1521 TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(f: TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected;
1522 TabBarOverlineSize = ImTrunc(f: TabBarOverlineSize * scale_factor);
1523 TreeLinesRounding = ImTrunc(f: TreeLinesRounding * scale_factor);
1524 SeparatorTextPadding = ImTrunc(v: SeparatorTextPadding * scale_factor);
1525 DockingSeparatorSize = ImTrunc(f: DockingSeparatorSize * scale_factor);
1526 DisplayWindowPadding = ImTrunc(v: DisplayWindowPadding * scale_factor);
1527 DisplaySafeAreaPadding = ImTrunc(v: DisplaySafeAreaPadding * scale_factor);
1528 MouseCursorScale = ImTrunc(f: MouseCursorScale * scale_factor);
1529}
1530
1531ImGuiIO::ImGuiIO()
1532{
1533 // Most fields are initialized with zero
1534 memset(s: this, c: 0, n: sizeof(*this));
1535 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1536
1537 // Settings
1538 ConfigFlags = ImGuiConfigFlags_None;
1539 BackendFlags = ImGuiBackendFlags_None;
1540 DisplaySize = ImVec2(-1.0f, -1.0f);
1541 DeltaTime = 1.0f / 60.0f;
1542 IniSavingRate = 5.0f;
1543 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).
1544 LogFilename = "imgui_log.txt";
1545 UserData = NULL;
1546
1547 Fonts = NULL;
1548 FontDefault = NULL;
1549 FontAllowUserScaling = false;
1550#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1551 FontGlobalScale = 1.0f; // Use style.FontScaleMain instead!
1552#endif
1553 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1554
1555 // Keyboard/Gamepad Navigation options
1556 ConfigNavSwapGamepadButtons = false;
1557 ConfigNavMoveSetMousePos = false;
1558 ConfigNavCaptureKeyboard = true;
1559 ConfigNavEscapeClearFocusItem = true;
1560 ConfigNavEscapeClearFocusWindow = false;
1561 ConfigNavCursorVisibleAuto = true;
1562 ConfigNavCursorVisibleAlways = false;
1563
1564 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1565 ConfigDockingNoSplit = false;
1566 ConfigDockingWithShift = false;
1567 ConfigDockingAlwaysTabBar = false;
1568 ConfigDockingTransparentPayload = false;
1569
1570 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1571 ConfigViewportsNoAutoMerge = false;
1572 ConfigViewportsNoTaskBarIcon = false;
1573 ConfigViewportsNoDecoration = true;
1574 ConfigViewportsNoDefaultParent = false;
1575 ConfigViewportPlatformFocusSetsImGuiFocus = true;
1576
1577 // Miscellaneous options
1578 MouseDrawCursor = false;
1579#ifdef __APPLE__
1580 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1581#else
1582 ConfigMacOSXBehaviors = false;
1583#endif
1584 ConfigInputTrickleEventQueue = true;
1585 ConfigInputTextCursorBlink = true;
1586 ConfigInputTextEnterKeepActive = false;
1587 ConfigDragClickToInputText = false;
1588 ConfigWindowsResizeFromEdges = true;
1589 ConfigWindowsMoveFromTitleBarOnly = false;
1590 ConfigWindowsCopyContentsWithCtrlC = false;
1591 ConfigScrollbarScrollByPage = true;
1592 ConfigMemoryCompactTimer = 60.0f;
1593 ConfigDebugIsDebuggerPresent = false;
1594 ConfigDebugHighlightIdConflicts = true;
1595 ConfigDebugHighlightIdConflictsShowItemPicker = true;
1596 ConfigDebugBeginReturnValueOnce = false;
1597 ConfigDebugBeginReturnValueLoop = false;
1598
1599 ConfigErrorRecovery = true;
1600 ConfigErrorRecoveryEnableAssert = true;
1601 ConfigErrorRecoveryEnableDebugLog = true;
1602 ConfigErrorRecoveryEnableTooltip = true;
1603
1604 // Inputs Behaviors
1605 MouseDoubleClickTime = 0.30f;
1606 MouseDoubleClickMaxDist = 6.0f;
1607 MouseDragThreshold = 6.0f;
1608 KeyRepeatDelay = 0.275f;
1609 KeyRepeatRate = 0.050f;
1610
1611 // Platform Functions
1612 // Note: Initialize() will setup default clipboard/ime handlers.
1613 BackendPlatformName = BackendRendererName = NULL;
1614 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1615
1616 // Input (NB: we already have memset zero the entire structure!)
1617 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1618 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1619 MouseSource = ImGuiMouseSource_Mouse;
1620 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1621 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1622 AppAcceptingEvents = true;
1623}
1624
1625// Pass in translated ASCII characters for text input.
1626// - with glfw you can get those from the callback set in glfwSetCharCallback()
1627// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1628// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1629void ImGuiIO::AddInputCharacter(unsigned int c)
1630{
1631 IM_ASSERT(Ctx != NULL);
1632 ImGuiContext& g = *Ctx;
1633 if (c == 0 || !AppAcceptingEvents)
1634 return;
1635
1636 ImGuiInputEvent e;
1637 e.Type = ImGuiInputEventType_Text;
1638 e.Source = ImGuiInputSource_Keyboard;
1639 e.EventId = g.InputEventsNextEventId++;
1640 e.Text.Char = c;
1641 g.InputEventsQueue.push_back(v: e);
1642}
1643
1644// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1645// we should save the high surrogate.
1646void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1647{
1648 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1649 return;
1650
1651 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1652 {
1653 if (InputQueueSurrogate != 0)
1654 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1655 InputQueueSurrogate = c;
1656 return;
1657 }
1658
1659 ImWchar cp = c;
1660 if (InputQueueSurrogate != 0)
1661 {
1662 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1663 {
1664 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1665 }
1666 else
1667 {
1668#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1669 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1670#else
1671 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1672#endif
1673 }
1674
1675 InputQueueSurrogate = 0;
1676 }
1677 AddInputCharacter(c: (unsigned)cp);
1678}
1679
1680void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1681{
1682 if (!AppAcceptingEvents)
1683 return;
1684 while (*utf8_chars != 0)
1685 {
1686 unsigned int c = 0;
1687 utf8_chars += ImTextCharFromUtf8(out_char: &c, in_text: utf8_chars, NULL);
1688 AddInputCharacter(c);
1689 }
1690}
1691
1692// Clear all incoming events.
1693void ImGuiIO::ClearEventsQueue()
1694{
1695 IM_ASSERT(Ctx != NULL);
1696 ImGuiContext& g = *Ctx;
1697 g.InputEventsQueue.clear();
1698}
1699
1700// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1701void ImGuiIO::ClearInputKeys()
1702{
1703 ImGuiContext& g = *Ctx;
1704 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
1705 {
1706 if (ImGui::IsMouseKey(key: (ImGuiKey)key))
1707 continue;
1708 ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
1709 key_data->Down = false;
1710 key_data->DownDuration = -1.0f;
1711 key_data->DownDurationPrev = -1.0f;
1712 }
1713 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1714 KeyMods = ImGuiMod_None;
1715 InputQueueCharacters.resize(new_size: 0); // Behavior of old ClearInputCharacters().
1716}
1717
1718void ImGuiIO::ClearInputMouse()
1719{
1720 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1721 {
1722 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
1723 key_data->Down = false;
1724 key_data->DownDuration = -1.0f;
1725 key_data->DownDurationPrev = -1.0f;
1726 }
1727 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1728 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1729 {
1730 MouseDown[n] = false;
1731 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1732 }
1733 MouseWheel = MouseWheelH = 0.0f;
1734}
1735
1736// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1737// Current frame character buffer is now also cleared by ClearInputKeys().
1738#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1739void ImGuiIO::ClearInputCharacters()
1740{
1741 InputQueueCharacters.resize(new_size: 0);
1742}
1743#endif
1744
1745static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1746{
1747 ImGuiContext& g = *ctx;
1748 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1749 {
1750 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1751 if (e->Type != type)
1752 continue;
1753 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1754 continue;
1755 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1756 continue;
1757 return e;
1758 }
1759 return NULL;
1760}
1761
1762// Queue a new key down/up event.
1763// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1764// - bool down: Is the key down? use false to signify a key release.
1765// - float analog_value: 0.0f..1.0f
1766// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1767// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1768void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1769{
1770 //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); }
1771 IM_ASSERT(Ctx != NULL);
1772 if (key == ImGuiKey_None || !AppAcceptingEvents)
1773 return;
1774 ImGuiContext& g = *Ctx;
1775 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.
1776 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1777
1778 // MacOS: swap Cmd(Super) and Ctrl
1779 if (g.IO.ConfigMacOSXBehaviors)
1780 {
1781 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1782 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1783 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1784 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1785 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1786 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1787 }
1788
1789 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1790 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)key);
1791 const ImGuiKeyData* key_data = ImGui::GetKeyData(ctx: &g, key);
1792 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1793 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1794 if (latest_key_down == down && latest_key_analog == analog_value)
1795 return;
1796
1797 // Add event
1798 ImGuiInputEvent e;
1799 e.Type = ImGuiInputEventType_Key;
1800 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1801 e.EventId = g.InputEventsNextEventId++;
1802 e.Key.Key = key;
1803 e.Key.Down = down;
1804 e.Key.AnalogValue = analog_value;
1805 g.InputEventsQueue.push_back(v: e);
1806}
1807
1808void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1809{
1810 if (!AppAcceptingEvents)
1811 return;
1812 AddKeyAnalogEvent(key, down, analog_value: down ? 1.0f : 0.0f);
1813}
1814
1815// [Optional] Call after AddKeyEvent().
1816// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1817// 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.
1818void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1819{
1820 if (key == ImGuiKey_None)
1821 return;
1822 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1823 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1824 IM_UNUSED(key); // Yet unused
1825 IM_UNUSED(native_keycode); // Yet unused
1826 IM_UNUSED(native_scancode); // Yet unused
1827 IM_UNUSED(native_legacy_index); // Yet unused
1828}
1829
1830// 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.
1831void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1832{
1833 AppAcceptingEvents = accepting_events;
1834}
1835
1836// Queue a mouse move event
1837void ImGuiIO::AddMousePosEvent(float x, float y)
1838{
1839 IM_ASSERT(Ctx != NULL);
1840 ImGuiContext& g = *Ctx;
1841 if (!AppAcceptingEvents)
1842 return;
1843
1844 // Apply same flooring as UpdateMouseInputs()
1845 ImVec2 pos((x > -FLT_MAX) ? ImFloor(f: x) : x, (y > -FLT_MAX) ? ImFloor(f: y) : y);
1846
1847 // Filter duplicate
1848 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MousePos);
1849 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1850 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1851 return;
1852
1853 ImGuiInputEvent e;
1854 e.Type = ImGuiInputEventType_MousePos;
1855 e.Source = ImGuiInputSource_Mouse;
1856 e.EventId = g.InputEventsNextEventId++;
1857 e.MousePos.PosX = pos.x;
1858 e.MousePos.PosY = pos.y;
1859 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1860 g.InputEventsQueue.push_back(v: e);
1861}
1862
1863void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1864{
1865 IM_ASSERT(Ctx != NULL);
1866 ImGuiContext& g = *Ctx;
1867 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1868 if (!AppAcceptingEvents)
1869 return;
1870
1871 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1872 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1873 {
1874 // Order of both statements matters: this event will still release mouse button 1
1875 mouse_button = 1;
1876 if (!down)
1877 MouseCtrlLeftAsRightClick = false;
1878 }
1879
1880 // Filter duplicate
1881 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseButton, arg: (int)mouse_button);
1882 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1883 if (latest_button_down == down)
1884 return;
1885
1886 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1887 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1888 // - At this point we want from !down to down, so this is handling the initial press.
1889 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1890 {
1891 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)ImGuiMod_Super);
1892 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1893 {
1894 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1895 MouseCtrlLeftAsRightClick = true;
1896 AddMouseButtonEvent(mouse_button: 1, down: true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1897 return;
1898 }
1899 }
1900
1901 ImGuiInputEvent e;
1902 e.Type = ImGuiInputEventType_MouseButton;
1903 e.Source = ImGuiInputSource_Mouse;
1904 e.EventId = g.InputEventsNextEventId++;
1905 e.MouseButton.Button = mouse_button;
1906 e.MouseButton.Down = down;
1907 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1908 g.InputEventsQueue.push_back(v: e);
1909}
1910
1911// Queue a mouse wheel event (some mouse/API may only have a Y component)
1912void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1913{
1914 IM_ASSERT(Ctx != NULL);
1915 ImGuiContext& g = *Ctx;
1916
1917 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1918 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1919 return;
1920
1921 ImGuiInputEvent e;
1922 e.Type = ImGuiInputEventType_MouseWheel;
1923 e.Source = ImGuiInputSource_Mouse;
1924 e.EventId = g.InputEventsNextEventId++;
1925 e.MouseWheel.WheelX = wheel_x;
1926 e.MouseWheel.WheelY = wheel_y;
1927 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1928 g.InputEventsQueue.push_back(v: e);
1929}
1930
1931// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1932// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1933void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1934{
1935 IM_ASSERT(Ctx != NULL);
1936 ImGuiContext& g = *Ctx;
1937 g.InputEventsNextMouseSource = source;
1938}
1939
1940void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1941{
1942 IM_ASSERT(Ctx != NULL);
1943 ImGuiContext& g = *Ctx;
1944 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1945 if (!AppAcceptingEvents)
1946 return;
1947
1948 // Filter duplicate
1949 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseViewport);
1950 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1951 if (latest_viewport_id == viewport_id)
1952 return;
1953
1954 ImGuiInputEvent e;
1955 e.Type = ImGuiInputEventType_MouseViewport;
1956 e.Source = ImGuiInputSource_Mouse;
1957 e.MouseViewport.HoveredViewportID = viewport_id;
1958 g.InputEventsQueue.push_back(v: e);
1959}
1960
1961void ImGuiIO::AddFocusEvent(bool focused)
1962{
1963 IM_ASSERT(Ctx != NULL);
1964 ImGuiContext& g = *Ctx;
1965
1966 // Filter duplicate
1967 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Focus);
1968 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1969 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1970 return;
1971
1972 ImGuiInputEvent e;
1973 e.Type = ImGuiInputEventType_Focus;
1974 e.EventId = g.InputEventsNextEventId++;
1975 e.AppFocused.Focused = focused;
1976 g.InputEventsQueue.push_back(v: e);
1977}
1978
1979ImGuiPlatformIO::ImGuiPlatformIO()
1980{
1981 // Most fields are initialized with zero
1982 memset(s: this, c: 0, n: sizeof(*this));
1983 Platform_LocaleDecimalPoint = '.';
1984}
1985
1986//-----------------------------------------------------------------------------
1987// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1988//-----------------------------------------------------------------------------
1989
1990ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1991{
1992 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1993 ImVec2 p_last = p1;
1994 ImVec2 p_closest;
1995 float p_closest_dist2 = FLT_MAX;
1996 float t_step = 1.0f / (float)num_segments;
1997 for (int i_step = 1; i_step <= num_segments; i_step++)
1998 {
1999 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t: t_step * i_step);
2000 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
2001 float dist2 = ImLengthSqr(lhs: p - p_line);
2002 if (dist2 < p_closest_dist2)
2003 {
2004 p_closest = p_line;
2005 p_closest_dist2 = dist2;
2006 }
2007 p_last = p_current;
2008 }
2009 return p_closest;
2010}
2011
2012// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
2013static 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)
2014{
2015 float dx = x4 - x1;
2016 float dy = y4 - y1;
2017 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
2018 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
2019 d2 = (d2 >= 0) ? d2 : -d2;
2020 d3 = (d3 >= 0) ? d3 : -d3;
2021 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
2022 {
2023 ImVec2 p_current(x4, y4);
2024 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
2025 float dist2 = ImLengthSqr(lhs: p - p_line);
2026 if (dist2 < p_closest_dist2)
2027 {
2028 p_closest = p_line;
2029 p_closest_dist2 = dist2;
2030 }
2031 p_last = p_current;
2032 }
2033 else if (level < 10)
2034 {
2035 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
2036 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
2037 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
2038 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
2039 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
2040 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
2041 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x2: x12, y2: y12, x3: x123, y3: y123, x4: x1234, y4: y1234, tess_tol, level: level + 1);
2042 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: x1234, y1: y1234, x2: x234, y2: y234, x3: x34, y3: y34, x4, y4, tess_tol, level: level + 1);
2043 }
2044}
2045
2046// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
2047// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
2048ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
2049{
2050 IM_ASSERT(tess_tol > 0.0f);
2051 ImVec2 p_last = p1;
2052 ImVec2 p_closest;
2053 float p_closest_dist2 = FLT_MAX;
2054 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y, x3: p3.x, y3: p3.y, x4: p4.x, y4: p4.y, tess_tol, level: 0);
2055 return p_closest;
2056}
2057
2058ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
2059{
2060 ImVec2 ap = p - a;
2061 ImVec2 ab_dir = b - a;
2062 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
2063 if (dot < 0.0f)
2064 return a;
2065 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
2066 if (dot > ab_len_sqr)
2067 return b;
2068 return a + ab_dir * dot / ab_len_sqr;
2069}
2070
2071bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2072{
2073 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
2074 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
2075 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
2076 return ((b1 == b2) && (b2 == b3));
2077}
2078
2079void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
2080{
2081 ImVec2 v0 = b - a;
2082 ImVec2 v1 = c - a;
2083 ImVec2 v2 = p - a;
2084 const float denom = v0.x * v1.y - v1.x * v0.y;
2085 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
2086 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
2087 out_u = 1.0f - out_v - out_w;
2088}
2089
2090ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2091{
2092 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
2093 ImVec2 proj_bc = ImLineClosestPoint(a: b, b: c, p);
2094 ImVec2 proj_ca = ImLineClosestPoint(a: c, b: a, p);
2095 float dist2_ab = ImLengthSqr(lhs: p - proj_ab);
2096 float dist2_bc = ImLengthSqr(lhs: p - proj_bc);
2097 float dist2_ca = ImLengthSqr(lhs: p - proj_ca);
2098 float m = ImMin(lhs: dist2_ab, rhs: ImMin(lhs: dist2_bc, rhs: dist2_ca));
2099 if (m == dist2_ab)
2100 return proj_ab;
2101 if (m == dist2_bc)
2102 return proj_bc;
2103 return proj_ca;
2104}
2105
2106//-----------------------------------------------------------------------------
2107// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
2108//-----------------------------------------------------------------------------
2109
2110// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
2111int ImStricmp(const char* str1, const char* str2)
2112{
2113 int d;
2114 while ((d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; }
2115 return d;
2116}
2117
2118int ImStrnicmp(const char* str1, const char* str2, size_t count)
2119{
2120 int d = 0;
2121 while (count > 0 && (d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; count--; }
2122 return d;
2123}
2124
2125void ImStrncpy(char* dst, const char* src, size_t count)
2126{
2127 if (count < 1)
2128 return;
2129 if (count > 1)
2130 strncpy(dest: dst, src: src, n: count - 1);
2131 dst[count - 1] = 0;
2132}
2133
2134char* ImStrdup(const char* str)
2135{
2136 size_t len = ImStrlen(s: str);
2137 void* buf = IM_ALLOC(len + 1);
2138 return (char*)memcpy(dest: buf, src: (const void*)str, n: len + 1);
2139}
2140
2141void* ImMemdup(const void* src, size_t size)
2142{
2143 void* dst = IM_ALLOC(size);
2144 return memcpy(dest: dst, src: src, n: size);
2145}
2146
2147char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
2148{
2149 size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(s: dst) + 1;
2150 size_t src_size = ImStrlen(s: src) + 1;
2151 if (dst_buf_size < src_size)
2152 {
2153 IM_FREE(dst);
2154 dst = (char*)IM_ALLOC(src_size);
2155 if (p_dst_size)
2156 *p_dst_size = src_size;
2157 }
2158 return (char*)memcpy(dest: dst, src: (const void*)src, n: src_size);
2159}
2160
2161const char* ImStrchrRange(const char* str, const char* str_end, char c)
2162{
2163 const char* p = (const char*)ImMemchr(s: str, c: (int)c, n: str_end - str);
2164 return p;
2165}
2166
2167int ImStrlenW(const ImWchar* str)
2168{
2169 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
2170 int n = 0;
2171 while (*str++) n++;
2172 return n;
2173}
2174
2175// Find end-of-line. Return pointer will point to either first \n, either str_end.
2176const char* ImStreolRange(const char* str, const char* str_end)
2177{
2178 const char* p = (const char*)ImMemchr(s: str, c: '\n', n: str_end - str);
2179 return p ? p : str_end;
2180}
2181
2182const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
2183{
2184 IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin));
2185 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2186 buf_mid_line--;
2187 return buf_mid_line;
2188}
2189
2190const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2191{
2192 if (!needle_end)
2193 needle_end = needle + ImStrlen(s: needle);
2194
2195 const char un0 = (char)ImToUpper(c: *needle);
2196 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2197 {
2198 if (ImToUpper(c: *haystack) == un0)
2199 {
2200 const char* b = needle + 1;
2201 for (const char* a = haystack + 1; b < needle_end; a++, b++)
2202 if (ImToUpper(c: *a) != ImToUpper(c: *b))
2203 break;
2204 if (b == needle_end)
2205 return haystack;
2206 }
2207 haystack++;
2208 }
2209 return NULL;
2210}
2211
2212// 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.
2213void ImStrTrimBlanks(char* buf)
2214{
2215 char* p = buf;
2216 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
2217 p++;
2218 char* p_start = p;
2219 while (*p != 0) // Find end of string
2220 p++;
2221 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
2222 p--;
2223 if (p_start != buf) // Copy memory if we had leading blanks
2224 memmove(dest: buf, src: p_start, n: p - p_start);
2225 buf[p - p_start] = 0; // Zero terminate
2226}
2227
2228const char* ImStrSkipBlank(const char* str)
2229{
2230 while (str[0] == ' ' || str[0] == '\t')
2231 str++;
2232 return str;
2233}
2234
2235// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2236// 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.
2237// B) When buf==NULL vsnprintf() will return the output size.
2238#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2239
2240// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2241// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2242// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2243// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2244#ifdef IMGUI_USE_STB_SPRINTF
2245#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2246#define STB_SPRINTF_IMPLEMENTATION
2247#endif
2248#ifdef IMGUI_STB_SPRINTF_FILENAME
2249#include IMGUI_STB_SPRINTF_FILENAME
2250#else
2251#include "stb_sprintf.h"
2252#endif
2253#endif // #ifdef IMGUI_USE_STB_SPRINTF
2254
2255#if defined(_MSC_VER) && !defined(vsnprintf)
2256#define vsnprintf _vsnprintf
2257#endif
2258
2259int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2260{
2261 va_list args;
2262 va_start(args, fmt);
2263#ifdef IMGUI_USE_STB_SPRINTF
2264 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2265#else
2266 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
2267#endif
2268 va_end(args);
2269 if (buf == NULL)
2270 return w;
2271 if (w == -1 || w >= (int)buf_size)
2272 w = (int)buf_size - 1;
2273 buf[w] = 0;
2274 return w;
2275}
2276
2277int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2278{
2279#ifdef IMGUI_USE_STB_SPRINTF
2280 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2281#else
2282 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
2283#endif
2284 if (buf == NULL)
2285 return w;
2286 if (w == -1 || w >= (int)buf_size)
2287 w = (int)buf_size - 1;
2288 buf[w] = 0;
2289 return w;
2290}
2291#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2292
2293void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2294{
2295 va_list args;
2296 va_start(args, fmt);
2297 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2298 va_end(args);
2299}
2300
2301// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2302// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2303// ImGuiTempBufferToken token;
2304// ImFormatStringToTempBuffer(token, ...);
2305void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2306{
2307 ImGuiContext& g = *GImGui;
2308 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2309 {
2310 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2311 if (buf == NULL)
2312 buf = "(null)";
2313 *out_buf = buf;
2314 if (out_buf_end) { *out_buf_end = buf + ImStrlen(s: buf); }
2315 }
2316 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2317 {
2318 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2319 const char* buf = va_arg(args, const char*);
2320 if (buf == NULL)
2321 {
2322 buf = "(null)";
2323 buf_len = ImMin(lhs: buf_len, rhs: 6);
2324 }
2325 *out_buf = buf;
2326 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2327 }
2328 else
2329 {
2330 int buf_len = ImFormatStringV(buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size, fmt, args);
2331 *out_buf = g.TempBuffer.Data;
2332 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2333 }
2334}
2335
2336#ifndef IMGUI_ENABLE_SSE4_2_CRC
2337// CRC32 needs a 1KB lookup table (not cache friendly)
2338// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2339// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2340static const ImU32 GCrc32LookupTable[256] =
2341{
2342#ifdef IMGUI_USE_LEGACY_CRC32_ADLER
2343 // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
2344 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2345 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2346 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2347 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2348 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2349 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2350 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2351 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2352 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2353 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2354 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2355 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2356 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2357 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2358 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2359 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2360#else
2361 // CRC32c table compatible with SSE 4.2 instructions
2362 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
2363 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
2364 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
2365 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
2366 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
2367 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
2368 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
2369 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
2370 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
2371 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
2372 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
2373 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
2374 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
2375 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
2376 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
2377 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
2378#endif
2379};
2380#endif
2381
2382// Known size hash
2383// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2384// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2385ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2386{
2387 ImU32 crc = ~seed;
2388 const unsigned char* data = (const unsigned char*)data_p;
2389 const unsigned char *data_end = (const unsigned char*)data_p + data_size;
2390#ifndef IMGUI_ENABLE_SSE4_2_CRC
2391 const ImU32* crc32_lut = GCrc32LookupTable;
2392 while (data < data_end)
2393 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2394 return ~crc;
2395#else
2396 while (data + 4 <= data_end)
2397 {
2398 crc = _mm_crc32_u32(crc, *(ImU32*)data);
2399 data += 4;
2400 }
2401 while (data < data_end)
2402 crc = _mm_crc32_u8(crc, *data++);
2403 return ~crc;
2404#endif
2405}
2406
2407// Zero-terminated string hash, with support for ### to reset back to seed value
2408// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2409// Because this syntax is rarely used we are optimizing for the common case.
2410// - If we reach ### in the string we discard the hash so far and reset to the seed.
2411// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2412// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2413ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2414{
2415 seed = ~seed;
2416 ImU32 crc = seed;
2417 const unsigned char* data = (const unsigned char*)data_p;
2418#ifndef IMGUI_ENABLE_SSE4_2_CRC
2419 const ImU32* crc32_lut = GCrc32LookupTable;
2420#endif
2421 if (data_size != 0)
2422 {
2423 while (data_size-- != 0)
2424 {
2425 unsigned char c = *data++;
2426 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2427 crc = seed;
2428#ifndef IMGUI_ENABLE_SSE4_2_CRC
2429 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2430#else
2431 crc = _mm_crc32_u8(crc, c);
2432#endif
2433 }
2434 }
2435 else
2436 {
2437 while (unsigned char c = *data++)
2438 {
2439 if (c == '#' && data[0] == '#' && data[1] == '#')
2440 crc = seed;
2441#ifndef IMGUI_ENABLE_SSE4_2_CRC
2442 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2443#else
2444 crc = _mm_crc32_u8(crc, c);
2445#endif
2446 }
2447 }
2448 return ~crc;
2449}
2450
2451//-----------------------------------------------------------------------------
2452// [SECTION] MISC HELPERS/UTILITIES (File functions)
2453//-----------------------------------------------------------------------------
2454
2455// Default file functions
2456#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2457
2458ImFileHandle ImFileOpen(const char* filename, const char* mode)
2459{
2460#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__)))
2461 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2462 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2463 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2464 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2465
2466 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2467 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2468 wchar_t local_temp_stack[FILENAME_MAX];
2469 ImVector<wchar_t> local_temp_heap;
2470 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2471 local_temp_heap.resize(filename_wsize + mode_wsize);
2472 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2473 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2474 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2475 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2476 return ::_wfopen(filename_wbuf, mode_wbuf);
2477#else
2478 return fopen(filename: filename, modes: mode);
2479#endif
2480}
2481
2482// 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.
2483bool ImFileClose(ImFileHandle f) { return fclose(stream: f) == 0; }
2484ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(stream: f)) != -1 && !fseek(stream: f, off: 0, SEEK_END) && (sz = ftell(stream: f)) != -1 && !fseek(stream: f, off: off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2485ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(ptr: data, size: (size_t)sz, n: (size_t)count, stream: f); }
2486ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(ptr: data, size: (size_t)sz, n: (size_t)count, s: f); }
2487#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2488
2489// Helper: Load file content into memory
2490// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2491// This can't really be used with "rt" because fseek size won't match read size.
2492void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2493{
2494 IM_ASSERT(filename && mode);
2495 if (out_file_size)
2496 *out_file_size = 0;
2497
2498 ImFileHandle f;
2499 if ((f = ImFileOpen(filename, mode)) == NULL)
2500 return NULL;
2501
2502 size_t file_size = (size_t)ImFileGetSize(f);
2503 if (file_size == (size_t)-1)
2504 {
2505 ImFileClose(f);
2506 return NULL;
2507 }
2508
2509 void* file_data = IM_ALLOC(file_size + padding_bytes);
2510 if (file_data == NULL)
2511 {
2512 ImFileClose(f);
2513 return NULL;
2514 }
2515 if (ImFileRead(data: file_data, sz: 1, count: file_size, f) != file_size)
2516 {
2517 ImFileClose(f);
2518 IM_FREE(file_data);
2519 return NULL;
2520 }
2521 if (padding_bytes > 0)
2522 memset(s: (void*)(((char*)file_data) + file_size), c: 0, n: (size_t)padding_bytes);
2523
2524 ImFileClose(f);
2525 if (out_file_size)
2526 *out_file_size = file_size;
2527
2528 return file_data;
2529}
2530
2531//-----------------------------------------------------------------------------
2532// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2533//-----------------------------------------------------------------------------
2534
2535IM_MSVC_RUNTIME_CHECKS_OFF
2536
2537// Convert UTF-8 to 32-bit character, process single character input.
2538// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2539// We handle UTF-8 decoding error by skipping forward.
2540int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2541{
2542 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 };
2543 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2544 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2545 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2546 static const int shifte[] = { 0, 6, 4, 2, 0 };
2547 int len = lengths[*(const unsigned char*)in_text >> 3];
2548 int wanted = len + (len ? 0 : 1);
2549
2550 if (in_text_end == NULL)
2551 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2552
2553 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2554 // so it is fast even with excessive branching.
2555 unsigned char s[4];
2556 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2557 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2558 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2559 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2560
2561 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2562 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2563 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2564 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2565 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2566 *out_char >>= shiftc[len];
2567
2568 // Accumulate the various error conditions.
2569 int e = 0;
2570 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2571 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2572 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve)
2573 e |= (s[1] & 0xc0) >> 2;
2574 e |= (s[2] & 0xc0) >> 4;
2575 e |= (s[3] ) >> 6;
2576 e ^= 0x2a; // top two bits of each tail byte correct?
2577 e >>= shifte[len];
2578
2579 if (e)
2580 {
2581 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2582 // One byte is consumed in case of invalid first byte of in_text.
2583 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2584 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2585 wanted = ImMin(lhs: wanted, rhs: !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2586 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2587 }
2588
2589 return wanted;
2590}
2591
2592int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2593{
2594 ImWchar* buf_out = buf;
2595 ImWchar* buf_end = buf + buf_size;
2596 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2597 {
2598 unsigned int c;
2599 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2600 *buf_out++ = (ImWchar)c;
2601 }
2602 *buf_out = 0;
2603 if (in_text_remaining)
2604 *in_text_remaining = in_text;
2605 return (int)(buf_out - buf);
2606}
2607
2608int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2609{
2610 int char_count = 0;
2611 while ((!in_text_end || in_text < in_text_end) && *in_text)
2612 {
2613 unsigned int c;
2614 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2615 char_count++;
2616 }
2617 return char_count;
2618}
2619
2620// Based on stb_to_utf8() from github.com/nothings/stb/
2621static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2622{
2623 if (c < 0x80)
2624 {
2625 buf[0] = (char)c;
2626 return 1;
2627 }
2628 if (c < 0x800)
2629 {
2630 if (buf_size < 2) return 0;
2631 buf[0] = (char)(0xc0 + (c >> 6));
2632 buf[1] = (char)(0x80 + (c & 0x3f));
2633 return 2;
2634 }
2635 if (c < 0x10000)
2636 {
2637 if (buf_size < 3) return 0;
2638 buf[0] = (char)(0xe0 + (c >> 12));
2639 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2640 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2641 return 3;
2642 }
2643 if (c <= 0x10FFFF)
2644 {
2645 if (buf_size < 4) return 0;
2646 buf[0] = (char)(0xf0 + (c >> 18));
2647 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2648 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2649 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2650 return 4;
2651 }
2652 // Invalid code point, the max unicode is 0x10FFFF
2653 return 0;
2654}
2655
2656int ImTextCharToUtf8(char out_buf[5], unsigned int c)
2657{
2658 int count = ImTextCharToUtf8_inline(buf: out_buf, buf_size: 5, c);
2659 out_buf[count] = 0;
2660 return count;
2661}
2662
2663// Not optimal but we very rarely use this function.
2664int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2665{
2666 unsigned int unused = 0;
2667 return ImTextCharFromUtf8(out_char: &unused, in_text, in_text_end);
2668}
2669
2670static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2671{
2672 if (c < 0x80) return 1;
2673 if (c < 0x800) return 2;
2674 if (c < 0x10000) return 3;
2675 if (c <= 0x10FFFF) return 4;
2676 return 3;
2677}
2678
2679int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2680{
2681 char* buf_p = out_buf;
2682 const char* buf_end = out_buf + out_buf_size;
2683 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2684 {
2685 unsigned int c = (unsigned int)(*in_text++);
2686 if (c < 0x80)
2687 *buf_p++ = (char)c;
2688 else
2689 buf_p += ImTextCharToUtf8_inline(buf: buf_p, buf_size: (int)(buf_end - buf_p - 1), c);
2690 }
2691 *buf_p = 0;
2692 return (int)(buf_p - out_buf);
2693}
2694
2695int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2696{
2697 int bytes_count = 0;
2698 while ((!in_text_end || in_text < in_text_end) && *in_text)
2699 {
2700 unsigned int c = (unsigned int)(*in_text++);
2701 if (c < 0x80)
2702 bytes_count++;
2703 else
2704 bytes_count += ImTextCountUtf8BytesFromChar(c);
2705 }
2706 return bytes_count;
2707}
2708
2709const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2710{
2711 while (in_text_curr > in_text_start)
2712 {
2713 in_text_curr--;
2714 if ((*in_text_curr & 0xC0) != 0x80)
2715 return in_text_curr;
2716 }
2717 return in_text_start;
2718}
2719
2720int ImTextCountLines(const char* in_text, const char* in_text_end)
2721{
2722 if (in_text_end == NULL)
2723 in_text_end = in_text + ImStrlen(s: in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2724 int count = 0;
2725 while (in_text < in_text_end)
2726 {
2727 const char* line_end = (const char*)ImMemchr(s: in_text, c: '\n', n: in_text_end - in_text);
2728 in_text = line_end ? line_end + 1 : in_text_end;
2729 count++;
2730 }
2731 return count;
2732}
2733
2734IM_MSVC_RUNTIME_CHECKS_RESTORE
2735
2736//-----------------------------------------------------------------------------
2737// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2738// Note: The Convert functions are early design which are not consistent with other API.
2739//-----------------------------------------------------------------------------
2740
2741IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2742{
2743 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2744 int r = ImLerp(a: (int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2745 int g = ImLerp(a: (int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2746 int b = ImLerp(a: (int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2747 return IM_COL32(r, g, b, 0xFF);
2748}
2749
2750ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2751{
2752 float s = 1.0f / 255.0f;
2753 return ImVec4(
2754 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2755 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2756 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2757 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2758}
2759
2760ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2761{
2762 ImU32 out;
2763 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2764 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2765 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2766 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2767 return out;
2768}
2769
2770// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2771// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2772void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2773{
2774 float K = 0.f;
2775 if (g < b)
2776 {
2777 ImSwap(a&: g, b);
2778 K = -1.f;
2779 }
2780 if (r < g)
2781 {
2782 ImSwap(a&: r, b&: g);
2783 K = -2.f / 6.f - K;
2784 }
2785
2786 const float chroma = r - (g < b ? g : b);
2787 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2788 out_s = chroma / (r + 1e-20f);
2789 out_v = r;
2790}
2791
2792// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2793// also http://en.wikipedia.org/wiki/HSL_and_HSV
2794void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2795{
2796 if (s == 0.0f)
2797 {
2798 // gray
2799 out_r = out_g = out_b = v;
2800 return;
2801 }
2802
2803 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2804 int i = (int)h;
2805 float f = h - (float)i;
2806 float p = v * (1.0f - s);
2807 float q = v * (1.0f - s * f);
2808 float t = v * (1.0f - s * (1.0f - f));
2809
2810 switch (i)
2811 {
2812 case 0: out_r = v; out_g = t; out_b = p; break;
2813 case 1: out_r = q; out_g = v; out_b = p; break;
2814 case 2: out_r = p; out_g = v; out_b = t; break;
2815 case 3: out_r = p; out_g = q; out_b = v; break;
2816 case 4: out_r = t; out_g = p; out_b = v; break;
2817 case 5: default: out_r = v; out_g = p; out_b = q; break;
2818 }
2819}
2820
2821//-----------------------------------------------------------------------------
2822// [SECTION] ImGuiStorage
2823// Helper: Key->value storage
2824//-----------------------------------------------------------------------------
2825
2826// std::lower_bound but without the bullshit
2827ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2828{
2829 ImGuiStoragePair* in_p = in_begin;
2830 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2831 {
2832 size_t count2 = count >> 1;
2833 ImGuiStoragePair* mid = in_p + count2;
2834 if (mid->key < key)
2835 {
2836 in_p = ++mid;
2837 count -= count2 + 1;
2838 }
2839 else
2840 {
2841 count = count2;
2842 }
2843 }
2844 return in_p;
2845}
2846
2847IM_MSVC_RUNTIME_CHECKS_OFF
2848static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2849{
2850 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2851 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2852 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2853 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2854}
2855
2856// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2857void ImGuiStorage::BuildSortByKey()
2858{
2859 ImQsort(base: Data.Data, count: (size_t)Data.Size, size_of_element: sizeof(ImGuiStoragePair), compare_func: PairComparerByID);
2860}
2861
2862int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2863{
2864 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2865 if (it == Data.Data + Data.Size || it->key != key)
2866 return default_val;
2867 return it->val_i;
2868}
2869
2870bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2871{
2872 return GetInt(key, default_val: default_val ? 1 : 0) != 0;
2873}
2874
2875float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2876{
2877 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2878 if (it == Data.Data + Data.Size || it->key != key)
2879 return default_val;
2880 return it->val_f;
2881}
2882
2883void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2884{
2885 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2886 if (it == Data.Data + Data.Size || it->key != key)
2887 return NULL;
2888 return it->val_p;
2889}
2890
2891// 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.
2892int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2893{
2894 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2895 if (it == Data.Data + Data.Size || it->key != key)
2896 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2897 return &it->val_i;
2898}
2899
2900bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2901{
2902 return (bool*)GetIntRef(key, default_val: default_val ? 1 : 0);
2903}
2904
2905float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2906{
2907 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2908 if (it == Data.Data + Data.Size || it->key != key)
2909 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2910 return &it->val_f;
2911}
2912
2913void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2914{
2915 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2916 if (it == Data.Data + Data.Size || it->key != key)
2917 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2918 return &it->val_p;
2919}
2920
2921// 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)
2922void ImGuiStorage::SetInt(ImGuiID key, int val)
2923{
2924 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2925 if (it == Data.Data + Data.Size || it->key != key)
2926 Data.insert(it, v: ImGuiStoragePair(key, val));
2927 else
2928 it->val_i = val;
2929}
2930
2931void ImGuiStorage::SetBool(ImGuiID key, bool val)
2932{
2933 SetInt(key, val: val ? 1 : 0);
2934}
2935
2936void ImGuiStorage::SetFloat(ImGuiID key, float val)
2937{
2938 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2939 if (it == Data.Data + Data.Size || it->key != key)
2940 Data.insert(it, v: ImGuiStoragePair(key, val));
2941 else
2942 it->val_f = val;
2943}
2944
2945void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2946{
2947 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2948 if (it == Data.Data + Data.Size || it->key != key)
2949 Data.insert(it, v: ImGuiStoragePair(key, val));
2950 else
2951 it->val_p = val;
2952}
2953
2954void ImGuiStorage::SetAllInt(int v)
2955{
2956 for (int i = 0; i < Data.Size; i++)
2957 Data[i].val_i = v;
2958}
2959IM_MSVC_RUNTIME_CHECKS_RESTORE
2960
2961//-----------------------------------------------------------------------------
2962// [SECTION] ImGuiTextFilter
2963//-----------------------------------------------------------------------------
2964
2965// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2966ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2967{
2968 InputBuf[0] = 0;
2969 CountGrep = 0;
2970 if (default_filter)
2971 {
2972 ImStrncpy(dst: InputBuf, src: default_filter, IM_ARRAYSIZE(InputBuf));
2973 Build();
2974 }
2975}
2976
2977bool ImGuiTextFilter::Draw(const char* label, float width)
2978{
2979 if (width != 0.0f)
2980 ImGui::SetNextItemWidth(width);
2981 bool value_changed = ImGui::InputText(label, buf: InputBuf, IM_ARRAYSIZE(InputBuf));
2982 if (value_changed)
2983 Build();
2984 return value_changed;
2985}
2986
2987void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2988{
2989 out->resize(new_size: 0);
2990 const char* wb = b;
2991 const char* we = wb;
2992 while (we < e)
2993 {
2994 if (*we == separator)
2995 {
2996 out->push_back(v: ImGuiTextRange(wb, we));
2997 wb = we + 1;
2998 }
2999 we++;
3000 }
3001 if (wb != we)
3002 out->push_back(v: ImGuiTextRange(wb, we));
3003}
3004
3005void ImGuiTextFilter::Build()
3006{
3007 Filters.resize(new_size: 0);
3008 ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(s: InputBuf));
3009 input_range.split(separator: ',', out: &Filters);
3010
3011 CountGrep = 0;
3012 for (ImGuiTextRange& f : Filters)
3013 {
3014 while (f.b < f.e && ImCharIsBlankA(c: f.b[0]))
3015 f.b++;
3016 while (f.e > f.b && ImCharIsBlankA(c: f.e[-1]))
3017 f.e--;
3018 if (f.empty())
3019 continue;
3020 if (f.b[0] != '-')
3021 CountGrep += 1;
3022 }
3023}
3024
3025bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
3026{
3027 if (Filters.Size == 0)
3028 return true;
3029
3030 if (text == NULL)
3031 text = text_end = "";
3032
3033 for (const ImGuiTextRange& f : Filters)
3034 {
3035 if (f.b == f.e)
3036 continue;
3037 if (f.b[0] == '-')
3038 {
3039 // Subtract
3040 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b + 1, needle_end: f.e) != NULL)
3041 return false;
3042 }
3043 else
3044 {
3045 // Grep
3046 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b, needle_end: f.e) != NULL)
3047 return true;
3048 }
3049 }
3050
3051 // Implicit * grep
3052 if (CountGrep == 0)
3053 return true;
3054
3055 return false;
3056}
3057
3058//-----------------------------------------------------------------------------
3059// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
3060//-----------------------------------------------------------------------------
3061
3062// On some platform vsnprintf() takes va_list by reference and modifies it.
3063// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
3064#ifndef va_copy
3065#if defined(__GNUC__) || defined(__clang__)
3066#define va_copy(dest, src) __builtin_va_copy(dest, src)
3067#else
3068#define va_copy(dest, src) (dest = src)
3069#endif
3070#endif
3071
3072char ImGuiTextBuffer::EmptyString[1] = { 0 };
3073
3074void ImGuiTextBuffer::append(const char* str, const char* str_end)
3075{
3076 int len = str_end ? (int)(str_end - str) : (int)ImStrlen(s: str);
3077
3078 // Add zero-terminator the first time
3079 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3080 const int needed_sz = write_off + len;
3081 if (write_off + len >= Buf.Capacity)
3082 {
3083 int new_capacity = Buf.Capacity * 2;
3084 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
3085 }
3086
3087 Buf.resize(new_size: needed_sz);
3088 memcpy(dest: &Buf[write_off - 1], src: str, n: (size_t)len);
3089 Buf[write_off - 1 + len] = 0;
3090}
3091
3092void ImGuiTextBuffer::appendf(const char* fmt, ...)
3093{
3094 va_list args;
3095 va_start(args, fmt);
3096 appendfv(fmt, args);
3097 va_end(args);
3098}
3099
3100// Helper: Text buffer for logging/accumulating text
3101void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
3102{
3103 va_list args_copy;
3104 va_copy(args_copy, args);
3105
3106 int len = ImFormatStringV(NULL, buf_size: 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
3107 if (len <= 0)
3108 {
3109 va_end(args_copy);
3110 return;
3111 }
3112
3113 // Add zero-terminator the first time
3114 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3115 const int needed_sz = write_off + len;
3116 if (write_off + len >= Buf.Capacity)
3117 {
3118 int new_capacity = Buf.Capacity * 2;
3119 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
3120 }
3121
3122 Buf.resize(new_size: needed_sz);
3123 ImFormatStringV(buf: &Buf[write_off - 1], buf_size: (size_t)len + 1, fmt, args: args_copy);
3124 va_end(args_copy);
3125}
3126
3127void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
3128{
3129 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
3130 if (old_size == new_size)
3131 return;
3132 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
3133 LineOffsets.push_back(v: EndOffset);
3134 const char* base_end = base + new_size;
3135 for (const char* p = base + old_size; (p = (const char*)ImMemchr(s: p, c: '\n', n: base_end - p)) != 0; )
3136 if (++p < base_end) // Don't push a trailing offset on last \n
3137 LineOffsets.push_back(v: (int)(intptr_t)(p - base));
3138 EndOffset = ImMax(lhs: EndOffset, rhs: new_size);
3139}
3140
3141//-----------------------------------------------------------------------------
3142// [SECTION] ImGuiListClipper
3143//-----------------------------------------------------------------------------
3144
3145// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
3146// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
3147static bool GetSkipItemForListClipping()
3148{
3149 ImGuiContext& g = *GImGui;
3150 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
3151}
3152
3153static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
3154{
3155 if (ranges.Size - offset <= 1)
3156 return;
3157
3158 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
3159 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
3160 for (int i = offset; i < sort_end + offset; ++i)
3161 if (ranges[i].Min > ranges[i + 1].Min)
3162 ImSwap(a&: ranges[i], b&: ranges[i + 1]);
3163
3164 // Now fuse ranges together as much as possible.
3165 for (int i = 1 + offset; i < ranges.Size; i++)
3166 {
3167 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
3168 if (ranges[i - 1].Max < ranges[i].Min)
3169 continue;
3170 ranges[i - 1].Min = ImMin(lhs: ranges[i - 1].Min, rhs: ranges[i].Min);
3171 ranges[i - 1].Max = ImMax(lhs: ranges[i - 1].Max, rhs: ranges[i].Max);
3172 ranges.erase(it: ranges.Data + i);
3173 i--;
3174 }
3175}
3176
3177static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
3178{
3179 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
3180 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
3181 // 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?
3182 ImGuiContext& g = *GImGui;
3183 ImGuiWindow* window = g.CurrentWindow;
3184 float off_y = pos_y - window->DC.CursorPos.y;
3185 window->DC.CursorPos.y = pos_y;
3186 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: pos_y - g.Style.ItemSpacing.y);
3187 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.
3188 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.
3189 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
3190 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
3191 if (ImGuiTable* table = g.CurrentTable)
3192 {
3193 if (table->IsInsideRow)
3194 ImGui::TableEndRow(table);
3195 table->RowPosY2 = window->DC.CursorPos.y;
3196 const int row_increase = (int)((off_y / line_height) + 0.5f);
3197 table->CurrentRow += row_increase;
3198 table->RowBgColorCounter += row_increase;
3199 }
3200}
3201
3202ImGuiListClipper::ImGuiListClipper()
3203{
3204 memset(s: this, c: 0, n: sizeof(*this));
3205}
3206
3207ImGuiListClipper::~ImGuiListClipper()
3208{
3209 End();
3210}
3211
3212void ImGuiListClipper::Begin(int items_count, float items_height)
3213{
3214 if (Ctx == NULL)
3215 Ctx = ImGui::GetCurrentContext();
3216
3217 ImGuiContext& g = *Ctx;
3218 ImGuiWindow* window = g.CurrentWindow;
3219 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3220
3221 if (ImGuiTable* table = g.CurrentTable)
3222 if (table->IsInsideRow)
3223 ImGui::TableEndRow(table);
3224
3225 StartPosY = window->DC.CursorPos.y;
3226 ItemsHeight = items_height;
3227 ItemsCount = items_count;
3228 DisplayStart = -1;
3229 DisplayEnd = 0;
3230
3231 // Acquire temporary buffer
3232 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3233 g.ClipperTempData.resize(new_size: g.ClipperTempDataStacked, v: ImGuiListClipperData());
3234 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3235 data->Reset(clipper: this);
3236 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3237 TempData = data;
3238 StartSeekOffsetY = data->LossynessOffset;
3239}
3240
3241void ImGuiListClipper::End()
3242{
3243 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3244 {
3245 // 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.
3246 ImGuiContext& g = *Ctx;
3247 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3248 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3249 SeekCursorForItem(item_index: ItemsCount);
3250
3251 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3252 IM_ASSERT(data->ListClipper == this);
3253 data->StepNo = data->Ranges.Size;
3254 if (--g.ClipperTempDataStacked > 0)
3255 {
3256 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3257 data->ListClipper->TempData = data;
3258 }
3259 TempData = NULL;
3260 }
3261 ItemsCount = -1;
3262}
3263
3264void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3265{
3266 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3267 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3268 IM_ASSERT(item_begin <= item_end);
3269 if (item_begin < item_end)
3270 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: item_begin, max: item_end));
3271}
3272
3273// This is already called while stepping.
3274// 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.
3275void ImGuiListClipper::SeekCursorForItem(int item_n)
3276{
3277 // - Perform the add and multiply with double to allow seeking through larger ranges.
3278 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3279 // - 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.
3280 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3281 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, line_height: ItemsHeight);
3282}
3283
3284static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3285{
3286 ImGuiContext& g = *clipper->Ctx;
3287 ImGuiWindow* window = g.CurrentWindow;
3288 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3289 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3290
3291 ImGuiTable* table = g.CurrentTable;
3292 if (table && table->IsInsideRow)
3293 ImGui::TableEndRow(table);
3294
3295 // No items
3296 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3297 return false;
3298
3299 // While we are in frozen row state, keep displaying items one by one, unclipped
3300 // FIXME: Could be stored as a table-agnostic state.
3301 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3302 {
3303 clipper->DisplayStart = data->ItemsFrozen;
3304 clipper->DisplayEnd = ImMin(lhs: data->ItemsFrozen + 1, rhs: clipper->ItemsCount);
3305 if (clipper->DisplayStart < clipper->DisplayEnd)
3306 data->ItemsFrozen++;
3307 return true;
3308 }
3309
3310 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3311 bool calc_clipping = false;
3312 if (data->StepNo == 0)
3313 {
3314 clipper->StartPosY = window->DC.CursorPos.y;
3315 if (clipper->ItemsHeight <= 0.0f)
3316 {
3317 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3318 data->Ranges.push_front(v: ImGuiListClipperRange::FromIndices(min: data->ItemsFrozen, max: data->ItemsFrozen + 1));
3319 clipper->DisplayStart = ImMax(lhs: data->Ranges[0].Min, rhs: data->ItemsFrozen);
3320 clipper->DisplayEnd = ImMin(lhs: data->Ranges[0].Max, rhs: clipper->ItemsCount);
3321 data->StepNo = 1;
3322 return true;
3323 }
3324 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3325 }
3326
3327 // Step 1: Let the clipper infer height from first range
3328 if (clipper->ItemsHeight <= 0.0f)
3329 {
3330 IM_ASSERT(data->StepNo == 1);
3331 if (table)
3332 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3333
3334 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(f: (float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(f: window->DC.CursorPos.y);
3335 if (affected_by_floating_point_precision)
3336 {
3337 // Mitigation/hack for very large range: assume last time height constitute line height.
3338 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3339 window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight);
3340 }
3341 else
3342 {
3343 clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3344 }
3345 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3346 return false;
3347 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3348 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3349 }
3350
3351 // Step 0 or 1: Calculate the actual ranges of visible elements.
3352 const int already_submitted = clipper->DisplayEnd;
3353 if (calc_clipping)
3354 {
3355 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3356 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3357
3358 if (g.LogEnabled)
3359 {
3360 // If logging is active, do not perform any clipping
3361 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: 0, max: clipper->ItemsCount));
3362 }
3363 else
3364 {
3365 // Add range selected to be included for navigation
3366 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3367 if (is_nav_request)
3368 {
3369 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringRect.Min.y, y2: g.NavScoringRect.Max.y, off_min: 0, off_max: 0));
3370 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringNoClipRect.Min.y, y2: g.NavScoringNoClipRect.Max.y, off_min: 0, off_max: 0));
3371 }
3372 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3373 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: clipper->ItemsCount - 1, max: clipper->ItemsCount));
3374
3375 // Add focused/active item
3376 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, r: window->NavRectRel[0]);
3377 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3378 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: nav_rect_abs.Min.y, y2: nav_rect_abs.Max.y, off_min: 0, off_max: 0));
3379
3380 // Add visible range
3381 float min_y = window->ClipRect.Min.y;
3382 float max_y = window->ClipRect.Max.y;
3383
3384 // Add box selection range
3385 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3386 if (bs->IsActive && bs->Window == window)
3387 {
3388 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3389 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3390 // As a workaround we currently half ItemSpacing worth on each side.
3391 min_y -= g.Style.ItemSpacing.y;
3392 max_y += g.Style.ItemSpacing.y;
3393
3394 // Box-select on 2D area requires different clipping.
3395 if (bs->UnclipMode)
3396 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: bs->UnclipRect.Min.y, y2: bs->UnclipRect.Max.y, off_min: 0, off_max: 0));
3397 }
3398
3399 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3400 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3401 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: min_y, y2: max_y, off_min, off_max));
3402 }
3403
3404 // Convert position ranges to item index ranges
3405 // - 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.
3406 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3407 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3408 for (ImGuiListClipperRange& range : data->Ranges)
3409 if (range.PosToIndexConvert)
3410 {
3411 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3412 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3413 range.Min = ImClamp(v: already_submitted + m1 + range.PosToIndexOffsetMin, mn: already_submitted, mx: clipper->ItemsCount - 1);
3414 range.Max = ImClamp(v: already_submitted + m2 + range.PosToIndexOffsetMax, mn: range.Min + 1, mx: clipper->ItemsCount);
3415 range.PosToIndexConvert = false;
3416 }
3417 ImGuiListClipper_SortAndFuseRanges(ranges&: data->Ranges, offset: data->StepNo);
3418 }
3419
3420 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3421 while (data->StepNo < data->Ranges.Size)
3422 {
3423 clipper->DisplayStart = ImMax(lhs: data->Ranges[data->StepNo].Min, rhs: already_submitted);
3424 clipper->DisplayEnd = ImMin(lhs: data->Ranges[data->StepNo].Max, rhs: clipper->ItemsCount);
3425 data->StepNo++;
3426 if (clipper->DisplayStart >= clipper->DisplayEnd)
3427 continue;
3428 if (clipper->DisplayStart > already_submitted)
3429 clipper->SeekCursorForItem(item_n: clipper->DisplayStart);
3430 return true;
3431 }
3432
3433 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3434 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3435 if (clipper->ItemsCount < INT_MAX)
3436 clipper->SeekCursorForItem(item_n: clipper->ItemsCount);
3437
3438 return false;
3439}
3440
3441bool ImGuiListClipper::Step()
3442{
3443 ImGuiContext& g = *Ctx;
3444 bool need_items_height = (ItemsHeight <= 0.0f);
3445 bool ret = ImGuiListClipper_StepInternal(clipper: this);
3446 if (ret && (DisplayStart >= DisplayEnd))
3447 ret = false;
3448 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3449 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3450 if (need_items_height && ItemsHeight > 0.0f)
3451 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3452 if (ret)
3453 {
3454 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3455 }
3456 else
3457 {
3458 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3459 End();
3460 }
3461 return ret;
3462}
3463
3464//-----------------------------------------------------------------------------
3465// [SECTION] STYLING
3466//-----------------------------------------------------------------------------
3467
3468ImGuiStyle& ImGui::GetStyle()
3469{
3470 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3471 return GImGui->Style;
3472}
3473
3474ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3475{
3476 ImGuiStyle& style = GImGui->Style;
3477 ImVec4 c = style.Colors[idx];
3478 c.w *= style.Alpha * alpha_mul;
3479 return ColorConvertFloat4ToU32(in: c);
3480}
3481
3482ImU32 ImGui::GetColorU32(const ImVec4& col)
3483{
3484 ImGuiStyle& style = GImGui->Style;
3485 ImVec4 c = col;
3486 c.w *= style.Alpha;
3487 return ColorConvertFloat4ToU32(in: c);
3488}
3489
3490const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3491{
3492 ImGuiStyle& style = GImGui->Style;
3493 return style.Colors[idx];
3494}
3495
3496ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3497{
3498 ImGuiStyle& style = GImGui->Style;
3499 alpha_mul *= style.Alpha;
3500 if (alpha_mul >= 1.0f)
3501 return col;
3502 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3503 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3504 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3505}
3506
3507// 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
3508void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3509{
3510 ImGuiContext& g = *GImGui;
3511 ImGuiColorMod backup;
3512 backup.Col = idx;
3513 backup.BackupValue = g.Style.Colors[idx];
3514 g.ColorStack.push_back(v: backup);
3515 if (g.DebugFlashStyleColorIdx != idx)
3516 g.Style.Colors[idx] = ColorConvertU32ToFloat4(in: col);
3517}
3518
3519void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3520{
3521 ImGuiContext& g = *GImGui;
3522 ImGuiColorMod backup;
3523 backup.Col = idx;
3524 backup.BackupValue = g.Style.Colors[idx];
3525 g.ColorStack.push_back(v: backup);
3526 if (g.DebugFlashStyleColorIdx != idx)
3527 g.Style.Colors[idx] = col;
3528}
3529
3530void ImGui::PopStyleColor(int count)
3531{
3532 ImGuiContext& g = *GImGui;
3533 if (g.ColorStack.Size < count)
3534 {
3535 IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
3536 count = g.ColorStack.Size;
3537 }
3538 while (count > 0)
3539 {
3540 ImGuiColorMod& backup = g.ColorStack.back();
3541 g.Style.Colors[backup.Col] = backup.BackupValue;
3542 g.ColorStack.pop_back();
3543 count--;
3544 }
3545}
3546
3547static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3548{
3549 ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3550};
3551
3552static const ImGuiStyleVarInfo GStyleVarsInfo[] =
3553{
3554 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3555 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3556 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3557 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3558 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3559 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3560 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3561 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3562 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3563 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3564 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3565 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3566 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3567 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3568 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3569 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3570 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3571 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3572 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3573 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3574 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3575 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3576 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize
3577 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3578 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3579 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase
3580 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink
3581 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3582 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3583 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3584 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3585 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize
3586 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding
3587 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3588 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3589 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3590 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3591 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3592 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3593};
3594
3595const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3596{
3597 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3598 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT);
3599 return &GStyleVarsInfo[idx];
3600}
3601
3602void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3603{
3604 ImGuiContext& g = *GImGui;
3605 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3606 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1)
3607 {
3608 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3609 return;
3610 }
3611 float* pvar = (float*)var_info->GetVarPtr(parent: &g.Style);
3612 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3613 *pvar = val;
3614}
3615
3616void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
3617{
3618 ImGuiContext& g = *GImGui;
3619 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3620 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3621 {
3622 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3623 return;
3624 }
3625 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3626 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3627 pvar->x = val_x;
3628}
3629
3630void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
3631{
3632 ImGuiContext& g = *GImGui;
3633 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3634 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3635 {
3636 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3637 return;
3638 }
3639 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3640 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3641 pvar->y = val_y;
3642}
3643
3644void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3645{
3646 ImGuiContext& g = *GImGui;
3647 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3648 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3649 {
3650 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3651 return;
3652 }
3653 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3654 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3655 *pvar = val;
3656}
3657
3658void ImGui::PopStyleVar(int count)
3659{
3660 ImGuiContext& g = *GImGui;
3661 if (g.StyleVarStack.Size < count)
3662 {
3663 IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
3664 count = g.StyleVarStack.Size;
3665 }
3666 while (count > 0)
3667 {
3668 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3669 ImGuiStyleMod& backup = g.StyleVarStack.back();
3670 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx: backup.VarIdx);
3671 void* data = var_info->GetVarPtr(parent: &g.Style);
3672 if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3673 else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3674 g.StyleVarStack.pop_back();
3675 count--;
3676 }
3677}
3678
3679const char* ImGui::GetStyleColorName(ImGuiCol idx)
3680{
3681 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3682 switch (idx)
3683 {
3684 case ImGuiCol_Text: return "Text";
3685 case ImGuiCol_TextDisabled: return "TextDisabled";
3686 case ImGuiCol_WindowBg: return "WindowBg";
3687 case ImGuiCol_ChildBg: return "ChildBg";
3688 case ImGuiCol_PopupBg: return "PopupBg";
3689 case ImGuiCol_Border: return "Border";
3690 case ImGuiCol_BorderShadow: return "BorderShadow";
3691 case ImGuiCol_FrameBg: return "FrameBg";
3692 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3693 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3694 case ImGuiCol_TitleBg: return "TitleBg";
3695 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3696 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3697 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3698 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3699 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3700 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3701 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3702 case ImGuiCol_CheckMark: return "CheckMark";
3703 case ImGuiCol_SliderGrab: return "SliderGrab";
3704 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3705 case ImGuiCol_Button: return "Button";
3706 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3707 case ImGuiCol_ButtonActive: return "ButtonActive";
3708 case ImGuiCol_Header: return "Header";
3709 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3710 case ImGuiCol_HeaderActive: return "HeaderActive";
3711 case ImGuiCol_Separator: return "Separator";
3712 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3713 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3714 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3715 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3716 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3717 case ImGuiCol_InputTextCursor: return "InputTextCursor";
3718 case ImGuiCol_TabHovered: return "TabHovered";
3719 case ImGuiCol_Tab: return "Tab";
3720 case ImGuiCol_TabSelected: return "TabSelected";
3721 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3722 case ImGuiCol_TabDimmed: return "TabDimmed";
3723 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3724 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3725 case ImGuiCol_DockingPreview: return "DockingPreview";
3726 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3727 case ImGuiCol_PlotLines: return "PlotLines";
3728 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3729 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3730 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3731 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3732 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3733 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3734 case ImGuiCol_TableRowBg: return "TableRowBg";
3735 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3736 case ImGuiCol_TextLink: return "TextLink";
3737 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3738 case ImGuiCol_TreeLines: return "TreeLines";
3739 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3740 case ImGuiCol_NavCursor: return "NavCursor";
3741 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3742 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3743 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3744 }
3745 IM_ASSERT(0);
3746 return "Unknown";
3747}
3748
3749//-----------------------------------------------------------------------------
3750// [SECTION] RENDER HELPERS
3751// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3752// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3753// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3754//-----------------------------------------------------------------------------
3755
3756const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3757{
3758 const char* text_display_end = text;
3759 if (!text_end)
3760 text_end = (const char*)-1;
3761
3762 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3763 text_display_end++;
3764 return text_display_end;
3765}
3766
3767// Internal ImGui functions to render text
3768// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3769void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3770{
3771 ImGuiContext& g = *GImGui;
3772 ImGuiWindow* window = g.CurrentWindow;
3773
3774 // Hide anything after a '##' string
3775 const char* text_display_end;
3776 if (hide_text_after_hash)
3777 {
3778 text_display_end = FindRenderedTextEnd(text, text_end);
3779 }
3780 else
3781 {
3782 if (!text_end)
3783 text_end = text + ImStrlen(s: text); // FIXME-OPT
3784 text_display_end = text_end;
3785 }
3786
3787 if (text != text_display_end)
3788 {
3789 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end);
3790 if (g.LogEnabled)
3791 LogRenderedText(ref_pos: &pos, text, text_end: text_display_end);
3792 }
3793}
3794
3795void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3796{
3797 ImGuiContext& g = *GImGui;
3798 ImGuiWindow* window = g.CurrentWindow;
3799
3800 if (!text_end)
3801 text_end = text + ImStrlen(s: text); // FIXME-OPT
3802
3803 if (text != text_end)
3804 {
3805 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end, wrap_width);
3806 if (g.LogEnabled)
3807 LogRenderedText(ref_pos: &pos, text, text_end);
3808 }
3809}
3810
3811// Default clip_rect uses (pos_min,pos_max)
3812// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3813// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList.
3814// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3815// better advantage of the render function taking size into account for coarse clipping.
3816void 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)
3817{
3818 // Perform CPU side clipping for single clipped element to avoid using scissor state
3819 ImVec2 pos = pos_min;
3820 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_display_end, hide_text_after_double_hash: false, wrap_width: 0.0f);
3821
3822 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3823 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3824 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3825 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3826 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3827
3828 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3829 if (align.x > 0.0f) pos.x = ImMax(lhs: pos.x, rhs: pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3830 if (align.y > 0.0f) pos.y = ImMax(lhs: pos.y, rhs: pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3831
3832 // Render
3833 if (need_clipping)
3834 {
3835 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3836 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, cpu_fine_clip_rect: &fine_clip_rect);
3837 }
3838 else
3839 {
3840 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, NULL);
3841 }
3842}
3843
3844void 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)
3845{
3846 // Hide anything after a '##' string
3847 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3848 const int text_len = (int)(text_display_end - text);
3849 if (text_len == 0)
3850 return;
3851
3852 ImGuiContext& g = *GImGui;
3853 ImGuiWindow* window = g.CurrentWindow;
3854 RenderTextClippedEx(draw_list: window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3855 if (g.LogEnabled)
3856 LogRenderedText(ref_pos: &pos_min, text, text_end: text_display_end);
3857}
3858
3859// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3860// 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.
3861// 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.
3862// (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceeding 'float ellipsis_max' and was the same value for 99% of users.
3863void 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)
3864{
3865 ImGuiContext& g = *GImGui;
3866 if (text_end_full == NULL)
3867 text_end_full = FindRenderedTextEnd(text);
3868 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_end_full, hide_text_after_double_hash: false, wrap_width: 0.0f);
3869
3870 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255));
3871 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255));
3872
3873 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3874 if (text_size.x > pos_max.x - pos_min.x)
3875 {
3876 // Hello wo...
3877 // | | |
3878 // min max ellipsis_max
3879 // <-> this is generally some padding value
3880
3881 ImFont* font = draw_list->_Data->Font;
3882 const float font_size = draw_list->_Data->FontSize;
3883 const float font_scale = draw_list->_Data->FontScale;
3884 const char* text_end_ellipsis = NULL;
3885 ImFontBaked* baked = font->GetFontBaked(font_size);
3886 const float ellipsis_width = baked->GetCharAdvance(c: font->EllipsisChar) * font_scale;
3887
3888 // We can now claim the space between pos_max.x and ellipsis_max.x
3889 const float text_avail_width = ImMax(lhs: (ImMax(lhs: pos_max.x, rhs: ellipsis_max_x) - ellipsis_width) - pos_min.x, rhs: 1.0f);
3890 float text_size_clipped_x = font->CalcTextSizeA(size: font_size, max_width: text_avail_width, wrap_width: 0.0f, text_begin: text, text_end: text_end_full, remaining: &text_end_ellipsis).x;
3891 while (text_end_ellipsis > text && ImCharIsBlankA(c: text_end_ellipsis[-1]))
3892 {
3893 // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3894 text_end_ellipsis--;
3895 text_size_clipped_x -= font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text_end_ellipsis, text_end: text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3896 }
3897
3898 // Render text, render ellipsis
3899 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_display_end: text_end_ellipsis, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3900 ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y);
3901 ImVec2 ellipsis_pos = ImTrunc(v: ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3902 font->RenderChar(draw_list, size: font_size, pos: ellipsis_pos, col: GetColorU32(idx: ImGuiCol_Text), c: font->EllipsisChar, cpu_fine_clip: &cpu_fine_clip_rect);
3903 }
3904 else
3905 {
3906 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_display_end: text_end_full, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3907 }
3908
3909 if (g.LogEnabled)
3910 LogRenderedText(ref_pos: &pos_min, text, text_end: text_end_full);
3911}
3912
3913// Render a rectangle shaped with optional rounding and borders
3914void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding)
3915{
3916 ImGuiContext& g = *GImGui;
3917 ImGuiWindow* window = g.CurrentWindow;
3918 window->DrawList->AddRectFilled(p_min, p_max, col: fill_col, rounding);
3919 const float border_size = g.Style.FrameBorderSize;
3920 if (borders && border_size > 0.0f)
3921 {
3922 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3923 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3924 }
3925}
3926
3927void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3928{
3929 ImGuiContext& g = *GImGui;
3930 ImGuiWindow* window = g.CurrentWindow;
3931 const float border_size = g.Style.FrameBorderSize;
3932 if (border_size > 0.0f)
3933 {
3934 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3935 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3936 }
3937}
3938
3939void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags)
3940{
3941 ImGuiContext& g = *GImGui;
3942 if (id != g.NavId)
3943 return;
3944 if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
3945 return;
3946 if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
3947 return;
3948 ImGuiWindow* window = g.CurrentWindow;
3949 if (window->DC.NavHideHighlightOneFrame)
3950 return;
3951
3952 float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3953 ImRect display_rect = bb;
3954 display_rect.ClipWith(r: window->ClipRect);
3955 const float thickness = 2.0f;
3956 if (flags & ImGuiNavRenderCursorFlags_Compact)
3957 {
3958 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavCursor), rounding, flags: 0, thickness);
3959 }
3960 else
3961 {
3962 const float distance = 3.0f + thickness * 0.5f;
3963 display_rect.Expand(amount: ImVec2(distance, distance));
3964 bool fully_visible = window->ClipRect.Contains(r: display_rect);
3965 if (!fully_visible)
3966 window->DrawList->PushClipRect(clip_rect_min: display_rect.Min, clip_rect_max: display_rect.Max);
3967 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavCursor), rounding, flags: 0, thickness);
3968 if (!fully_visible)
3969 window->DrawList->PopClipRect();
3970 }
3971}
3972
3973void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3974{
3975 ImGuiContext& g = *GImGui;
3976 if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
3977 mouse_cursor = ImGuiMouseCursor_Arrow;
3978 ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas;
3979 for (ImGuiViewportP* viewport : g.Viewports)
3980 {
3981 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3982 ImVec2 offset, size, uv[4];
3983 if (!ImFontAtlasGetMouseCursorTexData(atlas: font_atlas, cursor_type: mouse_cursor, out_offset: &offset, out_size: &size, out_uv_border: &uv[0], out_uv_fill: &uv[2]))
3984 continue;
3985 const ImVec2 pos = base_pos - offset;
3986 const float scale = base_scale * viewport->DpiScale;
3987 if (!viewport->GetMainRect().Overlaps(r: ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3988 continue;
3989 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3990 ImTextureRef tex_ref = font_atlas->TexRef;
3991 draw_list->PushTexture(tex_ref);
3992 draw_list->AddImage(tex_ref, p_min: pos + ImVec2(1, 0) * scale, p_max: pos + (ImVec2(1, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3993 draw_list->AddImage(tex_ref, p_min: pos + ImVec2(2, 0) * scale, p_max: pos + (ImVec2(2, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3994 draw_list->AddImage(tex_ref, p_min: pos, p_max: pos + size * scale, uv_min: uv[2], uv_max: uv[3], col: col_border);
3995 draw_list->AddImage(tex_ref, p_min: pos, p_max: pos + size * scale, uv_min: uv[0], uv_max: uv[1], col: col_fill);
3996 if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress)
3997 {
3998 float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI);
3999 float a_max = a_min + IM_PI * 1.65f;
4000 draw_list->PathArcTo(center: pos + ImVec2(14, -1) * scale, radius: 6.0f * scale, a_min, a_max);
4001 draw_list->PathStroke(col: col_fill, flags: ImDrawFlags_None, thickness: 3.0f * scale);
4002 }
4003 draw_list->PopTexture();
4004 }
4005}
4006
4007//-----------------------------------------------------------------------------
4008// [SECTION] INITIALIZATION, SHUTDOWN
4009//-----------------------------------------------------------------------------
4010
4011// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
4012// 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
4013ImGuiContext* ImGui::GetCurrentContext()
4014{
4015 return GImGui;
4016}
4017
4018void ImGui::SetCurrentContext(ImGuiContext* ctx)
4019{
4020#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
4021 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
4022#else
4023 GImGui = ctx;
4024#endif
4025}
4026
4027void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
4028{
4029 GImAllocatorAllocFunc = alloc_func;
4030 GImAllocatorFreeFunc = free_func;
4031 GImAllocatorUserData = user_data;
4032}
4033
4034// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
4035void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
4036{
4037 *p_alloc_func = GImAllocatorAllocFunc;
4038 *p_free_func = GImAllocatorFreeFunc;
4039 *p_user_data = GImAllocatorUserData;
4040}
4041
4042ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
4043{
4044 ImGuiContext* prev_ctx = GetCurrentContext();
4045 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
4046 SetCurrentContext(ctx);
4047 Initialize();
4048 if (prev_ctx != NULL)
4049 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
4050 return ctx;
4051}
4052
4053void ImGui::DestroyContext(ImGuiContext* ctx)
4054{
4055 ImGuiContext* prev_ctx = GetCurrentContext();
4056 if (ctx == NULL) //-V1051
4057 ctx = prev_ctx;
4058 SetCurrentContext(ctx);
4059 Shutdown();
4060 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
4061 IM_DELETE(p: ctx);
4062}
4063
4064// IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation.
4065static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
4066{
4067 { .Key: ImGuiLocKey_VersionStr, .Text: "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
4068 { .Key: ImGuiLocKey_TableSizeOne, .Text: "Size column to fit###SizeOne" },
4069 { .Key: ImGuiLocKey_TableSizeAllFit, .Text: "Size all columns to fit###SizeAll" },
4070 { .Key: ImGuiLocKey_TableSizeAllDefault, .Text: "Size all columns to default###SizeAll" },
4071 { .Key: ImGuiLocKey_TableResetOrder, .Text: "Reset order###ResetOrder" },
4072 { .Key: ImGuiLocKey_WindowingMainMenuBar, .Text: "(Main menu bar)" },
4073 { .Key: ImGuiLocKey_WindowingPopup, .Text: "(Popup)" },
4074 { .Key: ImGuiLocKey_WindowingUntitled, .Text: "(Untitled)" },
4075 { .Key: ImGuiLocKey_OpenLink_s, .Text: "Open '%s'" },
4076 { .Key: ImGuiLocKey_CopyLink, .Text: "Copy Link###CopyLink" },
4077 { .Key: ImGuiLocKey_DockingHideTabBar, .Text: "Hide tab bar###HideTabBar" },
4078 { .Key: ImGuiLocKey_DockingHoldShiftToDock, .Text: "Hold SHIFT to enable Docking window." },
4079 { .Key: ImGuiLocKey_DockingDragToUndockOrMoveNode,.Text: "Click and drag to move or undock whole node." },
4080};
4081
4082ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
4083{
4084 IO.Ctx = this;
4085 InputTextState.Ctx = this;
4086
4087 Initialized = false;
4088 ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None;
4089
4090 Font = NULL;
4091 FontBaked = NULL;
4092 FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f;
4093 FontRasterizerDensity = 1.0f;
4094 IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
4095 if (shared_font_atlas == NULL)
4096 IO.Fonts->OwnerContext = this;
4097 Time = 0.0f;
4098 FrameCount = 0;
4099 FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1;
4100 WithinEndChildID = 0;
4101 WithinFrameScope = WithinFrameScopeWithImplicitWindow = false;
4102 GcCompactAll = false;
4103 TestEngineHookItems = false;
4104 TestEngine = NULL;
4105 memset(s: ContextName, c: 0, n: sizeof(ContextName));
4106
4107 InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
4108 InputEventsNextEventId = 1;
4109
4110 WindowsActiveCount = 0;
4111 WindowsBorderHoverPadding = 0.0f;
4112 CurrentWindow = NULL;
4113 HoveredWindow = NULL;
4114 HoveredWindowUnderMovingWindow = NULL;
4115 HoveredWindowBeforeClear = NULL;
4116 MovingWindow = NULL;
4117 WheelingWindow = NULL;
4118 WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
4119 WheelingWindowReleaseTimer = 0.0f;
4120
4121 DebugDrawIdConflictsId = 0;
4122 DebugHookIdInfo = 0;
4123 HoveredId = HoveredIdPreviousFrame = 0;
4124 HoveredIdPreviousFrameItemCount = 0;
4125 HoveredIdAllowOverlap = false;
4126 HoveredIdIsDisabled = false;
4127 HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
4128 ItemUnclipByLog = false;
4129 ActiveId = 0;
4130 ActiveIdIsAlive = 0;
4131 ActiveIdTimer = 0.0f;
4132 ActiveIdIsJustActivated = false;
4133 ActiveIdAllowOverlap = false;
4134 ActiveIdNoClearOnFocusLoss = false;
4135 ActiveIdHasBeenPressedBefore = false;
4136 ActiveIdHasBeenEditedBefore = false;
4137 ActiveIdHasBeenEditedThisFrame = false;
4138 ActiveIdFromShortcut = false;
4139 ActiveIdClickOffset = ImVec2(-1, -1);
4140 ActiveIdWindow = NULL;
4141 ActiveIdSource = ImGuiInputSource_None;
4142 ActiveIdDisabledId = 0;
4143 ActiveIdMouseButton = -1;
4144 ActiveIdPreviousFrame = 0;
4145 memset(s: &DeactivatedItemData, c: 0, n: sizeof(DeactivatedItemData));
4146 memset(s: &ActiveIdValueOnActivation, c: 0, n: sizeof(ActiveIdValueOnActivation));
4147 LastActiveId = 0;
4148 LastActiveIdTimer = 0.0f;
4149
4150 LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
4151
4152 ActiveIdUsingNavDirMask = 0x00;
4153 ActiveIdUsingAllKeyboardKeys = false;
4154
4155 CurrentFocusScopeId = 0;
4156 CurrentItemFlags = ImGuiItemFlags_None;
4157 DebugShowGroupRects = false;
4158
4159 CurrentViewport = NULL;
4160 MouseViewport = MouseLastHoveredViewport = NULL;
4161 PlatformLastFocusedViewportId = 0;
4162 ViewportCreatedCount = PlatformWindowsCreatedCount = 0;
4163 ViewportFocusedStampCount = 0;
4164
4165 NavCursorVisible = false;
4166 NavHighlightItemUnderNav = false;
4167 NavMousePosDirty = false;
4168 NavIdIsAlive = false;
4169 NavId = 0;
4170 NavWindow = NULL;
4171 NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
4172 NavLayer = ImGuiNavLayer_Main;
4173 NavNextActivateId = 0;
4174 NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
4175 NavHighlightActivatedId = 0;
4176 NavHighlightActivatedTimer = 0.0f;
4177 NavInputSource = ImGuiInputSource_Keyboard;
4178 NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
4179 NavCursorHideFrames = 0;
4180
4181 NavAnyRequest = false;
4182 NavInitRequest = false;
4183 NavInitRequestFromMove = false;
4184 NavMoveSubmitted = false;
4185 NavMoveScoringItems = false;
4186 NavMoveForwardToNextFrame = false;
4187 NavMoveFlags = ImGuiNavMoveFlags_None;
4188 NavMoveScrollFlags = ImGuiScrollFlags_None;
4189 NavMoveKeyMods = ImGuiMod_None;
4190 NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
4191 NavScoringDebugCount = 0;
4192 NavTabbingDir = 0;
4193 NavTabbingCounter = 0;
4194
4195 NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
4196 NavJustMovedToKeyMods = ImGuiMod_None;
4197 NavJustMovedToIsTabbing = false;
4198 NavJustMovedToHasSelectionData = false;
4199
4200 // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
4201 // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
4202 ConfigNavWindowingWithGamepad = true;
4203 ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
4204 ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
4205 NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
4206 NavWindowingInputSource = ImGuiInputSource_None;
4207 NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
4208 NavWindowingToggleLayer = false;
4209 NavWindowingToggleKey = ImGuiKey_None;
4210
4211 DimBgRatio = 0.0f;
4212
4213 DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
4214 DragDropSourceFlags = ImGuiDragDropFlags_None;
4215 DragDropSourceFrameCount = -1;
4216 DragDropMouseButton = -1;
4217 DragDropTargetId = 0;
4218 DragDropAcceptFlags = ImGuiDragDropFlags_None;
4219 DragDropAcceptIdCurrRectSurface = 0.0f;
4220 DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
4221 DragDropAcceptFrameCount = -1;
4222 DragDropHoldJustPressedId = 0;
4223 memset(s: DragDropPayloadBufLocal, c: 0, n: sizeof(DragDropPayloadBufLocal));
4224
4225 ClipperTempDataStacked = 0;
4226
4227 CurrentTable = NULL;
4228 TablesTempDataStacked = 0;
4229 CurrentTabBar = NULL;
4230 CurrentMultiSelect = NULL;
4231 MultiSelectTempDataStacked = 0;
4232
4233 HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
4234 HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
4235
4236 MouseCursor = ImGuiMouseCursor_Arrow;
4237 MouseStationaryTimer = 0.0f;
4238
4239 InputTextPasswordFontBackupFlags = ImFontFlags_None;
4240 TempInputId = 0;
4241 memset(s: &DataTypeZeroValue, c: 0, n: sizeof(DataTypeZeroValue));
4242 BeginMenuDepth = BeginComboDepth = 0;
4243 ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
4244 ColorEditCurrentID = ColorEditSavedID = 0;
4245 ColorEditSavedHue = ColorEditSavedSat = 0.0f;
4246 ColorEditSavedColor = 0;
4247 WindowResizeRelativeMode = false;
4248 ScrollbarSeekMode = 0;
4249 ScrollbarClickDeltaToGrabCenter = 0.0f;
4250 SliderGrabClickOffset = 0.0f;
4251 SliderCurrentAccum = 0.0f;
4252 SliderCurrentAccumDirty = false;
4253 DragCurrentAccumDirty = false;
4254 DragCurrentAccum = 0.0f;
4255 DragSpeedDefaultRatio = 1.0f / 100.0f;
4256 DisabledAlphaBackup = 0.0f;
4257 DisabledStackSize = 0;
4258 TooltipOverrideCount = 0;
4259 TooltipPreviousWindow = NULL;
4260
4261 PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
4262 PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
4263
4264 DockNodeWindowMenuHandler = NULL;
4265
4266 SettingsLoaded = false;
4267 SettingsDirtyTimer = 0.0f;
4268 HookIdNext = 0;
4269
4270 memset(s: LocalizationTable, c: 0, n: sizeof(LocalizationTable));
4271
4272 LogEnabled = false;
4273 LogFlags = ImGuiLogFlags_None;
4274 LogWindow = NULL;
4275 LogNextPrefix = LogNextSuffix = NULL;
4276 LogFile = NULL;
4277 LogLinePosY = FLT_MAX;
4278 LogLineFirstItem = false;
4279 LogDepthRef = 0;
4280 LogDepthToExpand = LogDepthToExpandDefault = 2;
4281
4282 ErrorCallback = NULL;
4283 ErrorCallbackUserData = NULL;
4284 ErrorFirst = true;
4285 ErrorCountCurrentFrame = 0;
4286 StackSizesInBeginForCurrentWindow = NULL;
4287
4288 DebugDrawIdConflictsCount = 0;
4289 DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
4290 DebugLocateId = 0;
4291 DebugLogSkippedErrors = 0;
4292 DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4293 DebugLogAutoDisableFrames = 0;
4294 DebugLocateFrames = 0;
4295 DebugBeginReturnValueCullDepth = -1;
4296 DebugItemPickerActive = false;
4297 DebugItemPickerMouseButton = ImGuiMouseButton_Left;
4298 DebugItemPickerBreakId = 0;
4299 DebugFlashStyleColorTime = 0.0f;
4300 DebugFlashStyleColorIdx = ImGuiCol_COUNT;
4301 DebugHoveredDockNode = NULL;
4302
4303 // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
4304 DebugBreakInWindow = 0;
4305 DebugBreakInTable = 0;
4306 DebugBreakInLocateId = false;
4307 DebugBreakKeyChord = ImGuiKey_Pause;
4308 DebugBreakInShortcutRouting = ImGuiKey_None;
4309
4310 memset(s: FramerateSecPerFrame, c: 0, n: sizeof(FramerateSecPerFrame));
4311 FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
4312 FramerateSecPerFrameAccum = 0.0f;
4313 WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
4314 memset(s: TempKeychordName, c: 0, n: sizeof(TempKeychordName));
4315}
4316
4317void ImGui::Initialize()
4318{
4319 ImGuiContext& g = *GImGui;
4320 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4321
4322 // Add .ini handle for ImGuiWindow and ImGuiTable types
4323 {
4324 ImGuiSettingsHandler ini_handler;
4325 ini_handler.TypeName = "Window";
4326 ini_handler.TypeHash = ImHashStr(data_p: "Window");
4327 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4328 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4329 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4330 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4331 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4332 AddSettingsHandler(handler: &ini_handler);
4333 }
4334 TableSettingsAddSettingsHandler();
4335
4336 // Setup default localization table
4337 LocalizeRegisterEntries(entries: GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
4338
4339 // Setup default ImGuiPlatformIO clipboard/IME handlers.
4340 g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
4341 g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl;
4342 g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl;
4343 g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl;
4344
4345 // Create default viewport
4346 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4347 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4348 viewport->Idx = 0;
4349 viewport->PlatformWindowCreated = true;
4350 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
4351 g.Viewports.push_back(v: viewport);
4352 g.TempBuffer.resize(new_size: 1024 * 3 + 1, v: 0);
4353 g.ViewportCreatedCount++;
4354 g.PlatformIO.Viewports.push_back(v: g.Viewports[0]);
4355
4356 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
4357 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4358 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
4359 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
4360 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
4361 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
4362 g.KeysMayBeCharInput.SetBit(key);
4363
4364#ifdef IMGUI_HAS_DOCK
4365 // Initialize Docking
4366 DockContextInitialize(ctx: &g);
4367#endif
4368
4369 // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow.
4370 // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED.
4371#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
4372 DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
4373#endif
4374
4375 // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context.
4376 // But this link allows us to facilitate/handle a few edge cases better.
4377 ImFontAtlas* atlas = g.IO.Fonts;
4378 g.DrawListSharedData.Context = &g;
4379 RegisterFontAtlas(atlas);
4380
4381 g.Initialized = true;
4382}
4383
4384// This function is merely here to free heap allocations.
4385void ImGui::Shutdown()
4386{
4387 ImGuiContext& g = *GImGui;
4388 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
4389 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
4390
4391 // 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)
4392 for (ImFontAtlas* atlas : g.FontAtlases)
4393 {
4394 UnregisterFontAtlas(atlas);
4395 if (atlas->OwnerContext == &g)
4396 {
4397 atlas->Locked = false;
4398 IM_DELETE(p: atlas);
4399 }
4400 }
4401 g.DrawListSharedData.TempBuffer.clear();
4402
4403 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4404 if (!g.Initialized)
4405 return;
4406
4407 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4408 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4409 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
4410
4411 // Destroy platform windows
4412 DestroyPlatformWindows();
4413
4414 // Shutdown extensions
4415 DockContextShutdown(ctx: &g);
4416
4417 CallContextHooks(context: &g, type: ImGuiContextHookType_Shutdown);
4418
4419 // Clear everything else
4420 g.Windows.clear_delete();
4421 g.WindowsFocusOrder.clear();
4422 g.WindowsTempSortBuffer.clear();
4423 g.CurrentWindow = NULL;
4424 g.CurrentWindowStack.clear();
4425 g.WindowsById.Clear();
4426 g.NavWindow = NULL;
4427 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4428 g.ActiveIdWindow = NULL;
4429 g.MovingWindow = NULL;
4430
4431 g.KeysRoutingTable.Clear();
4432
4433 g.ColorStack.clear();
4434 g.StyleVarStack.clear();
4435 g.FontStack.clear();
4436 g.OpenPopupStack.clear();
4437 g.BeginPopupStack.clear();
4438 g.TreeNodeStack.clear();
4439
4440 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
4441 g.Viewports.clear_delete();
4442
4443 g.TabBars.Clear();
4444 g.CurrentTabBarStack.clear();
4445 g.ShrinkWidthBuffer.clear();
4446
4447 g.ClipperTempData.clear_destruct();
4448
4449 g.Tables.Clear();
4450 g.TablesTempData.clear_destruct();
4451 g.DrawChannelsTempMergeBuffer.clear();
4452
4453 g.MultiSelectStorage.Clear();
4454 g.MultiSelectTempData.clear_destruct();
4455
4456 g.ClipboardHandlerData.clear();
4457 g.MenusIdSubmittedThisFrame.clear();
4458 g.InputTextState.ClearFreeMemory();
4459 g.InputTextDeactivatedState.ClearFreeMemory();
4460
4461 g.SettingsWindows.clear();
4462 g.SettingsHandlers.clear();
4463
4464 if (g.LogFile)
4465 {
4466#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4467 if (g.LogFile != stdout)
4468#endif
4469 ImFileClose(f: g.LogFile);
4470 g.LogFile = NULL;
4471 }
4472 g.LogBuffer.clear();
4473 g.DebugLogBuf.clear();
4474 g.DebugLogIndex.clear();
4475
4476 g.Initialized = false;
4477}
4478
4479// No specific ordering/dependency support, will see as needed
4480ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
4481{
4482 ImGuiContext& g = *ctx;
4483 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
4484 g.Hooks.push_back(v: *hook);
4485 g.Hooks.back().HookId = ++g.HookIdNext;
4486 return g.HookIdNext;
4487}
4488
4489// Deferred removal, avoiding issue with changing vector while iterating it
4490void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
4491{
4492 ImGuiContext& g = *ctx;
4493 IM_ASSERT(hook_id != 0);
4494 for (ImGuiContextHook& hook : g.Hooks)
4495 if (hook.HookId == hook_id)
4496 hook.Type = ImGuiContextHookType_PendingRemoval_;
4497}
4498
4499// Call context hooks (used by e.g. test engine)
4500// We assume a small number of hooks so all stored in same array
4501void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
4502{
4503 ImGuiContext& g = *ctx;
4504 for (ImGuiContextHook& hook : g.Hooks)
4505 if (hook.Type == hook_type)
4506 hook.Callback(&g, &hook);
4507}
4508
4509//-----------------------------------------------------------------------------
4510// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4511//-----------------------------------------------------------------------------
4512
4513// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4514ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4515{
4516 memset(s: this, c: 0, n: sizeof(*this));
4517 Ctx = ctx;
4518 Name = ImStrdup(str: name);
4519 NameBufLen = (int)ImStrlen(s: name) + 1;
4520 ID = ImHashStr(data_p: name);
4521 IDStack.push_back(v: ID);
4522 ViewportAllowPlatformMonitorExtend = -1;
4523 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
4524 MoveId = GetID(str: "#MOVE");
4525 TabId = GetID(str: "#TAB");
4526 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4527 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4528 AutoFitFramesX = AutoFitFramesY = -1;
4529 AutoPosLastDirection = ImGuiDir_None;
4530 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4531 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4532 LastFrameActive = -1;
4533 LastFrameJustFocused = -1;
4534 LastTimeActive = -1.0f;
4535 FontRefSize = 0.0f;
4536 FontWindowScale = FontWindowScaleParents = 1.0f;
4537 SettingsOffset = -1;
4538 DockOrder = -1;
4539 DrawList = &DrawListInst;
4540 DrawList->_OwnerName = Name;
4541 DrawList->_SetDrawListSharedData(data: &Ctx->DrawListSharedData);
4542 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4543 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4544}
4545
4546ImGuiWindow::~ImGuiWindow()
4547{
4548 IM_ASSERT(DrawList == &DrawListInst);
4549 IM_DELETE(p: Name);
4550 ColumnsStorage.clear_destruct();
4551}
4552
4553static void SetCurrentWindow(ImGuiWindow* window)
4554{
4555 ImGuiContext& g = *GImGui;
4556 g.CurrentWindow = window;
4557 g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
4558 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(n: window->DC.CurrentTableIdx) : NULL;
4559 if (window)
4560 {
4561 bool backup_skip_items = window->SkipItems;
4562 window->SkipItems = false;
4563 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
4564 {
4565 ImGuiViewport* viewport = window->Viewport;
4566 g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity()
4567 }
4568 ImGui::UpdateCurrentFontSize(restore_font_size_after_scaling: 0.0f);
4569 window->SkipItems = backup_skip_items;
4570 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4571 }
4572}
4573
4574void ImGui::GcCompactTransientMiscBuffers()
4575{
4576 ImGuiContext& g = *GImGui;
4577 g.ItemFlagsStack.clear();
4578 g.GroupStack.clear();
4579 g.MultiSelectTempDataStacked = 0;
4580 g.MultiSelectTempData.clear_destruct();
4581 TableGcCompactSettings();
4582 for (ImFontAtlas* atlas : g.FontAtlases)
4583 atlas->CompactCache();
4584}
4585
4586// Free up/compact internal window buffers, we can use this when a window becomes unused.
4587// Not freed:
4588// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4589// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4590void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4591{
4592 window->MemoryCompacted = true;
4593 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4594 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4595 window->IDStack.clear();
4596 window->DrawList->_ClearFreeMemory();
4597 window->DC.ChildWindows.clear();
4598 window->DC.ItemWidthStack.clear();
4599 window->DC.TextWrapPosStack.clear();
4600}
4601
4602void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4603{
4604 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4605 // The other buffers tends to amortize much faster.
4606 window->MemoryCompacted = false;
4607 window->DrawList->IdxBuffer.reserve(new_capacity: window->MemoryDrawListIdxCapacity);
4608 window->DrawList->VtxBuffer.reserve(new_capacity: window->MemoryDrawListVtxCapacity);
4609 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4610}
4611
4612void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4613{
4614 ImGuiContext& g = *GImGui;
4615
4616 // Clear previous active id
4617 if (g.ActiveId != 0)
4618 {
4619 // Store deactivate data
4620 ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData;
4621 deactivated_data->ID = g.ActiveId;
4622 deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData?
4623 deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4624 deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId);
4625
4626 // This could be written in a more general way (e.g associate a hook to ActiveId),
4627 // but since this is currently quite an exception we'll leave it as is.
4628 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
4629 if (g.InputTextState.ID == g.ActiveId)
4630 InputTextDeactivateHook(id: g.ActiveId);
4631
4632 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4633 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4634 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4635 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4636 {
4637 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4638 StopMouseMovingWindow();
4639 }
4640 }
4641
4642 // Set active id
4643 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4644 if (g.ActiveIdIsJustActivated)
4645 {
4646 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4647 g.ActiveIdTimer = 0.0f;
4648 g.ActiveIdHasBeenPressedBefore = false;
4649 g.ActiveIdHasBeenEditedBefore = false;
4650 g.ActiveIdMouseButton = -1;
4651 if (id != 0)
4652 {
4653 g.LastActiveId = id;
4654 g.LastActiveIdTimer = 0.0f;
4655 }
4656 }
4657 g.ActiveId = id;
4658 g.ActiveIdAllowOverlap = false;
4659 g.ActiveIdNoClearOnFocusLoss = false;
4660 g.ActiveIdWindow = window;
4661 g.ActiveIdHasBeenEditedThisFrame = false;
4662 g.ActiveIdFromShortcut = false;
4663 g.ActiveIdDisabledId = 0;
4664 if (id)
4665 {
4666 g.ActiveIdIsAlive = id;
4667 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4668 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4669 }
4670
4671 // Clear declaration of inputs claimed by the widget
4672 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4673 g.ActiveIdUsingNavDirMask = 0x00;
4674 g.ActiveIdUsingAllKeyboardKeys = false;
4675}
4676
4677void ImGui::ClearActiveID()
4678{
4679 SetActiveID(id: 0, NULL); // g.ActiveId = 0;
4680}
4681
4682void ImGui::SetHoveredID(ImGuiID id)
4683{
4684 ImGuiContext& g = *GImGui;
4685 g.HoveredId = id;
4686 g.HoveredIdAllowOverlap = false;
4687 if (id != 0 && g.HoveredIdPreviousFrame != id)
4688 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4689}
4690
4691ImGuiID ImGui::GetHoveredID()
4692{
4693 ImGuiContext& g = *GImGui;
4694 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4695}
4696
4697void ImGui::MarkItemEdited(ImGuiID id)
4698{
4699 // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
4700 // 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.
4701 ImGuiContext& g = *GImGui;
4702 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
4703 return;
4704 if (g.ActiveId == id || g.ActiveId == 0)
4705 {
4706 // FIXME: Can't we fully rely on LastItemData yet?
4707 g.ActiveIdHasBeenEditedThisFrame = true;
4708 g.ActiveIdHasBeenEditedBefore = true;
4709 if (g.DeactivatedItemData.ID == id)
4710 g.DeactivatedItemData.HasBeenEditedBefore = true;
4711 }
4712
4713 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4714 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4715 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4716
4717 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4718 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4719}
4720
4721bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4722{
4723 // An active popup disable hovering on other windows (apart from its own children)
4724 // FIXME-OPT: This could be cached/stored within the window.
4725 ImGuiContext& g = *GImGui;
4726 if (g.NavWindow)
4727 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4728 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4729 {
4730 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4731 // NB: The 'else' is important because Modal windows are also Popups.
4732 bool want_inhibit = false;
4733 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4734 want_inhibit = true;
4735 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4736 want_inhibit = true;
4737
4738 // Inhibit hover unless the window is within the stack of our modal/popup
4739 if (want_inhibit)
4740 if (!IsWindowWithinBeginStackOf(window: window->RootWindow, potential_parent: focused_root_window))
4741 return false;
4742 }
4743
4744 // Filter by viewport
4745 if (window->Viewport != g.MouseViewport)
4746 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4747 return false;
4748
4749 return true;
4750}
4751
4752static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4753{
4754 ImGuiContext& g = *GImGui;
4755 if (flags & ImGuiHoveredFlags_DelayNormal)
4756 return g.Style.HoverDelayNormal;
4757 if (flags & ImGuiHoveredFlags_DelayShort)
4758 return g.Style.HoverDelayShort;
4759 return 0.0f;
4760}
4761
4762static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4763{
4764 // Allow instance flags to override shared flags
4765 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4766 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4767 return user_flags | shared_flags;
4768}
4769
4770// This is roughly matching the behavior of internal-facing ItemHoverable()
4771// - 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()
4772// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4773bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4774{
4775 ImGuiContext& g = *GImGui;
4776 ImGuiWindow* window = g.CurrentWindow;
4777 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
4778
4779 if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
4780 {
4781 if (!IsItemFocused())
4782 return false;
4783 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4784 return false;
4785
4786 if (flags & ImGuiHoveredFlags_ForTooltip)
4787 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipNav);
4788 }
4789 else
4790 {
4791 // Test for bounding box overlap, as updated as ItemAdd()
4792 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4793 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4794 return false;
4795
4796 if (flags & ImGuiHoveredFlags_ForTooltip)
4797 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
4798
4799 // Done with rectangle culling so we can perform heavier checks now
4800 // Test if we are hovering the right window (our window could be behind another window)
4801 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4802 // [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
4803 // 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
4804 // the test that has been running for a long while.
4805 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4806 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4807 return false;
4808
4809 // Test if another item is active (e.g. being dragged)
4810 const ImGuiID id = g.LastItemData.ID;
4811 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4812 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4813 {
4814 // When ActiveId == MoveId it means that either:
4815 // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag)
4816 // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed.
4817 // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId.
4818 bool cancel_is_hovered = true;
4819 if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id))
4820 cancel_is_hovered = false;
4821 // When ActiveId == TabId it means user clicked docking tab for the window.
4822 if (g.ActiveId == window->TabId)
4823 cancel_is_hovered = false;
4824 if (cancel_is_hovered)
4825 return false;
4826 }
4827
4828 // Test if interactions on this window are blocked by an active popup or modal.
4829 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4830 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4831 return false;
4832
4833 // Test if the item is disabled
4834 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4835 return false;
4836
4837 // Special handling for calling after Begin() which represent the title bar or tab.
4838 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4839 // will never be overwritten so we need to detect the case.
4840 if (id == window->MoveId && window->WriteAccessed)
4841 return false;
4842
4843 // Test if using AllowOverlap and overlapped
4844 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4845 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4846 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4847 return false;
4848 }
4849
4850 // Handle hover delay
4851 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4852 const float delay = CalcDelayFromHoveredFlags(flags);
4853 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4854 {
4855 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(p_abs: g.LastItemData.Rect.Min);
4856 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4857 g.HoverItemDelayTimer = 0.0f;
4858 g.HoverItemDelayId = hover_delay_id;
4859
4860 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4861 // but once unlocked on a given item we also moving.
4862 //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); }
4863 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4864 return false;
4865
4866 if (g.HoverItemDelayTimer < delay)
4867 return false;
4868 }
4869
4870 return true;
4871}
4872
4873// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK.
4874// Returns whether the item was hovered, logic differs slightly from IsItemHovered().
4875// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4876// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4877// If you used this in your legacy/custom widgets code:
4878// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
4879// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4880bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4881{
4882 ImGuiContext& g = *GImGui;
4883 ImGuiWindow* window = g.CurrentWindow;
4884
4885 // Detect ID conflicts
4886 // (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)
4887#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4888 if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
4889 {
4890 g.HoveredIdPreviousFrameItemCount++;
4891 if (g.DebugDrawIdConflictsId == id)
4892 window->DrawList->AddRect(p_min: bb.Min - ImVec2(1,1), p_max: bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), rounding: 0.0f, flags: ImDrawFlags_None, thickness: 2.0f);
4893 }
4894#endif
4895
4896 if (g.HoveredWindow != window)
4897 return false;
4898 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
4899 return false;
4900
4901 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4902 return false;
4903 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4904 if (!g.ActiveIdFromShortcut)
4905 return false;
4906
4907 // We are done with rectangle culling so we can perform heavier checks now.
4908 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, flags: ImGuiHoveredFlags_None))
4909 {
4910 g.HoveredIdIsDisabled = true;
4911 return false;
4912 }
4913
4914 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4915 // hover test in widgets code. We could also decide to split this function is two.
4916 if (id != 0)
4917 {
4918 // Drag source doesn't report as hovered
4919 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4920 return false;
4921
4922 SetHoveredID(id);
4923
4924 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4925 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4926 if (item_flags & ImGuiItemFlags_AllowOverlap)
4927 {
4928 g.HoveredIdAllowOverlap = true;
4929 if (g.HoveredIdPreviousFrame != id)
4930 return false;
4931 }
4932
4933 // Display shortcut (only works with mouse)
4934 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4935 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
4936 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4937 SetTooltip("%s", GetKeyChordName(key_chord: g.LastItemData.Shortcut));
4938 }
4939
4940 // When disabled we'll return false but still set HoveredId
4941 if (item_flags & ImGuiItemFlags_Disabled)
4942 {
4943 // Release active id if turning disabled
4944 if (g.ActiveId == id && id != 0)
4945 ClearActiveID();
4946 g.HoveredIdIsDisabled = true;
4947 return false;
4948 }
4949
4950#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4951 if (id != 0)
4952 {
4953 // [DEBUG] Item Picker tool!
4954 // We perform the check here because reaching is path is rare (1~ time a frame),
4955 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4956 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4957 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4958 GetForegroundDrawList()->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
4959 if (g.DebugItemPickerBreakId == id)
4960 IM_DEBUG_BREAK();
4961 }
4962#endif
4963
4964 if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
4965 return false;
4966
4967 return true;
4968}
4969
4970// FIXME: This is inlined/duplicated in ItemAdd()
4971// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4972bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4973{
4974 ImGuiContext& g = *GImGui;
4975 ImGuiWindow* window = g.CurrentWindow;
4976 if (!bb.Overlaps(r: window->ClipRect))
4977 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4978 if (!g.ItemUnclipByLog)
4979 return true;
4980 return false;
4981}
4982
4983// This is also inlined in ItemAdd()
4984// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4985void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect)
4986{
4987 ImGuiContext& g = *GImGui;
4988 g.LastItemData.ID = item_id;
4989 g.LastItemData.ItemFlags = item_flags;
4990 g.LastItemData.StatusFlags = status_flags;
4991 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4992}
4993
4994static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
4995{
4996 ImGuiContext& g = *GImGui;
4997 if (window->DockIsActive)
4998 SetLastItemData(item_id: window->MoveId, item_flags: g.CurrentItemFlags, status_flags: window->DC.DockTabItemStatusFlags, item_rect: window->DC.DockTabItemRect);
4999 else
5000 SetLastItemData(item_id: window->MoveId, item_flags: g.CurrentItemFlags, status_flags: window->DC.WindowItemStatusFlags, item_rect: rect);
5001}
5002
5003static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect)
5004{
5005 ImGuiContext& g = *GImGui;
5006 SetLastItemData(item_id: window->ChildId, item_flags: g.CurrentItemFlags, status_flags: window->DC.ChildItemStatusFlags, item_rect: rect);
5007}
5008
5009float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
5010{
5011 if (wrap_pos_x < 0.0f)
5012 return 0.0f;
5013
5014 ImGuiContext& g = *GImGui;
5015 ImGuiWindow* window = g.CurrentWindow;
5016 if (wrap_pos_x == 0.0f)
5017 {
5018 // We could decide to setup a default wrapping max point for auto-resizing windows,
5019 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
5020 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
5021 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
5022 //else
5023 wrap_pos_x = window->WorkRect.Max.x;
5024 }
5025 else if (wrap_pos_x > 0.0f)
5026 {
5027 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
5028 }
5029
5030 return ImMax(lhs: wrap_pos_x - pos.x, rhs: 1.0f);
5031}
5032
5033// IM_ALLOC() == ImGui::MemAlloc()
5034void* ImGui::MemAlloc(size_t size)
5035{
5036 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
5037#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5038 if (ImGuiContext* ctx = GImGui)
5039 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size);
5040#endif
5041 return ptr;
5042}
5043
5044// IM_FREE() == ImGui::MemFree()
5045void ImGui::MemFree(void* ptr)
5046{
5047#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5048 if (ptr != NULL)
5049 if (ImGuiContext* ctx = GImGui)
5050 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size: (size_t)-1);
5051#endif
5052 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
5053}
5054
5055// 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"
5056void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
5057{
5058 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5059 IM_UNUSED(ptr);
5060 if (entry->FrameCount != frame_count)
5061 {
5062 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
5063 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5064 entry->FrameCount = frame_count;
5065 entry->AllocCount = entry->FreeCount = 0;
5066 }
5067 if (size != (size_t)-1)
5068 {
5069 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
5070 entry->AllocCount++;
5071 info->TotalAllocCount++;
5072 }
5073 else
5074 {
5075 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
5076 entry->FreeCount++;
5077 info->TotalFreeCount++;
5078 }
5079}
5080
5081const char* ImGui::GetClipboardText()
5082{
5083 ImGuiContext& g = *GImGui;
5084 return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : "";
5085}
5086
5087void ImGui::SetClipboardText(const char* text)
5088{
5089 ImGuiContext& g = *GImGui;
5090 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5091 g.PlatformIO.Platform_SetClipboardTextFn(&g, text);
5092}
5093
5094const char* ImGui::GetVersion()
5095{
5096 return IMGUI_VERSION;
5097}
5098
5099ImGuiIO& ImGui::GetIO()
5100{
5101 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5102 return GImGui->IO;
5103}
5104
5105// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5106ImGuiIO& ImGui::GetIO(ImGuiContext* ctx)
5107{
5108 IM_ASSERT(ctx != NULL);
5109 return ctx->IO;
5110}
5111
5112ImGuiPlatformIO& ImGui::GetPlatformIO()
5113{
5114 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
5115 return GImGui->PlatformIO;
5116}
5117
5118// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5119ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx)
5120{
5121 IM_ASSERT(ctx != NULL);
5122 return ctx->PlatformIO;
5123}
5124
5125// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
5126ImDrawData* ImGui::GetDrawData()
5127{
5128 ImGuiContext& g = *GImGui;
5129 ImGuiViewportP* viewport = g.Viewports[0];
5130 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
5131}
5132
5133double ImGui::GetTime()
5134{
5135 return GImGui->Time;
5136}
5137
5138int ImGui::GetFrameCount()
5139{
5140 return GImGui->FrameCount;
5141}
5142
5143static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
5144{
5145 // Create the draw list on demand, because they are not frequently used for all viewports
5146 ImGuiContext& g = *GImGui;
5147 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
5148 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
5149 if (draw_list == NULL)
5150 {
5151 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
5152 draw_list->_OwnerName = drawlist_name;
5153 viewport->BgFgDrawLists[drawlist_no] = draw_list;
5154 }
5155
5156 // Our ImDrawList system requires that there is always a command
5157 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
5158 {
5159 draw_list->_ResetForNewFrame();
5160 draw_list->PushTexture(tex_ref: g.IO.Fonts->TexRef);
5161 draw_list->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size, intersect_with_current_clip_rect: false);
5162 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
5163 }
5164 return draw_list;
5165}
5166
5167ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
5168{
5169 if (viewport == NULL)
5170 viewport = GImGui->CurrentWindow->Viewport;
5171 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 0, drawlist_name: "##Background");
5172}
5173
5174ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
5175{
5176 if (viewport == NULL)
5177 viewport = GImGui->CurrentWindow->Viewport;
5178 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 1, drawlist_name: "##Foreground");
5179}
5180
5181ImDrawListSharedData* ImGui::GetDrawListSharedData()
5182{
5183 return &GImGui->DrawListSharedData;
5184}
5185
5186void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
5187{
5188 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
5189 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
5190 // This is because we want ActiveId to be set even when the window is not permitted to move.
5191 ImGuiContext& g = *GImGui;
5192 FocusWindow(window);
5193 SetActiveID(id: window->MoveId, window);
5194 if (g.IO.ConfigNavCursorVisibleAuto)
5195 g.NavCursorVisible = false;
5196 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
5197 g.ActiveIdNoClearOnFocusLoss = true;
5198 SetActiveIdUsingAllKeyboardKeys();
5199
5200 bool can_move_window = true;
5201 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
5202 can_move_window = false;
5203 if (ImGuiDockNode* node = window->DockNodeAsHost)
5204 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
5205 can_move_window = false;
5206 if (can_move_window)
5207 g.MovingWindow = window;
5208}
5209
5210// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
5211void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
5212{
5213 ImGuiContext& g = *GImGui;
5214 bool can_undock_node = false;
5215 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
5216 {
5217 // Can undock if:
5218 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
5219 // - part of a dockspace node hierarchy: so we can undock the last single visible node too. Undocking from a fixed/central node will create a new node and copy windows.
5220 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
5221 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
5222 can_undock_node = true;
5223 }
5224
5225 const bool clicked = IsMouseClicked(button: 0);
5226 const bool dragging = IsMouseDragging(button: 0);
5227 if (can_undock_node && dragging)
5228 DockContextQueueUndockNode(ctx: &g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
5229 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
5230 StartMouseMovingWindow(window);
5231}
5232
5233// This is not 100% symetric with StartMouseMovingWindow().
5234// We do NOT clear ActiveID, because:
5235// - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired.
5236// - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item).
5237void ImGui::StopMouseMovingWindow()
5238{
5239 ImGuiContext& g = *GImGui;
5240 ImGuiWindow* window = g.MovingWindow;
5241
5242 // Ref commits 6b7766817, 36055213c for some partial history on checking if viewport != NULL.
5243 if (window && window->Viewport)
5244 {
5245 // Try to merge the window back into the main viewport.
5246 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
5247 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
5248 UpdateTryMergeWindowIntoHostViewport(window, host_viewport: g.MouseViewport);
5249
5250 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
5251 if (!IsDragDropPayloadBeingAccepted())
5252 g.MouseViewport = window->Viewport;
5253
5254 // Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport()
5255 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
5256 if (window_can_use_inputs)
5257 window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
5258 }
5259 g.MovingWindow = NULL;
5260}
5261
5262// Handle mouse moving window
5263// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
5264// FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId.
5265// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
5266// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
5267void ImGui::UpdateMouseMovingWindowNewFrame()
5268{
5269 ImGuiContext& g = *GImGui;
5270 if (g.MovingWindow != NULL)
5271 {
5272 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
5273 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
5274 KeepAliveID(id: g.ActiveId);
5275 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
5276 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
5277
5278 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
5279 const bool window_disappeared = (!moving_window->WasActive && !moving_window->Active);
5280 if (g.IO.MouseDown[0] && IsMousePosValid(mouse_pos: &g.IO.MousePos) && !window_disappeared)
5281 {
5282 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
5283 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
5284 {
5285 SetWindowPos(window: moving_window, pos, cond: ImGuiCond_Always);
5286 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
5287 {
5288 moving_window->Viewport->Pos = pos;
5289 moving_window->Viewport->UpdateWorkRect();
5290 }
5291 }
5292 FocusWindow(window: g.MovingWindow);
5293 }
5294 else
5295 {
5296 StopMouseMovingWindow();
5297 ClearActiveID();
5298 }
5299 }
5300 else
5301 {
5302 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
5303 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
5304 {
5305 KeepAliveID(id: g.ActiveId);
5306 if (!g.IO.MouseDown[0])
5307 ClearActiveID();
5308 }
5309 }
5310}
5311
5312// Initiate focusing and moving window when clicking on empty space or title bar.
5313// Initiate focusing window when clicking on a disabled item.
5314// Handle left-click and right-click focus.
5315void ImGui::UpdateMouseMovingWindowEndFrame()
5316{
5317 ImGuiContext& g = *GImGui;
5318 if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
5319 return;
5320
5321 // Unless we just made a window/popup appear
5322 if (g.NavWindow && g.NavWindow->Appearing)
5323 return;
5324
5325 // Click on empty space to focus window and start moving
5326 // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
5327 if (g.IO.MouseClicked[0])
5328 {
5329 // Handle the edge case of a popup being closed while clicking in its empty space.
5330 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
5331 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
5332 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(id: root_window->PopupId, popup_flags: ImGuiPopupFlags_AnyPopupLevel);
5333
5334 if (root_window != NULL && !is_closed_popup)
5335 {
5336 StartMouseMovingWindow(window: g.HoveredWindow); //-V595
5337
5338 // FIXME: In principal we might be able to call StopMouseMovingWindow() below.
5339 // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId.
5340
5341 // Cancel moving if clicked outside of title bar
5342 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
5343 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
5344 if (!root_window->TitleBarRect().Contains(p: g.IO.MouseClickedPos[0]))
5345 g.MovingWindow = NULL;
5346
5347 // Cancel moving if clicked over an item which was disabled or inhibited by popups
5348 // (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)
5349 if (g.HoveredIdIsDisabled)
5350 {
5351 g.MovingWindow = NULL;
5352 g.ActiveIdDisabledId = g.HoveredId;
5353 }
5354 }
5355 else if (root_window == NULL && g.NavWindow != NULL)
5356 {
5357 // Clicking on void disable focus
5358 FocusWindow(NULL, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
5359 }
5360 }
5361
5362 // With right mouse button we close popups without changing focus based on where the mouse is aimed
5363 // Instead, focus will be restored to the window under the bottom-most closed popup.
5364 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
5365 if (g.IO.MouseClicked[1] && g.HoveredId == 0)
5366 {
5367 // Find the top-most window between HoveredWindow and the top-most Modal Window.
5368 // This is where we can trim the popup stack.
5369 ImGuiWindow* modal = GetTopMostPopupModal();
5370 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(potential_above: g.HoveredWindow, potential_below: modal));
5371 ClosePopupsOverWindow(ref_window: hovered_window_above_modal ? g.HoveredWindow : modal, restore_focus_to_window_under_popup: true);
5372 }
5373}
5374
5375// This is called during NewFrame()->UpdateViewportsNewFrame() only.
5376// Need to keep in sync with SetWindowPos()
5377static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
5378{
5379 window->Pos += delta;
5380 window->ClipRect.Translate(d: delta);
5381 window->OuterRectClipped.Translate(d: delta);
5382 window->InnerRect.Translate(d: delta);
5383 window->DC.CursorPos += delta;
5384 window->DC.CursorStartPos += delta;
5385 window->DC.CursorMaxPos += delta;
5386 window->DC.IdealMaxPos += delta;
5387}
5388
5389static void ScaleWindow(ImGuiWindow* window, float scale)
5390{
5391 ImVec2 origin = window->Viewport->Pos;
5392 window->Pos = ImFloor(v: (window->Pos - origin) * scale + origin);
5393 window->Size = ImTrunc(v: window->Size * scale);
5394 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
5395 window->ContentSize = ImTrunc(v: window->ContentSize * scale);
5396}
5397
5398static bool IsWindowActiveAndVisible(ImGuiWindow* window)
5399{
5400 return (window->Active) && (!window->Hidden);
5401}
5402
5403// 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)
5404void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos)
5405{
5406 ImGuiContext& g = *GImGui;
5407 ImGuiIO& io = g.IO;
5408
5409 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
5410 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
5411 g.WindowsBorderHoverPadding = ImMax(lhs: ImMax(lhs: g.Style.TouchExtraPadding.x, rhs: g.Style.TouchExtraPadding.y), rhs: g.Style.WindowBorderHoverPadding);
5412
5413 // Find the window hovered by mouse:
5414 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
5415 // - 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.
5416 // - 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.
5417 bool clear_hovered_windows = false;
5418 FindHoveredWindowEx(pos: mouse_pos, find_first_and_in_any_viewport: false, out_hovered_window: &g.HoveredWindow, out_hovered_window_under_moving_window: &g.HoveredWindowUnderMovingWindow);
5419 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
5420 g.HoveredWindowBeforeClear = g.HoveredWindow;
5421
5422 // Modal windows prevents mouse from hovering behind them.
5423 ImGuiWindow* modal_window = GetTopMostPopupModal();
5424 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(window: g.HoveredWindow->RootWindow, potential_parent: modal_window)) // FIXME-MERGE: RootWindowDockTree ?
5425 clear_hovered_windows = true;
5426
5427 // Disabled mouse hovering (we don't currently clear MousePos, we could)
5428 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
5429 clear_hovered_windows = true;
5430
5431 // We track click ownership. When clicked outside of a window the click is owned by the application and
5432 // won't report hovering nor request capture even while dragging over our windows afterward.
5433 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
5434 const bool has_open_modal = (modal_window != NULL);
5435 int mouse_earliest_down = -1;
5436 bool mouse_any_down = false;
5437 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
5438 {
5439 if (io.MouseClicked[i])
5440 {
5441 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
5442 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
5443 }
5444 mouse_any_down |= io.MouseDown[i];
5445 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
5446 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
5447 mouse_earliest_down = i;
5448 }
5449 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
5450 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
5451
5452 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
5453 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
5454 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
5455 if (!mouse_avail && !mouse_dragging_extern_payload)
5456 clear_hovered_windows = true;
5457
5458 if (clear_hovered_windows)
5459 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5460
5461 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
5462 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
5463 if (g.WantCaptureMouseNextFrame != -1)
5464 {
5465 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
5466 }
5467 else
5468 {
5469 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
5470 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
5471 }
5472
5473 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
5474 io.WantCaptureKeyboard = false;
5475 if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
5476 {
5477 if ((g.ActiveId != 0) || (modal_window != NULL))
5478 io.WantCaptureKeyboard = true;
5479 else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
5480 io.WantCaptureKeyboard = true;
5481 }
5482 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
5483 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
5484
5485 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
5486 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
5487}
5488
5489// Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
5490// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
5491static void SetupDrawListSharedData()
5492{
5493 ImGuiContext& g = *GImGui;
5494 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
5495 for (ImGuiViewportP* viewport : g.Viewports)
5496 virtual_space.Add(r: viewport->GetMainRect());
5497 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
5498 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
5499 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
5500 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
5501 if (g.Style.AntiAliasedLines)
5502 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
5503 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
5504 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
5505 if (g.Style.AntiAliasedFill)
5506 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
5507 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
5508 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
5509 g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments.
5510}
5511
5512void ImGui::NewFrame()
5513{
5514 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5515 ImGuiContext& g = *GImGui;
5516
5517 // Remove pending delete hooks before frame start.
5518 // This deferred removal avoid issues of removal while iterating the hook vector
5519 for (int n = g.Hooks.Size - 1; n >= 0; n--)
5520 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
5521 g.Hooks.erase(it: &g.Hooks[n]);
5522
5523 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePre);
5524
5525 // Check and assert for various common IO and Configuration mistakes
5526 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
5527 ErrorCheckNewFrameSanityChecks();
5528 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
5529
5530 // Load settings on first frame, save settings when modified (after a delay)
5531 UpdateSettings();
5532
5533 g.Time += g.IO.DeltaTime;
5534 g.FrameCount += 1;
5535 g.TooltipOverrideCount = 0;
5536 g.WindowsActiveCount = 0;
5537 g.MenusIdSubmittedThisFrame.resize(new_size: 0);
5538
5539 // Calculate frame-rate for the user, as a purely luxurious feature
5540 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
5541 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
5542 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
5543 g.FramerateSecPerFrameCount = ImMin(lhs: g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
5544 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
5545
5546 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
5547 g.InputEventsTrail.resize(new_size: 0);
5548 UpdateInputEvents(trickle_fast_inputs: g.IO.ConfigInputTrickleEventQueue);
5549
5550 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
5551 UpdateViewportsNewFrame();
5552
5553 // Update texture list (collect destroyed textures, etc.)
5554 UpdateTexturesNewFrame();
5555
5556 // Setup current font and draw list shared data
5557 SetupDrawListSharedData();
5558 UpdateFontsNewFrame();
5559
5560 g.WithinFrameScope = true;
5561
5562 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
5563 for (ImGuiViewportP* viewport : g.Viewports)
5564 {
5565 viewport->DrawData = NULL;
5566 viewport->DrawDataP.Valid = false;
5567 }
5568
5569 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
5570 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
5571 KeepAliveID(id: g.DragDropPayload.SourceId);
5572
5573 // [DEBUG]
5574 if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
5575 g.DebugDrawIdConflictsId = 0;
5576 if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
5577 g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame;
5578
5579 // Update HoveredId data
5580 if (!g.HoveredIdPreviousFrame)
5581 g.HoveredIdTimer = 0.0f;
5582 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
5583 g.HoveredIdNotActiveTimer = 0.0f;
5584 if (g.HoveredId)
5585 g.HoveredIdTimer += g.IO.DeltaTime;
5586 if (g.HoveredId && g.ActiveId != g.HoveredId)
5587 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
5588 g.HoveredIdPreviousFrame = g.HoveredId;
5589 g.HoveredIdPreviousFrameItemCount = 0;
5590 g.HoveredId = 0;
5591 g.HoveredIdAllowOverlap = false;
5592 g.HoveredIdIsDisabled = false;
5593
5594 // Clear ActiveID if the item is not alive anymore.
5595 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
5596 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
5597 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
5598 {
5599 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
5600 ClearActiveID();
5601 }
5602
5603 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
5604 if (g.ActiveId)
5605 g.ActiveIdTimer += g.IO.DeltaTime;
5606 g.LastActiveIdTimer += g.IO.DeltaTime;
5607 g.ActiveIdPreviousFrame = g.ActiveId;
5608 g.ActiveIdIsAlive = 0;
5609 g.ActiveIdHasBeenEditedThisFrame = false;
5610 g.ActiveIdIsJustActivated = false;
5611 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
5612 g.TempInputId = 0;
5613 if (g.ActiveId == 0)
5614 {
5615 g.ActiveIdUsingNavDirMask = 0x00;
5616 g.ActiveIdUsingAllKeyboardKeys = false;
5617 }
5618 if (g.DeactivatedItemData.ElapseFrame < g.FrameCount)
5619 g.DeactivatedItemData.ID = 0;
5620 g.DeactivatedItemData.IsAlive = false;
5621
5622 // Record when we have been stationary as this state is preserved while over same item.
5623 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5624 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5625 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5626 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5627 else if (g.HoverItemDelayId == 0)
5628 g.HoverItemUnlockedStationaryId = 0;
5629 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5630 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5631 else if (g.HoveredWindow == NULL)
5632 g.HoverWindowUnlockedStationaryId = 0;
5633
5634 // Update hover delay for IsItemHovered() with delays and tooltips
5635 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5636 if (g.HoverItemDelayId != 0)
5637 {
5638 g.HoverItemDelayTimer += g.IO.DeltaTime;
5639 g.HoverItemDelayClearTimer = 0.0f;
5640 g.HoverItemDelayId = 0;
5641 }
5642 else if (g.HoverItemDelayTimer > 0.0f)
5643 {
5644 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5645 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5646 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5647 if (g.HoverItemDelayClearTimer >= ImMax(lhs: 0.25f, rhs: g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5648 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.
5649 }
5650
5651 // Drag and drop
5652 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5653 g.DragDropAcceptIdCurr = 0;
5654 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5655 g.DragDropWithinSource = false;
5656 g.DragDropWithinTarget = false;
5657 g.DragDropHoldJustPressedId = 0;
5658 g.TooltipPreviousWindow = NULL;
5659
5660 // Close popups on focus lost (currently wip/opt-in)
5661 //if (g.IO.AppFocusLost)
5662 // ClosePopupsExceptModals();
5663
5664 // Update keyboard input state
5665 UpdateKeyboardInputs();
5666
5667 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5668 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5669 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5670 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5671
5672 // Update keyboard/gamepad navigation
5673 NavUpdate();
5674
5675 // Update mouse input state
5676 UpdateMouseInputs();
5677
5678 // Undocking
5679 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5680 DockContextNewFrameUpdateUndocking(ctx: &g);
5681
5682 // Mark all windows as not visible and compact unused memory.
5683 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5684 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5685 for (ImGuiWindow* window : g.Windows)
5686 {
5687 window->WasActive = window->Active;
5688 window->Active = false;
5689 window->WriteAccessed = false;
5690 window->BeginCountPreviousFrame = window->BeginCount;
5691 window->BeginCount = 0;
5692
5693 // Garbage collect transient buffers of recently unused windows
5694 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5695 GcCompactTransientWindowBuffers(window);
5696 }
5697
5698 // Find hovered window
5699 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5700 // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
5701 UpdateHoveredWindowAndCaptureFlags(mouse_pos: g.IO.MousePos);
5702
5703 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5704 UpdateMouseMovingWindowNewFrame();
5705
5706 // Background darkening/whitening
5707 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5708 g.DimBgRatio = ImMin(lhs: g.DimBgRatio + g.IO.DeltaTime * 6.0f, rhs: 1.0f);
5709 else
5710 g.DimBgRatio = ImMax(lhs: g.DimBgRatio - g.IO.DeltaTime * 10.0f, rhs: 0.0f);
5711
5712 g.MouseCursor = ImGuiMouseCursor_Arrow;
5713 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5714
5715 // Platform IME data: reset for the frame
5716 g.PlatformImeDataPrev = g.PlatformImeData;
5717 g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false;
5718
5719 // Mouse wheel scrolling, scale
5720 UpdateMouseWheel();
5721
5722 // Garbage collect transient buffers of recently unused tables
5723 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5724 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5725 TableGcCompactTransientBuffers(table: g.Tables.GetByIndex(n: i));
5726 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5727 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5728 TableGcCompactTransientBuffers(table: &table_temp_data);
5729 if (g.GcCompactAll)
5730 GcCompactTransientMiscBuffers();
5731 g.GcCompactAll = false;
5732
5733 // Closing the focused window restore focus to the first active root window in descending z-order
5734 if (g.NavWindow && !g.NavWindow->WasActive)
5735 FocusTopMostWindowUnderOne(NULL, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
5736
5737 // No window should be open at the beginning of the frame.
5738 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5739 g.CurrentWindowStack.resize(new_size: 0);
5740 g.BeginPopupStack.resize(new_size: 0);
5741 g.ItemFlagsStack.resize(new_size: 0);
5742 g.ItemFlagsStack.push_back(v: ImGuiItemFlags_AutoClosePopups); // Default flags
5743 g.CurrentItemFlags = g.ItemFlagsStack.back();
5744 g.GroupStack.resize(new_size: 0);
5745
5746 // Docking
5747 DockContextNewFrameUpdateDocking(ctx: &g);
5748
5749 // [DEBUG] Update debug features
5750#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5751 UpdateDebugToolItemPicker();
5752 UpdateDebugToolStackQueries();
5753 UpdateDebugToolFlashStyleColor();
5754 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5755 {
5756 g.DebugLocateId = 0;
5757 g.DebugBreakInLocateId = false;
5758 }
5759 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5760 {
5761 DebugLog(fmt: "(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5762 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5763 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5764 }
5765#endif
5766
5767 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5768 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5769 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5770 g.WithinFrameScopeWithImplicitWindow = true;
5771 SetNextWindowSize(size: ImVec2(400, 400), cond: ImGuiCond_FirstUseEver);
5772 Begin(name: "Debug##Default");
5773 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5774
5775 // Store stack sizes
5776 g.ErrorCountCurrentFrame = 0;
5777 ErrorRecoveryStoreState(state_out: &g.StackSizesInNewFrame);
5778
5779 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5780 // allowing to validate correct Begin/End behavior in user code.
5781#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5782 if (g.IO.ConfigDebugBeginReturnValueLoop)
5783 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5784 else
5785 g.DebugBeginReturnValueCullDepth = -1;
5786#endif
5787
5788 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePost);
5789}
5790
5791// FIXME: Add a more explicit sort order in the window structure.
5792static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5793{
5794 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5795 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5796 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5797 return d;
5798 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5799 return d;
5800 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5801}
5802
5803static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5804{
5805 out_sorted_windows->push_back(v: window);
5806 if (window->Active)
5807 {
5808 int count = window->DC.ChildWindows.Size;
5809 ImQsort(base: window->DC.ChildWindows.Data, count: (size_t)count, size_of_element: sizeof(ImGuiWindow*), compare_func: ChildWindowComparer);
5810 for (int i = 0; i < count; i++)
5811 {
5812 ImGuiWindow* child = window->DC.ChildWindows[i];
5813 if (child->Active)
5814 AddWindowToSortBuffer(out_sorted_windows, window: child);
5815 }
5816 }
5817}
5818
5819static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5820{
5821 ImGuiContext& g = *GImGui;
5822 ImGuiViewportP* viewport = window->Viewport;
5823 IM_ASSERT(viewport != NULL);
5824 g.IO.MetricsRenderWindows++;
5825 if (window->DrawList->_Splitter._Count > 1)
5826 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5827 ImGui::AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[layer], draw_list: window->DrawList);
5828 for (ImGuiWindow* child : window->DC.ChildWindows)
5829 if (IsWindowActiveAndVisible(window: child)) // Clipped children may have been marked not active
5830 AddWindowToDrawData(window: child, layer);
5831}
5832
5833static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5834{
5835 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5836}
5837
5838// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5839static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5840{
5841 AddWindowToDrawData(window, layer: GetWindowDisplayLayer(window));
5842}
5843
5844static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5845{
5846 int n = builder->Layers[0]->Size;
5847 int full_size = n;
5848 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5849 full_size += builder->Layers[i]->Size;
5850 builder->Layers[0]->resize(new_size: full_size);
5851 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5852 {
5853 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5854 if (layer->empty())
5855 continue;
5856 memcpy(dest: builder->Layers[0]->Data + n, src: layer->Data, n: layer->Size * sizeof(ImDrawList*));
5857 n += layer->Size;
5858 layer->resize(new_size: 0);
5859 }
5860}
5861
5862static void InitViewportDrawData(ImGuiViewportP* viewport)
5863{
5864 ImGuiIO& io = ImGui::GetIO();
5865 ImDrawData* draw_data = &viewport->DrawDataP;
5866
5867 viewport->DrawData = draw_data; // Make publicly accessible
5868 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5869 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5870 viewport->DrawDataBuilder.Layers[0]->resize(new_size: 0);
5871 viewport->DrawDataBuilder.Layers[1]->resize(new_size: 0);
5872
5873 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5874 // and to allow applications/backends to easily skip rendering.
5875 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5876 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5877 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5878 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5879
5880 draw_data->Valid = true;
5881 draw_data->CmdListsCount = 0;
5882 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5883 draw_data->DisplayPos = viewport->Pos;
5884 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5885 draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale;
5886 draw_data->OwnerViewport = viewport;
5887 draw_data->Textures = &ImGui::GetPlatformIO().Textures;
5888}
5889
5890// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5891// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5892// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5893// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5894// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5895// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5896// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
5897// which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
5898void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5899{
5900 ImGuiWindow* window = GetCurrentWindow();
5901 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5902 window->ClipRect = window->DrawList->_ClipRectStack.back();
5903}
5904
5905void ImGui::PopClipRect()
5906{
5907 ImGuiWindow* window = GetCurrentWindow();
5908 window->DrawList->PopClipRect();
5909 window->ClipRect = window->DrawList->_ClipRectStack.back();
5910}
5911
5912static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5913{
5914 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5915 if (IsWindowActiveAndVisible(window: window->DC.ChildWindows[n]))
5916 return FindFrontMostVisibleChildWindow(window: window->DC.ChildWindows[n]);
5917 return window;
5918}
5919
5920static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5921{
5922 if ((col & IM_COL32_A_MASK) == 0)
5923 return;
5924
5925 ImGuiViewportP* viewport = window->Viewport;
5926 ImRect viewport_rect = viewport->GetMainRect();
5927
5928 // Draw behind window by moving the draw command at the FRONT of the draw list
5929 {
5930 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5931 // 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.
5932 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5933 draw_list->ChannelsMerge();
5934 if (draw_list->CmdBuffer.Size == 0)
5935 draw_list->AddDrawCmd();
5936 draw_list->PushClipRect(clip_rect_min: viewport_rect.Min - ImVec2(1, 1), clip_rect_max: viewport_rect.Max + ImVec2(1, 1), intersect_with_current_clip_rect: false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5937 draw_list->AddRectFilled(p_min: viewport_rect.Min, p_max: viewport_rect.Max, col);
5938 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5939 IM_ASSERT(cmd.ElemCount == 6);
5940 draw_list->CmdBuffer.pop_back();
5941 draw_list->CmdBuffer.push_front(v: cmd);
5942 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5943 draw_list->PopClipRect();
5944 }
5945
5946 // Draw over sibling docking nodes in a same docking tree
5947 if (window->RootWindow->DockIsActive)
5948 {
5949 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window: window->RootWindowDockTree)->DrawList;
5950 draw_list->ChannelsMerge();
5951 if (draw_list->CmdBuffer.Size == 0)
5952 draw_list->AddDrawCmd();
5953 draw_list->PushClipRect(clip_rect_min: viewport_rect.Min, clip_rect_max: viewport_rect.Max, intersect_with_current_clip_rect: false);
5954 RenderRectFilledWithHole(draw_list, outer: window->RootWindowDockTree->Rect(), inner: window->RootWindow->Rect(), col, rounding: 0.0f);// window->RootWindowDockTree->WindowRounding);
5955 draw_list->PopClipRect();
5956 }
5957}
5958
5959ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5960{
5961 ImGuiContext& g = *GImGui;
5962 ImGuiWindow* bottom_most_visible_window = parent_window;
5963 for (int i = FindWindowDisplayIndex(window: parent_window); i >= 0; i--)
5964 {
5965 ImGuiWindow* window = g.Windows[i];
5966 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5967 continue;
5968 if (!IsWindowWithinBeginStackOf(window, potential_parent: parent_window))
5969 break;
5970 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(window: parent_window))
5971 bottom_most_visible_window = window;
5972 }
5973 return bottom_most_visible_window;
5974}
5975
5976// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5977// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5978static void ImGui::RenderDimmedBackgrounds()
5979{
5980 ImGuiContext& g = *GImGui;
5981 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5982 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5983 return;
5984 const bool dim_bg_for_modal = (modal_window != NULL);
5985 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5986 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5987 return;
5988
5989 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5990 if (dim_bg_for_modal)
5991 {
5992 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5993 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(parent_window: modal_window);
5994 RenderDimmedBackgroundBehindWindow(window: dim_behind_window, col: GetColorU32(col: modal_window->DC.ModalDimBgColor, alpha_mul: g.DimBgRatio));
5995 viewports_already_dimmed[0] = modal_window->Viewport;
5996 }
5997 else if (dim_bg_for_window_list)
5998 {
5999 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
6000 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingTargetAnim, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
6001 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
6002 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingListWindow, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
6003 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
6004 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
6005
6006 // Draw border around CTRL+Tab target window
6007 ImGuiWindow* window = g.NavWindowingTargetAnim;
6008 ImGuiViewport* viewport = window->Viewport;
6009 float distance = g.FontSize;
6010 ImRect bb = window->Rect();
6011 bb.Expand(amount: distance);
6012 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
6013 bb.Expand(amount: -distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
6014 window->DrawList->ChannelsMerge();
6015 if (window->DrawList->CmdBuffer.Size == 0)
6016 window->DrawList->AddDrawCmd();
6017 window->DrawList->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size);
6018 window->DrawList->AddRect(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_NavWindowingHighlight, alpha_mul: g.NavWindowingHighlightAlpha), rounding: window->WindowRounding, flags: 0, thickness: 3.0f); // FIXME-DPI
6019 window->DrawList->PopClipRect();
6020 }
6021
6022 // Draw dimming background on _other_ viewports than the ones our windows are in
6023 for (ImGuiViewportP* viewport : g.Viewports)
6024 {
6025 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
6026 continue;
6027 if (modal_window && viewport->Window && IsWindowAbove(potential_above: viewport->Window, potential_below: modal_window))
6028 continue;
6029 ImDrawList* draw_list = GetForegroundDrawList(viewport);
6030 const ImU32 dim_bg_col = GetColorU32(idx: dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio);
6031 draw_list->AddRectFilled(p_min: viewport->Pos, p_max: viewport->Pos + viewport->Size, col: dim_bg_col);
6032 }
6033}
6034
6035// 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.
6036void ImGui::EndFrame()
6037{
6038 ImGuiContext& g = *GImGui;
6039 IM_ASSERT(g.Initialized);
6040
6041 // Don't process EndFrame() multiple times.
6042 if (g.FrameCountEnded == g.FrameCount)
6043 return;
6044 if (!g.WithinFrameScope)
6045 {
6046 IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?");
6047 return;
6048 }
6049
6050 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePre);
6051
6052 // [EXPERIMENTAL] Recover from errors
6053 if (g.IO.ConfigErrorRecovery)
6054 ErrorRecoveryTryToRecoverState(state_in: &g.StackSizesInNewFrame);
6055 ErrorCheckEndFrameSanityChecks();
6056 ErrorCheckEndFrameFinalizeErrorTooltip();
6057
6058 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
6059 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
6060 if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(s1: ime_data, s2: &g.PlatformImeDataPrev, n: sizeof(ImGuiPlatformImeData)) != 0)
6061 {
6062 ImGuiViewport* viewport = FindViewportByID(id: ime_data->ViewportId);
6063 IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
6064 if (viewport == NULL)
6065 viewport = GetMainViewport();
6066 g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
6067 }
6068 g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0;
6069
6070 // Hide implicit/fallback "Debug" window if it hasn't been used
6071 g.WithinFrameScopeWithImplicitWindow = false;
6072 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
6073 g.CurrentWindow->Active = false;
6074 End();
6075
6076 // Update navigation: CTRL+Tab, wrap-around requests
6077 NavEndFrame();
6078
6079 // Update docking
6080 DockContextEndFrame(ctx: &g);
6081
6082 SetCurrentViewport(NULL, NULL);
6083
6084 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
6085 if (g.DragDropActive)
6086 {
6087 bool is_delivered = g.DragDropPayload.Delivery;
6088 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(button: g.DragDropMouseButton));
6089 if (is_delivered || is_elapsed)
6090 ClearDragDrop();
6091 }
6092
6093 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
6094 // If you want to handle source item disappearing: instead of submitting your description tooltip
6095 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
6096 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
6097 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
6098 if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
6099 {
6100 g.DragDropWithinSource = true;
6101 SetTooltip("...");
6102 g.DragDropWithinSource = false;
6103 }
6104
6105 // End frame
6106 g.WithinFrameScope = false;
6107 g.FrameCountEnded = g.FrameCount;
6108 UpdateFontsEndFrame();
6109
6110 // Initiate moving window + handle left-click and right-click focus
6111 UpdateMouseMovingWindowEndFrame();
6112
6113 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
6114 UpdateViewportsEndFrame();
6115
6116 // Sort the window list so that all child windows are after their parent
6117 // We cannot do that on FocusWindow() because children may not exist yet
6118 g.WindowsTempSortBuffer.resize(new_size: 0);
6119 g.WindowsTempSortBuffer.reserve(new_capacity: g.Windows.Size);
6120 for (ImGuiWindow* window : g.Windows)
6121 {
6122 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
6123 continue;
6124 AddWindowToSortBuffer(out_sorted_windows: &g.WindowsTempSortBuffer, window);
6125 }
6126
6127 // 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.
6128 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
6129 g.Windows.swap(rhs&: g.WindowsTempSortBuffer);
6130 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
6131
6132 UpdateTexturesEndFrame();
6133
6134 // Unlock font atlas
6135 for (ImFontAtlas* atlas : g.FontAtlases)
6136 atlas->Locked = false;
6137
6138 // Clear Input data for next frame
6139 g.IO.MousePosPrev = g.IO.MousePos;
6140 g.IO.AppFocusLost = false;
6141 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
6142 g.IO.InputQueueCharacters.resize(new_size: 0);
6143
6144 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePost);
6145}
6146
6147// Prepare the data for rendering so you can call GetDrawData()
6148// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all:
6149// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
6150void ImGui::Render()
6151{
6152 ImGuiContext& g = *GImGui;
6153 IM_ASSERT(g.Initialized);
6154
6155 if (g.FrameCountEnded != g.FrameCount)
6156 EndFrame();
6157 if (g.FrameCountRendered == g.FrameCount)
6158 return;
6159 g.FrameCountRendered = g.FrameCount;
6160
6161 g.IO.MetricsRenderWindows = 0;
6162 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPre);
6163
6164 // Add background ImDrawList (for each active viewport)
6165 for (ImGuiViewportP* viewport : g.Viewports)
6166 {
6167 InitViewportDrawData(viewport);
6168 if (viewport->BgFgDrawLists[0] != NULL)
6169 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetBackgroundDrawList(viewport));
6170 }
6171
6172 // Draw modal/window whitening backgrounds
6173 RenderDimmedBackgrounds();
6174
6175 // Add ImDrawList to render
6176 ImGuiWindow* windows_to_render_top_most[2];
6177 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
6178 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
6179 for (ImGuiWindow* window : g.Windows)
6180 {
6181 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
6182 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
6183 AddRootWindowToDrawData(window);
6184 }
6185 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
6186 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(window: windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
6187 AddRootWindowToDrawData(window: windows_to_render_top_most[n]);
6188
6189 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
6190 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
6191 RenderMouseCursor(base_pos: g.IO.MousePos, base_scale: g.Style.MouseCursorScale, mouse_cursor: g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
6192
6193 // Setup ImDrawData structures for end-user
6194 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
6195 for (ImGuiViewportP* viewport : g.Viewports)
6196 {
6197 FlattenDrawDataIntoSingleLayer(builder: &viewport->DrawDataBuilder);
6198
6199 // Add foreground ImDrawList (for each active viewport)
6200 if (viewport->BgFgDrawLists[1] != NULL)
6201 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetForegroundDrawList(viewport));
6202
6203 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
6204 ImDrawData* draw_data = &viewport->DrawDataP;
6205 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
6206 for (ImDrawList* draw_list : draw_data->CmdLists)
6207 draw_list->_PopUnusedDrawCmd();
6208
6209 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
6210 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
6211 }
6212
6213#ifndef IMGUI_DISABLE_DEBUG_TOOLS
6214 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
6215 for (ImFontAtlas* atlas : g.FontAtlases)
6216 ImFontAtlasDebugLogTextureRequests(atlas);
6217#endif
6218
6219 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPost);
6220}
6221
6222// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
6223// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
6224ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
6225{
6226 ImGuiContext& g = *GImGui;
6227
6228 const char* text_display_end;
6229 if (hide_text_after_double_hash)
6230 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
6231 else
6232 text_display_end = text_end;
6233
6234 ImFont* font = g.Font;
6235 const float font_size = g.FontSize;
6236 if (text == text_display_end)
6237 return ImVec2(0.0f, font_size);
6238 ImVec2 text_size = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width, text_begin: text, text_end: text_display_end, NULL);
6239
6240 // Round
6241 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
6242 // FIXME: Investigate using ceilf or e.g.
6243 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
6244 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
6245 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
6246
6247 return text_size;
6248}
6249
6250// Find window given position, search front-to-back
6251// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
6252// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
6253// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
6254// called, aka before the next Begin(). Moving window isn't affected.
6255// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
6256void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
6257{
6258 ImGuiContext& g = *GImGui;
6259 ImGuiWindow* hovered_window = NULL;
6260 ImGuiWindow* hovered_window_under_moving_window = NULL;
6261
6262 // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
6263 ImGuiViewportP* backup_moving_window_viewport = NULL;
6264 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6265 {
6266 backup_moving_window_viewport = g.MovingWindow->Viewport;
6267 g.MovingWindow->Viewport = g.MouseViewport;
6268 if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
6269 hovered_window = g.MovingWindow;
6270 }
6271
6272 ImVec2 padding_regular = g.Style.TouchExtraPadding;
6273 ImVec2 padding_for_resize = ImMax(lhs: g.Style.TouchExtraPadding, rhs: ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding));
6274 for (int i = g.Windows.Size - 1; i >= 0; i--)
6275 {
6276 ImGuiWindow* window = g.Windows[i];
6277 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6278 if (!window->WasActive || window->Hidden)
6279 continue;
6280 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
6281 continue;
6282 IM_ASSERT(window->Viewport);
6283 if (window->Viewport != g.MouseViewport)
6284 continue;
6285
6286 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
6287 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
6288 if (!window->OuterRectClipped.ContainsWithPad(p: pos, pad: hit_padding))
6289 continue;
6290
6291 // Support for one rectangular hole in any given window
6292 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
6293 if (window->HitTestHoleSize.x != 0)
6294 {
6295 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
6296 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
6297 if (ImRect(hole_pos, hole_pos + hole_size).Contains(p: pos))
6298 continue;
6299 }
6300
6301 if (find_first_and_in_any_viewport)
6302 {
6303 hovered_window = window;
6304 break;
6305 }
6306 else
6307 {
6308 if (hovered_window == NULL)
6309 hovered_window = window;
6310 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6311 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
6312 hovered_window_under_moving_window = window;
6313 if (hovered_window && hovered_window_under_moving_window)
6314 break;
6315 }
6316 }
6317
6318 *out_hovered_window = hovered_window;
6319 if (out_hovered_window_under_moving_window != NULL)
6320 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
6321 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6322 g.MovingWindow->Viewport = backup_moving_window_viewport;
6323}
6324
6325bool ImGui::IsItemActive()
6326{
6327 ImGuiContext& g = *GImGui;
6328 if (g.ActiveId)
6329 return g.ActiveId == g.LastItemData.ID;
6330 return false;
6331}
6332
6333bool ImGui::IsItemActivated()
6334{
6335 ImGuiContext& g = *GImGui;
6336 if (g.ActiveId)
6337 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
6338 return true;
6339 return false;
6340}
6341
6342bool ImGui::IsItemDeactivated()
6343{
6344 ImGuiContext& g = *GImGui;
6345 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
6346 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
6347 return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount);
6348}
6349
6350bool ImGui::IsItemDeactivatedAfterEdit()
6351{
6352 ImGuiContext& g = *GImGui;
6353 return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore;
6354}
6355
6356// == (GetItemID() == GetFocusID() && GetFocusID() != 0)
6357bool ImGui::IsItemFocused()
6358{
6359 ImGuiContext& g = *GImGui;
6360 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
6361 return false;
6362
6363 // Special handling for the dummy item after Begin() which represent the title bar or tab.
6364 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
6365 ImGuiWindow* window = g.CurrentWindow;
6366 if (g.LastItemData.ID == window->ID && window->WriteAccessed)
6367 return false;
6368
6369 return true;
6370}
6371
6372// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
6373// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
6374bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
6375{
6376 return IsMouseClicked(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_None);
6377}
6378
6379bool ImGui::IsItemToggledOpen()
6380{
6381 ImGuiContext& g = *GImGui;
6382 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
6383}
6384
6385// Call after a Selectable() or TreeNode() involved in multi-selection.
6386// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
6387// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
6388// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
6389// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
6390bool ImGui::IsItemToggledSelection()
6391{
6392 ImGuiContext& g = *GImGui;
6393 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
6394 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
6395}
6396
6397// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
6398// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
6399// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
6400bool ImGui::IsAnyItemHovered()
6401{
6402 ImGuiContext& g = *GImGui;
6403 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
6404}
6405
6406bool ImGui::IsAnyItemActive()
6407{
6408 ImGuiContext& g = *GImGui;
6409 return g.ActiveId != 0;
6410}
6411
6412bool ImGui::IsAnyItemFocused()
6413{
6414 ImGuiContext& g = *GImGui;
6415 return g.NavId != 0 && g.NavCursorVisible;
6416}
6417
6418bool ImGui::IsItemVisible()
6419{
6420 ImGuiContext& g = *GImGui;
6421 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
6422}
6423
6424bool ImGui::IsItemEdited()
6425{
6426 ImGuiContext& g = *GImGui;
6427 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
6428}
6429
6430// Allow next item to be overlapped by subsequent items.
6431// This works by requiring HoveredId to match for two subsequent frames,
6432// so if a following items overwrite it our interactions will naturally be disabled.
6433void ImGui::SetNextItemAllowOverlap()
6434{
6435 ImGuiContext& g = *GImGui;
6436 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
6437}
6438
6439#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6440// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
6441// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
6442void ImGui::SetItemAllowOverlap()
6443{
6444 ImGuiContext& g = *GImGui;
6445 ImGuiID id = g.LastItemData.ID;
6446 if (g.HoveredId == id)
6447 g.HoveredIdAllowOverlap = true;
6448 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
6449 g.ActiveIdAllowOverlap = true;
6450}
6451#endif
6452
6453// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
6454// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
6455void ImGui::SetActiveIdUsingAllKeyboardKeys()
6456{
6457 ImGuiContext& g = *GImGui;
6458 IM_ASSERT(g.ActiveId != 0);
6459 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
6460 g.ActiveIdUsingAllKeyboardKeys = true;
6461 NavMoveRequestCancel();
6462}
6463
6464ImGuiID ImGui::GetItemID()
6465{
6466 ImGuiContext& g = *GImGui;
6467 return g.LastItemData.ID;
6468}
6469
6470ImVec2 ImGui::GetItemRectMin()
6471{
6472 ImGuiContext& g = *GImGui;
6473 return g.LastItemData.Rect.Min;
6474}
6475
6476ImVec2 ImGui::GetItemRectMax()
6477{
6478 ImGuiContext& g = *GImGui;
6479 return g.LastItemData.Rect.Max;
6480}
6481
6482ImVec2 ImGui::GetItemRectSize()
6483{
6484 ImGuiContext& g = *GImGui;
6485 return g.LastItemData.Rect.GetSize();
6486}
6487
6488// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
6489// ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
6490bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6491{
6492 ImGuiID id = GetCurrentWindow()->GetID(str: str_id);
6493 return BeginChildEx(name: str_id, id, size_arg, child_flags, window_flags);
6494}
6495
6496bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6497{
6498 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
6499}
6500
6501bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6502{
6503 ImGuiContext& g = *GImGui;
6504 ImGuiWindow* parent_window = g.CurrentWindow;
6505 IM_ASSERT(id != 0);
6506
6507 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
6508 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
6509 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
6510 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
6511 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
6512 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
6513 {
6514 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6515 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6516 }
6517#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6518 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
6519 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
6520 if (window_flags & ImGuiWindowFlags_NavFlattened)
6521 child_flags |= ImGuiChildFlags_NavFlattened;
6522#endif
6523 if (child_flags & ImGuiChildFlags_AutoResizeX)
6524 child_flags &= ~ImGuiChildFlags_ResizeX;
6525 if (child_flags & ImGuiChildFlags_AutoResizeY)
6526 child_flags &= ~ImGuiChildFlags_ResizeY;
6527
6528 // Set window flags
6529 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
6530 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
6531 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
6532 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
6533 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
6534 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
6535
6536 // Special framed style
6537 if (child_flags & ImGuiChildFlags_FrameStyle)
6538 {
6539 PushStyleColor(idx: ImGuiCol_ChildBg, col: g.Style.Colors[ImGuiCol_FrameBg]);
6540 PushStyleVar(idx: ImGuiStyleVar_ChildRounding, val: g.Style.FrameRounding);
6541 PushStyleVar(idx: ImGuiStyleVar_ChildBorderSize, val: g.Style.FrameBorderSize);
6542 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.FramePadding);
6543 child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding;
6544 window_flags |= ImGuiWindowFlags_NoMove;
6545 }
6546
6547 // Forward size
6548 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
6549 // (the alternative would to store conditional flags per axis, which is possible but more code)
6550 const ImVec2 size_avail = GetContentRegionAvail();
6551 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
6552 ImVec2 size = CalcItemSize(size: size_arg, default_w: size_default.x, default_h: size_default.y);
6553
6554 // A SetNextWindowSize() call always has priority (#8020)
6555 // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
6556 // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
6557 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
6558 {
6559 if (g.NextWindowData.SizeVal.x > 0.0f)
6560 {
6561 size.x = g.NextWindowData.SizeVal.x;
6562 child_flags &= ~ImGuiChildFlags_ResizeX;
6563 }
6564 if (g.NextWindowData.SizeVal.y > 0.0f)
6565 {
6566 size.y = g.NextWindowData.SizeVal.y;
6567 child_flags &= ~ImGuiChildFlags_ResizeY;
6568 }
6569 }
6570 SetNextWindowSize(size);
6571
6572 // Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
6573 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
6574 g.NextWindowData.ChildFlags |= child_flags;
6575 else
6576 g.NextWindowData.ChildFlags = child_flags;
6577 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
6578
6579 // 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.
6580 // 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.
6581 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
6582 const char* temp_window_name;
6583 /*if (name && parent_window->IDStack.back() == parent_window->ID)
6584 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
6585 else*/
6586 if (name)
6587 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%s_%08X", parent_window->Name, name, id);
6588 else
6589 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%08X", parent_window->Name, id);
6590
6591 // Set style
6592 const float backup_border_size = g.Style.ChildBorderSize;
6593 if ((child_flags & ImGuiChildFlags_Borders) == 0)
6594 g.Style.ChildBorderSize = 0.0f;
6595
6596 // Begin into window
6597 const bool ret = Begin(name: temp_window_name, NULL, flags: window_flags);
6598
6599 // Restore style
6600 g.Style.ChildBorderSize = backup_border_size;
6601 if (child_flags & ImGuiChildFlags_FrameStyle)
6602 {
6603 PopStyleVar(count: 3);
6604 PopStyleColor();
6605 }
6606
6607 ImGuiWindow* child_window = g.CurrentWindow;
6608 child_window->ChildId = id;
6609
6610 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
6611 // While this is not really documented/defined, it seems that the expected thing to do.
6612 if (child_window->BeginCount == 1)
6613 parent_window->DC.CursorPos = child_window->Pos;
6614
6615 // Process navigation-in immediately so NavInit can run on first frame
6616 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
6617 const ImGuiID temp_id_for_activation = ImHashStr(data_p: "##Child", data_size: 0, seed: id);
6618 if (g.ActiveId == temp_id_for_activation)
6619 ClearActiveID();
6620 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
6621 {
6622 FocusWindow(window: child_window);
6623 NavInitWindow(window: child_window, force_reinit: false);
6624 SetActiveID(id: temp_id_for_activation, window: child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
6625 g.ActiveIdSource = g.NavInputSource;
6626 }
6627 return ret;
6628}
6629
6630void ImGui::EndChild()
6631{
6632 ImGuiContext& g = *GImGui;
6633 ImGuiWindow* child_window = g.CurrentWindow;
6634
6635 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
6636 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
6637
6638 g.WithinEndChildID = child_window->ID;
6639 ImVec2 child_size = child_window->Size;
6640 End();
6641 if (child_window->BeginCount == 1)
6642 {
6643 ImGuiWindow* parent_window = g.CurrentWindow;
6644 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
6645 ItemSize(size: child_size);
6646 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
6647 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
6648 {
6649 ItemAdd(bb, id: child_window->ChildId);
6650 RenderNavCursor(bb, id: child_window->ChildId);
6651
6652 // 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)
6653 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
6654 RenderNavCursor(bb: ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), id: g.NavId, flags: ImGuiNavRenderCursorFlags_Compact);
6655 }
6656 else
6657 {
6658 // Not navigable into
6659 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
6660 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
6661 ItemAdd(bb, id: child_window->ChildId, NULL, extra_flags: ImGuiItemFlags_NoNav);
6662
6663 // But when flattened we directly reach items, adjust active layer mask accordingly
6664 if (nav_flattened)
6665 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6666 }
6667 if (g.HoveredWindow == child_window)
6668 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6669 child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags;
6670 //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd()
6671 }
6672 else
6673 {
6674 SetLastItemDataForChildWindowItem(window: child_window, rect: child_window->Rect());
6675 }
6676
6677 g.WithinEndChildID = backup_within_end_child_id;
6678 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6679}
6680
6681static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6682{
6683 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
6684 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
6685 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6686 window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
6687}
6688
6689ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6690{
6691 ImGuiContext& g = *GImGui;
6692 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(key: id);
6693}
6694
6695ImGuiWindow* ImGui::FindWindowByName(const char* name)
6696{
6697 ImGuiID id = ImHashStr(data_p: name);
6698 return FindWindowByID(id);
6699}
6700
6701static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6702{
6703 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6704 window->ViewportPos = main_viewport->Pos;
6705 if (settings->ViewportId)
6706 {
6707 window->ViewportId = settings->ViewportId;
6708 window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6709 }
6710 window->Pos = ImTrunc(v: ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6711 if (settings->Size.x > 0 && settings->Size.y > 0)
6712 window->Size = window->SizeFull = ImTrunc(v: ImVec2(settings->Size.x, settings->Size.y));
6713 window->Collapsed = settings->Collapsed;
6714 window->DockId = settings->DockId;
6715 window->DockOrder = settings->DockOrder;
6716}
6717
6718static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6719{
6720 // Initial window state with e.g. default/arbitrary window position
6721 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6722 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6723 window->Pos = main_viewport->Pos + ImVec2(60, 60);
6724 window->Size = window->SizeFull = ImVec2(0, 0);
6725 window->ViewportPos = main_viewport->Pos;
6726 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6727
6728 if (settings != NULL)
6729 {
6730 SetWindowConditionAllowFlags(window, flags: ImGuiCond_FirstUseEver, enabled: false);
6731 ApplyWindowSettings(window, settings);
6732 }
6733 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6734
6735 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6736 {
6737 window->AutoFitFramesX = window->AutoFitFramesY = 2;
6738 window->AutoFitOnlyGrows = false;
6739 }
6740 else
6741 {
6742 if (window->Size.x <= 0.0f)
6743 window->AutoFitFramesX = 2;
6744 if (window->Size.y <= 0.0f)
6745 window->AutoFitFramesY = 2;
6746 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6747 }
6748}
6749
6750static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6751{
6752 // Create window the first time
6753 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6754 ImGuiContext& g = *GImGui;
6755 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6756 window->Flags = flags;
6757 g.WindowsById.SetVoidPtr(key: window->ID, val: window);
6758
6759 ImGuiWindowSettings* settings = NULL;
6760 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6761 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6762 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
6763
6764 InitOrLoadWindowSettings(window, settings);
6765
6766 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6767 g.Windows.push_front(v: window); // Quite slow but rare and only once
6768 else
6769 g.Windows.push_back(v: window);
6770
6771 return window;
6772}
6773
6774static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6775{
6776 return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6777}
6778
6779static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6780{
6781 return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6782}
6783
6784static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6785{
6786 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6787 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6788 // Perhaps should tend further a neater test for this.
6789 ImGuiContext& g = *GImGui;
6790 ImVec2 size_min;
6791 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6792 {
6793 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6794 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6795 }
6796 else
6797 {
6798 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6799 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6800 }
6801
6802 // Reduce artifacts with very small windows
6803 ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6804 size_min.y = ImMax(lhs: size_min.y, rhs: window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(lhs: 0.0f, rhs: g.Style.WindowRounding - 1.0f));
6805 return size_min;
6806}
6807
6808static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6809{
6810 ImGuiContext& g = *GImGui;
6811 ImVec2 new_size = size_desired;
6812 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6813 {
6814 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6815 ImRect cr = g.NextWindowData.SizeConstraintRect;
6816 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(v: new_size.x, mn: cr.Min.x, mx: cr.Max.x) : window->SizeFull.x;
6817 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(v: new_size.y, mn: cr.Min.y, mx: cr.Max.y) : window->SizeFull.y;
6818 if (g.NextWindowData.SizeCallback)
6819 {
6820 ImGuiSizeCallbackData data;
6821 data.UserData = g.NextWindowData.SizeCallbackUserData;
6822 data.Pos = window->Pos;
6823 data.CurrentSize = window->SizeFull;
6824 data.DesiredSize = new_size;
6825 g.NextWindowData.SizeCallback(&data);
6826 new_size = data.DesiredSize;
6827 }
6828 new_size.x = IM_TRUNC(new_size.x);
6829 new_size.y = IM_TRUNC(new_size.y);
6830 }
6831
6832 // Minimum size
6833 ImVec2 size_min = CalcWindowMinSize(window);
6834 return ImMax(lhs: new_size, rhs: size_min);
6835}
6836
6837static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6838{
6839 bool preserve_old_content_sizes = false;
6840 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6841 preserve_old_content_sizes = true;
6842 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6843 preserve_old_content_sizes = true;
6844 if (preserve_old_content_sizes)
6845 {
6846 *content_size_current = window->ContentSize;
6847 *content_size_ideal = window->ContentSizeIdeal;
6848 return;
6849 }
6850
6851 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(f: window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6852 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(f: window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6853 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(f: ImMax(lhs: window->DC.CursorMaxPos.x, rhs: window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6854 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(f: ImMax(lhs: window->DC.CursorMaxPos.y, rhs: window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6855}
6856
6857static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6858{
6859 ImGuiContext& g = *GImGui;
6860 ImGuiStyle& style = g.Style;
6861 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6862 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6863 ImVec2 size_pad = window->WindowPadding * 2.0f;
6864 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6865
6866 // Determine maximum window size
6867 // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6868 ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6869 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6870 {
6871 if (!window->ViewportOwned)
6872 size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6873 const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6874 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6875 size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6876 }
6877
6878 if (window->Flags & ImGuiWindowFlags_Tooltip)
6879 {
6880 // Tooltip always resize (up to maximum size)
6881 return ImMin(lhs: size_desired, rhs: size_max);
6882 }
6883 else
6884 {
6885 ImVec2 size_min = CalcWindowMinSize(window);
6886 ImVec2 size_auto_fit = ImClamp(v: size_desired, mn: ImMin(lhs: size_min, rhs: size_max), mx: size_max);
6887
6888 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6889 // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6890 // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6891 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY)))
6892 size_auto_fit.y = window->SizeFull.y;
6893 else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX)))
6894 size_auto_fit.x = window->SizeFull.x;
6895
6896 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6897 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6898 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6899 bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6900 bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6901 if (will_have_scrollbar_x)
6902 size_auto_fit.y += style.ScrollbarSize;
6903 if (will_have_scrollbar_y)
6904 size_auto_fit.x += style.ScrollbarSize;
6905 return size_auto_fit;
6906 }
6907}
6908
6909ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6910{
6911 ImVec2 size_contents_current;
6912 ImVec2 size_contents_ideal;
6913 CalcWindowContentSizes(window, content_size_current: &size_contents_current, content_size_ideal: &size_contents_ideal);
6914 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: size_contents_ideal);
6915 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6916 return size_final;
6917}
6918
6919static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6920{
6921 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6922 return ImGuiCol_PopupBg;
6923 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6924 return ImGuiCol_ChildBg;
6925 return ImGuiCol_WindowBg;
6926}
6927
6928static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6929{
6930 ImVec2 pos_min = ImLerp(a: corner_target, b: window->Pos, t: corner_norm); // Expected window upper-left
6931 ImVec2 pos_max = ImLerp(a: window->Pos + window->Size, b: corner_target, t: corner_norm); // Expected window lower-right
6932 ImVec2 size_expected = pos_max - pos_min;
6933 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_desired: size_expected);
6934 *out_pos = pos_min;
6935 if (corner_norm.x == 0.0f)
6936 out_pos->x -= (size_constrained.x - size_expected.x);
6937 if (corner_norm.y == 0.0f)
6938 out_pos->y -= (size_constrained.y - size_expected.y);
6939 *out_size = size_constrained;
6940}
6941
6942// Data for resizing from resize grip / corner
6943struct ImGuiResizeGripDef
6944{
6945 ImVec2 CornerPosN;
6946 ImVec2 InnerDir;
6947 int AngleMin12, AngleMax12;
6948};
6949static const ImGuiResizeGripDef resize_grip_def[4] =
6950{
6951 { .CornerPosN: ImVec2(1, 1), .InnerDir: ImVec2(-1, -1), .AngleMin12: 0, .AngleMax12: 3 }, // Lower-right
6952 { .CornerPosN: ImVec2(0, 1), .InnerDir: ImVec2(+1, -1), .AngleMin12: 3, .AngleMax12: 6 }, // Lower-left
6953 { .CornerPosN: ImVec2(0, 0), .InnerDir: ImVec2(+1, +1), .AngleMin12: 6, .AngleMax12: 9 }, // Upper-left (Unused)
6954 { .CornerPosN: ImVec2(1, 0), .InnerDir: ImVec2(-1, +1), .AngleMin12: 9, .AngleMax12: 12 } // Upper-right (Unused)
6955};
6956
6957// Data for resizing from borders
6958struct ImGuiResizeBorderDef
6959{
6960 ImVec2 InnerDir; // Normal toward inside
6961 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6962 float OuterAngle; // Angle toward outside
6963};
6964static const ImGuiResizeBorderDef resize_border_def[4] =
6965{
6966 { .InnerDir: ImVec2(+1, 0), .SegmentN1: ImVec2(0, 1), .SegmentN2: ImVec2(0, 0), IM_PI * 1.00f }, // Left
6967 { .InnerDir: ImVec2(-1, 0), .SegmentN1: ImVec2(1, 0), .SegmentN2: ImVec2(1, 1), IM_PI * 0.00f }, // Right
6968 { .InnerDir: ImVec2(0, +1), .SegmentN1: ImVec2(0, 0), .SegmentN2: ImVec2(1, 0), IM_PI * 1.50f }, // Up
6969 { .InnerDir: ImVec2(0, -1), .SegmentN1: ImVec2(1, 1), .SegmentN2: ImVec2(0, 1), IM_PI * 0.50f } // Down
6970};
6971
6972static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6973{
6974 ImRect rect = window->Rect();
6975 if (thickness == 0.0f)
6976 rect.Max -= ImVec2(1, 1);
6977 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); }
6978 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); }
6979 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); }
6980 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); }
6981 IM_ASSERT(0);
6982 return ImRect();
6983}
6984
6985// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6986ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6987{
6988 IM_ASSERT(n >= 0 && n < 4);
6989 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6990 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
6991 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
6992 return id;
6993}
6994
6995// Borders (Left, Right, Up, Down)
6996ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6997{
6998 IM_ASSERT(dir >= 0 && dir < 4);
6999 int n = (int)dir + 4;
7000 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
7001 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
7002 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
7003 return id;
7004}
7005
7006// Handle resize for: Resize Grips, Borders, Gamepad
7007// Return true when using auto-fit (double-click on resize grip)
7008static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
7009{
7010 ImGuiContext& g = *GImGui;
7011 ImGuiWindowFlags flags = window->Flags;
7012
7013 if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7014 return false;
7015 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
7016 return false;
7017 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
7018 return false;
7019
7020 int ret_auto_fit_mask = 0x00;
7021 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7022 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
7023 const float grip_hover_outer_size = g.WindowsBorderHoverPadding;
7024
7025 ImRect clamp_rect = visibility_rect;
7026 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
7027 if (window_move_from_title_bar)
7028 clamp_rect.Min.y -= window->TitleBarHeight;
7029
7030 ImVec2 pos_target(FLT_MAX, FLT_MAX);
7031 ImVec2 size_target(FLT_MAX, FLT_MAX);
7032
7033 // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
7034 // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
7035 // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
7036 // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
7037 // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
7038 // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
7039 const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
7040 if (clip_with_viewport_rect)
7041 window->ClipRect = window->Viewport->GetMainRect();
7042
7043 // Resize grips and borders are on layer 1
7044 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7045
7046 // Manual resize grips
7047 PushID(str_id: "#RESIZE");
7048 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7049 {
7050 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
7051 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: def.CornerPosN);
7052
7053 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
7054 bool hovered, held;
7055 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
7056 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(a&: resize_rect.Min.x, b&: resize_rect.Max.x);
7057 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(a&: resize_rect.Min.y, b&: resize_rect.Max.y);
7058 ImGuiID resize_grip_id = window->GetID(n: resize_grip_n); // == GetWindowResizeCornerID()
7059 ItemAdd(bb: resize_rect, id: resize_grip_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
7060 ButtonBehavior(bb: resize_rect, id: resize_grip_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7061 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
7062 if (hovered || held)
7063 SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
7064
7065 if (held && g.IO.MouseDoubleClicked[0])
7066 {
7067 // Auto-fit when double-clicking
7068 size_target = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
7069 ret_auto_fit_mask = 0x03; // Both axes
7070 ClearActiveID();
7071 }
7072 else if (held)
7073 {
7074 // Resize from any of the four corners
7075 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
7076 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);
7077 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);
7078 ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(a: def.InnerDir * grip_hover_outer_size, b: def.InnerDir * -grip_hover_inner_size, t: def.CornerPosN); // Corner of the window corresponding to our corner grip
7079 corner_target = ImClamp(v: corner_target, mn: clamp_min, mx: clamp_max);
7080 CalcResizePosSizeFromAnyCorner(window, corner_target, corner_norm: def.CornerPosN, out_pos: &pos_target, out_size: &size_target);
7081 }
7082
7083 // Only lower-left grip is visible before hovering/activating
7084 if (resize_grip_n == 0 || held || hovered)
7085 resize_grip_col[resize_grip_n] = GetColorU32(idx: held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
7086 }
7087
7088 int resize_border_mask = 0x00;
7089 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7090 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
7091 else
7092 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
7093 for (int border_n = 0; border_n < 4; border_n++)
7094 {
7095 if ((resize_border_mask & (1 << border_n)) == 0)
7096 continue;
7097 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7098 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
7099
7100 bool hovered, held;
7101 ImRect border_rect = GetResizeBorderRect(window, border_n, perp_padding: grip_hover_inner_size, thickness: g.WindowsBorderHoverPadding);
7102 ImGuiID border_id = window->GetID(n: border_n + 4); // == GetWindowResizeBorderID()
7103 ItemAdd(bb: border_rect, id: border_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
7104 ButtonBehavior(bb: border_rect, id: border_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7105 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
7106 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
7107 hovered = false;
7108 if (hovered || held)
7109 SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
7110 if (held && g.IO.MouseDoubleClicked[0])
7111 {
7112 // Double-clicking bottom or right border auto-fit on this axis
7113 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
7114 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
7115 if (border_n == 1 || border_n == 3) // Right and bottom border
7116 {
7117 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit)[axis];
7118 ret_auto_fit_mask |= (1 << axis);
7119 hovered = held = false; // So border doesn't show highlighted at new position
7120 }
7121 ClearActiveID();
7122 }
7123 else if (held)
7124 {
7125 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
7126 // 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.
7127 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
7128 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, potential_parent: g.WheelingWindow, popup_hierarchy: false, dock_hierarchy: true));
7129 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
7130 {
7131 g.WindowResizeBorderExpectedRect = border_rect;
7132 g.WindowResizeRelativeMode = false;
7133 }
7134 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(s1: &g.WindowResizeBorderExpectedRect, s2: &border_rect, n: sizeof(ImRect)) != 0)
7135 g.WindowResizeRelativeMode = true;
7136
7137 const ImVec2 border_curr = (window->Pos + ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2) * window->Size);
7138 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
7139 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above.
7140
7141 // Use absolute mode position
7142 ImVec2 border_target = window->Pos;
7143 border_target[axis] = border_target_abs_mode_for_axis;
7144
7145 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
7146 bool ignore_resize = false;
7147 if (g.WindowResizeRelativeMode)
7148 {
7149 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
7150 border_target[axis] = border_target_rel_mode_for_axis;
7151 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))
7152 ignore_resize = true;
7153 }
7154
7155 // Clamp, apply
7156 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);
7157 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
7158 border_target = ImClamp(v: border_target, mn: clamp_min, mx: clamp_max);
7159 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
7160 {
7161 ImGuiWindow* parent_window = window->ParentWindow;
7162 ImGuiWindowFlags parent_flags = parent_window->Flags;
7163 ImRect border_limit_rect = parent_window->InnerRect;
7164 border_limit_rect.Expand(amount: ImVec2(-ImMax(lhs: parent_window->WindowPadding.x, rhs: parent_window->WindowBorderSize), -ImMax(lhs: parent_window->WindowPadding.y, rhs: parent_window->WindowBorderSize)));
7165 if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
7166 border_target.x = ImClamp(v: border_target.x, mn: border_limit_rect.Min.x, mx: border_limit_rect.Max.x);
7167 if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
7168 border_target.y = ImClamp(v: border_target.y, mn: border_limit_rect.Min.y, mx: border_limit_rect.Max.y);
7169 }
7170 if (!ignore_resize)
7171 CalcResizePosSizeFromAnyCorner(window, corner_target: border_target, corner_norm: ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2), out_pos: &pos_target, out_size: &size_target);
7172 }
7173 if (hovered)
7174 *border_hovered = border_n;
7175 if (held)
7176 *border_held = border_n;
7177 }
7178 PopID();
7179
7180 // Restore nav layer
7181 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7182
7183 // Navigation resize (keyboard/gamepad)
7184 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
7185 // Not even sure the callback works here.
7186 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
7187 {
7188 ImVec2 nav_resize_dir;
7189 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
7190 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
7191 if (g.NavInputSource == ImGuiInputSource_Gamepad)
7192 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadDpadLeft, key_right: ImGuiKey_GamepadDpadRight, key_up: ImGuiKey_GamepadDpadUp, key_down: ImGuiKey_GamepadDpadDown);
7193 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
7194 {
7195 const float NAV_RESIZE_SPEED = 600.0f;
7196 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(lhs: g.IO.DisplayFramebufferScale.x, rhs: g.IO.DisplayFramebufferScale.y);
7197 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
7198 g.NavWindowingAccumDeltaSize = ImMax(lhs: g.NavWindowingAccumDeltaSize, rhs: 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
7199 g.NavWindowingToggleLayer = false;
7200 g.NavHighlightItemUnderNav = true;
7201 resize_grip_col[0] = GetColorU32(idx: ImGuiCol_ResizeGripActive);
7202 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaSize);
7203 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
7204 {
7205 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
7206 size_target = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull + accum_floored);
7207 g.NavWindowingAccumDeltaSize -= accum_floored;
7208 }
7209 }
7210 }
7211
7212 // Apply back modified position/size to window
7213 const ImVec2 curr_pos = window->Pos;
7214 const ImVec2 curr_size = window->SizeFull;
7215 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
7216 window->Size.x = window->SizeFull.x = size_target.x;
7217 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
7218 window->Size.y = window->SizeFull.y = size_target.y;
7219 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(f: pos_target.x))
7220 window->Pos.x = ImTrunc(f: pos_target.x);
7221 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(f: pos_target.y))
7222 window->Pos.y = ImTrunc(f: pos_target.y);
7223 if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
7224 MarkIniSettingsDirty(window);
7225
7226 // Recalculate next expected border expected coordinates
7227 if (*border_held != -1)
7228 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_n: *border_held, perp_padding: grip_hover_inner_size, thickness: g.WindowsBorderHoverPadding);
7229
7230 return ret_auto_fit_mask;
7231}
7232
7233static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
7234{
7235 ImGuiContext& g = *GImGui;
7236 ImVec2 size_for_clamping = window->Size;
7237 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
7238 size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
7239 else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7240 size_for_clamping.y = window->TitleBarHeight;
7241 window->Pos = ImClamp(v: window->Pos, mn: visibility_rect.Min - size_for_clamping, mx: visibility_rect.Max);
7242}
7243
7244static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
7245{
7246 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7247 const float rounding = window->WindowRounding;
7248 const ImRect border_r = GetResizeBorderRect(window, border_n, perp_padding: rounding, thickness: 0.0f);
7249 window->DrawList->PathArcTo(center: ImLerp(a: border_r.Min, b: border_r.Max, t: def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, radius: rounding, a_min: def.OuterAngle - IM_PI * 0.25f, a_max: def.OuterAngle);
7250 window->DrawList->PathArcTo(center: ImLerp(a: border_r.Min, b: border_r.Max, t: def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, radius: rounding, a_min: def.OuterAngle, a_max: def.OuterAngle + IM_PI * 0.25f);
7251 window->DrawList->PathStroke(col: border_col, flags: ImDrawFlags_None, thickness: border_size);
7252}
7253
7254static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
7255{
7256 ImGuiContext& g = *GImGui;
7257 const float border_size = window->WindowBorderSize;
7258 const ImU32 border_col = GetColorU32(idx: ImGuiCol_Border);
7259 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
7260 window->DrawList->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, col: border_col, rounding: window->WindowRounding, flags: 0, thickness: window->WindowBorderSize);
7261 else if (border_size > 0.0f)
7262 {
7263 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
7264 RenderWindowOuterSingleBorder(window, border_n: 1, border_col, border_size);
7265 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
7266 RenderWindowOuterSingleBorder(window, border_n: 3, border_col, border_size);
7267 }
7268 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
7269 {
7270 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
7271 const ImU32 border_col_resizing = GetColorU32(idx: (window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
7272 RenderWindowOuterSingleBorder(window, border_n, border_col: border_col_resizing, border_size: ImMax(lhs: 2.0f, rhs: window->WindowBorderSize)); // Thicker than usual
7273 }
7274 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7275 {
7276 float y = window->Pos.y + window->TitleBarHeight - 1;
7277 window->DrawList->AddLine(p1: ImVec2(window->Pos.x + border_size * 0.5f, y), p2: ImVec2(window->Pos.x + window->Size.x - border_size * 0.5f, y), col: border_col, thickness: g.Style.FrameBorderSize);
7278 }
7279}
7280
7281// Draw background and borders
7282// Draw and handle scrollbars
7283void 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)
7284{
7285 ImGuiContext& g = *GImGui;
7286 ImGuiStyle& style = g.Style;
7287 ImGuiWindowFlags flags = window->Flags;
7288
7289 // Ensure that Scrollbar() doesn't read last frame's SkipItems
7290 IM_ASSERT(window->BeginCount == 0);
7291 window->SkipItems = false;
7292 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7293
7294 // Draw window + handle manual resize
7295 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
7296 const float window_rounding = window->WindowRounding;
7297 const float window_border_size = window->WindowBorderSize;
7298 if (window->Collapsed)
7299 {
7300 // Title bar only
7301 const float backup_border_size = style.FrameBorderSize;
7302 g.Style.FrameBorderSize = window->WindowBorderSize;
7303 ImU32 title_bar_col = GetColorU32(idx: (title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
7304 if (window->ViewportOwned)
7305 title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
7306 RenderFrame(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, fill_col: title_bar_col, borders: true, rounding: window_rounding);
7307 g.Style.FrameBorderSize = backup_border_size;
7308 }
7309 else
7310 {
7311 // Window background
7312 if (!(flags & ImGuiWindowFlags_NoBackground))
7313 {
7314 bool is_docking_transparent_payload = false;
7315 if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
7316 if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
7317 is_docking_transparent_payload = true;
7318
7319 ImU32 bg_col = GetColorU32(idx: GetWindowBgColorIdx(window));
7320 if (window->ViewportOwned)
7321 {
7322 bg_col |= IM_COL32_A_MASK; // No alpha
7323 if (is_docking_transparent_payload)
7324 window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
7325 }
7326 else
7327 {
7328 // Adjust alpha. For docking
7329 bool override_alpha = false;
7330 float alpha = 1.0f;
7331 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha)
7332 {
7333 alpha = g.NextWindowData.BgAlphaVal;
7334 override_alpha = true;
7335 }
7336 if (is_docking_transparent_payload)
7337 {
7338 alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
7339 override_alpha = true;
7340 }
7341 if (override_alpha)
7342 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
7343 }
7344
7345 // Render, for docked windows and host windows we ensure bg goes before decorations
7346 if (window->DockIsActive)
7347 window->DockNode->LastBgColor = bg_col;
7348 ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
7349 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7350 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
7351 bg_draw_list->AddRectFilled(p_min: window->Pos + ImVec2(0, window->TitleBarHeight), p_max: window->Pos + window->Size, col: bg_col, rounding: window_rounding, flags: (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
7352 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7353 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
7354 }
7355 if (window->DockIsActive)
7356 window->DockNode->IsBgDrawnThisFrame = true;
7357
7358 // Title bar
7359 // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
7360 // in order for their pos/size to be matching their undocking state.)
7361 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7362 {
7363 ImU32 title_bar_col = GetColorU32(idx: title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
7364 if (window->ViewportOwned)
7365 title_bar_col |= IM_COL32_A_MASK; // No alpha
7366 window->DrawList->AddRectFilled(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, col: title_bar_col, rounding: window_rounding, flags: ImDrawFlags_RoundCornersTop);
7367 }
7368
7369 // Menu bar
7370 if (flags & ImGuiWindowFlags_MenuBar)
7371 {
7372 ImRect menu_bar_rect = window->MenuBarRect();
7373 menu_bar_rect.ClipWith(r: window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
7374 window->DrawList->AddRectFilled(p_min: menu_bar_rect.Min, p_max: menu_bar_rect.Max, col: GetColorU32(idx: ImGuiCol_MenuBarBg), rounding: (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, flags: ImDrawFlags_RoundCornersTop);
7375 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
7376 window->DrawList->AddLine(p1: menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), p2: menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), col: GetColorU32(idx: ImGuiCol_Border), thickness: style.FrameBorderSize);
7377 }
7378
7379 // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
7380 ImGuiDockNode* node = window->DockNode;
7381 if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
7382 {
7383 float unhide_sz_draw = ImTrunc(f: g.FontSize * 0.70f);
7384 float unhide_sz_hit = ImTrunc(f: g.FontSize * 0.55f);
7385 ImVec2 p = node->Pos;
7386 ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
7387 ImGuiID unhide_id = window->GetID(str: "#UNHIDE");
7388 KeepAliveID(id: unhide_id);
7389 bool hovered, held;
7390 if (ButtonBehavior(bb: r, id: unhide_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren))
7391 node->WantHiddenTabBarToggle = true;
7392 else if (held && IsMouseDragging(button: 0))
7393 StartMouseMovingWindowOrNode(window, node, undock: true); // Undock from tab-bar triangle = same as window/collapse menu button
7394
7395 // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
7396 ImU32 col = GetColorU32(idx: ((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
7397 window->DrawList->AddTriangleFilled(p1: p, p2: p + ImVec2(unhide_sz_draw, 0.0f), p3: p + ImVec2(0.0f, unhide_sz_draw), col);
7398 }
7399
7400 // Scrollbars
7401 if (window->ScrollbarX)
7402 Scrollbar(axis: ImGuiAxis_X);
7403 if (window->ScrollbarY)
7404 Scrollbar(axis: ImGuiAxis_Y);
7405
7406 // Render resize grips (after their input handling so we don't have a frame of latency)
7407 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
7408 {
7409 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7410 {
7411 const ImU32 col = resize_grip_col[resize_grip_n];
7412 if ((col & IM_COL32_A_MASK) == 0)
7413 continue;
7414 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
7415 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: grip.CornerPosN);
7416 const float border_inner = IM_ROUND(window_border_size * 0.5f);
7417 window->DrawList->PathLineTo(pos: corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner)));
7418 window->DrawList->PathLineTo(pos: corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size)));
7419 window->DrawList->PathArcToFast(center: ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), radius: window_rounding, a_min_of_12: grip.AngleMin12, a_max_of_12: grip.AngleMax12);
7420 window->DrawList->PathFillConvex(col);
7421 }
7422 }
7423
7424 // Borders (for dock node host they will be rendered over after the tab bar)
7425 if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
7426 RenderWindowOuterBorders(window);
7427 }
7428 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7429}
7430
7431// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
7432// Render title text, collapse button, close button
7433void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
7434{
7435 ImGuiContext& g = *GImGui;
7436 ImGuiStyle& style = g.Style;
7437 ImGuiWindowFlags flags = window->Flags;
7438
7439 const bool has_close_button = (p_open != NULL);
7440 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
7441
7442 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
7443 // 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?
7444 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
7445 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
7446 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7447
7448 // Layout buttons
7449 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
7450 float pad_l = style.FramePadding.x;
7451 float pad_r = style.FramePadding.x;
7452 float button_sz = g.FontSize;
7453 ImVec2 close_button_pos;
7454 ImVec2 collapse_button_pos;
7455 if (has_close_button)
7456 {
7457 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7458 pad_r += button_sz + style.ItemInnerSpacing.x;
7459 }
7460 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
7461 {
7462 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7463 pad_r += button_sz + style.ItemInnerSpacing.x;
7464 }
7465 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
7466 {
7467 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
7468 pad_l += button_sz + style.ItemInnerSpacing.x;
7469 }
7470
7471 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
7472 if (has_collapse_button)
7473 if (CollapseButton(id: window->GetID(str: "#COLLAPSE"), pos: collapse_button_pos, NULL))
7474 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
7475
7476 // Close button
7477 if (has_close_button)
7478 {
7479 g.CurrentItemFlags |= ImGuiItemFlags_NoFocus;
7480 if (CloseButton(id: window->GetID(str: "#CLOSE"), pos: close_button_pos))
7481 *p_open = false;
7482 g.CurrentItemFlags &= ~ImGuiItemFlags_NoFocus;
7483 }
7484
7485 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7486 g.CurrentItemFlags = item_flags_backup;
7487
7488 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
7489 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
7490 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
7491 const ImVec2 text_size = CalcTextSize(text: name, NULL, hide_text_after_double_hash: true) + ImVec2(marker_size_x, 0.0f);
7492
7493 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
7494 // while uncentered title text will still reach edges correctly.
7495 if (pad_l > style.FramePadding.x)
7496 pad_l += g.Style.ItemInnerSpacing.x;
7497 if (pad_r > style.FramePadding.x)
7498 pad_r += g.Style.ItemInnerSpacing.x;
7499 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
7500 {
7501 float centerness = ImSaturate(f: 1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
7502 float pad_extend = ImMin(lhs: ImMax(lhs: pad_l, rhs: pad_r), rhs: title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
7503 pad_l = ImMax(lhs: pad_l, rhs: pad_extend * centerness);
7504 pad_r = ImMax(lhs: pad_r, rhs: pad_extend * centerness);
7505 }
7506
7507 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);
7508 ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(lhs: layout_r.Max.x + g.Style.ItemInnerSpacing.x, rhs: title_bar_rect.Max.x), layout_r.Max.y);
7509 if (flags & ImGuiWindowFlags_UnsavedDocument)
7510 {
7511 ImVec2 marker_pos;
7512 marker_pos.x = ImClamp(v: layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, mn: layout_r.Min.x, mx: layout_r.Max.x);
7513 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
7514 if (marker_pos.x > layout_r.Min.x)
7515 {
7516 RenderBullet(draw_list: window->DrawList, pos: marker_pos, col: GetColorU32(idx: ImGuiCol_Text));
7517 clip_r.Max.x = ImMin(lhs: clip_r.Max.x, rhs: marker_pos.x - (int)(marker_size_x * 0.5f));
7518 }
7519 }
7520 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7521 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7522 RenderTextClipped(pos_min: layout_r.Min, pos_max: layout_r.Max, text: name, NULL, text_size_if_known: &text_size, align: style.WindowTitleAlign, clip_rect: &clip_r);
7523}
7524
7525void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
7526{
7527 window->ParentWindow = parent_window;
7528 window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
7529 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
7530 {
7531 window->RootWindowDockTree = parent_window->RootWindowDockTree;
7532 if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
7533 window->RootWindow = parent_window->RootWindow;
7534 }
7535 if (parent_window && (flags & ImGuiWindowFlags_Popup))
7536 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
7537 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
7538 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
7539 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
7540 {
7541 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
7542 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
7543 }
7544}
7545
7546// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
7547// This is designed as a toy/test-bed for
7548void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
7549{
7550 ImGuiContext& g = *GImGui;
7551 window->SkipRefresh = false;
7552 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
7553 return;
7554 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
7555 {
7556 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
7557 if (window->Appearing) // If currently appearing
7558 return;
7559 if (window->Hidden) // If was hidden (previous frame)
7560 return;
7561 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow)
7562 if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(window: g.HoveredWindow->RootWindow, potential_parent: window))
7563 return;
7564 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow)
7565 if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(window: g.NavWindow->RootWindow, potential_parent: window))
7566 return;
7567 window->DrawList = NULL;
7568 window->SkipRefresh = true;
7569 }
7570}
7571
7572static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
7573{
7574 window->Active = true;
7575 for (ImGuiWindow* child : window->DC.ChildWindows)
7576 if (!child->Hidden)
7577 {
7578 child->Active = child->SkipRefresh = true;
7579 SetWindowActiveForSkipRefresh(child);
7580 }
7581}
7582
7583// Push a new Dear ImGui window to add widgets to.
7584// - 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.
7585// - Begin/End can be called multiple times during the frame with the same window name to append content.
7586// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
7587// 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.
7588// - 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.
7589// - 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.
7590bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
7591{
7592 ImGuiContext& g = *GImGui;
7593 const ImGuiStyle& style = g.Style;
7594 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
7595 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
7596 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
7597
7598 // Find or create
7599 ImGuiWindow* window = FindWindowByName(name);
7600 const bool window_just_created = (window == NULL);
7601 if (window_just_created)
7602 window = CreateNewWindow(name, flags);
7603
7604 // [DEBUG] Debug break requested by user
7605 if (g.DebugBreakInWindow == window->ID)
7606 IM_DEBUG_BREAK();
7607
7608 // Automatically disable manual moving/resizing when NoInputs is set
7609 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
7610 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
7611
7612 const int current_frame = g.FrameCount;
7613 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
7614 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
7615
7616 // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
7617 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
7618 if (flags & ImGuiWindowFlags_Popup)
7619 {
7620 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7621 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
7622 window_just_activated_by_user |= (window != popup_ref.Window);
7623 }
7624
7625 // Update Flags, LastFrameActive, BeginOrderXXX fields
7626 const bool window_was_appearing = window->Appearing;
7627 if (first_begin_of_the_frame)
7628 {
7629 UpdateWindowInFocusOrderList(window, just_created: window_just_created, new_flags: flags);
7630 window->Appearing = window_just_activated_by_user;
7631 if (window->Appearing)
7632 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
7633 window->FlagsPreviousFrame = window->Flags;
7634 window->Flags = (ImGuiWindowFlags)flags;
7635 window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7636 window->LastFrameActive = current_frame;
7637 window->LastTimeActive = (float)g.Time;
7638 window->BeginOrderWithinParent = 0;
7639 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7640 }
7641 else
7642 {
7643 flags = window->Flags;
7644 }
7645
7646 // Docking
7647 // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7648 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7649 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasDock)
7650 SetWindowDock(window, dock_id: g.NextWindowData.DockId, cond: g.NextWindowData.DockCond);
7651 if (first_begin_of_the_frame)
7652 {
7653 bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7654 bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7655 bool dock_node_was_visible = window->DockNodeIsVisible;
7656 bool dock_tab_was_visible = window->DockTabIsVisible;
7657 if (has_dock_node || new_auto_dock_node)
7658 {
7659 BeginDocked(window, p_open);
7660 flags = window->Flags;
7661 if (window->DockIsActive)
7662 {
7663 IM_ASSERT(window->DockNode != NULL);
7664 g.NextWindowData.HasFlags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7665 }
7666
7667 // Amend the Appearing flag
7668 if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7669 {
7670 window->Appearing = true;
7671 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
7672 }
7673 }
7674 else
7675 {
7676 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7677 }
7678 }
7679
7680 // 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
7681 ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7682 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7683 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7684
7685 // We allow window memory to be compacted so recreate the base stack when needed.
7686 if (window->IDStack.Size == 0)
7687 window->IDStack.push_back(v: window->ID);
7688
7689 // Add to stack
7690 g.CurrentWindow = window;
7691 g.CurrentWindowStack.resize(new_size: g.CurrentWindowStack.Size + 1);
7692 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7693 window_stack_data.Window = window;
7694 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7695 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7696 window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f;
7697 ErrorRecoveryStoreState(state_out: &window_stack_data.StackSizesInBegin);
7698 g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
7699 if (flags & ImGuiWindowFlags_ChildMenu)
7700 g.BeginMenuDepth++;
7701
7702 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7703 if (first_begin_of_the_frame)
7704 {
7705 UpdateWindowParentAndRootLinks(window, flags, parent_window);
7706 window->ParentWindowInBeginStack = parent_window_in_stack;
7707
7708 // Focus route
7709 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7710 // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7711 window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7712 if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7713 if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7714 window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7715
7716 // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7717 if (window->WindowClass.FocusRouteParentWindowId != 0)
7718 {
7719 window->ParentWindowForFocusRoute = FindWindowByID(id: window->WindowClass.FocusRouteParentWindowId);
7720 IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7721 }
7722
7723 // Inherit SetWindowFontScale() from parent until we fix this system...
7724 window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f;
7725 }
7726
7727 // Add to focus scope stack
7728 PushFocusScope(id: (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7729 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7730
7731 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7732 if (flags & ImGuiWindowFlags_Popup)
7733 {
7734 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7735 popup_ref.Window = window;
7736 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7737 g.BeginPopupStack.push_back(v: popup_ref);
7738 window->PopupId = popup_ref.PopupId;
7739 }
7740
7741 // Process SetNextWindow***() calls
7742 // (FIXME: Consider splitting the HasXXX flags into X/Y components
7743 bool window_pos_set_by_api = false;
7744 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7745 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos)
7746 {
7747 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7748 if (window_pos_set_by_api && ImLengthSqr(lhs: g.NextWindowData.PosPivotVal) > 0.00001f)
7749 {
7750 // May be processed on the next frame if this is our first frame and we are measuring size
7751 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7752 window->SetWindowPosVal = g.NextWindowData.PosVal;
7753 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7754 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7755 }
7756 else
7757 {
7758 SetWindowPos(window, pos: g.NextWindowData.PosVal, cond: g.NextWindowData.PosCond);
7759 }
7760 }
7761 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize)
7762 {
7763 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7764 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7765 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7766 g.NextWindowData.SizeVal.x = window->SizeFull.x;
7767 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7768 g.NextWindowData.SizeVal.y = window->SizeFull.y;
7769 SetWindowSize(window, size: g.NextWindowData.SizeVal, cond: g.NextWindowData.SizeCond);
7770 }
7771 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll)
7772 {
7773 if (g.NextWindowData.ScrollVal.x >= 0.0f)
7774 {
7775 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7776 window->ScrollTargetCenterRatio.x = 0.0f;
7777 }
7778 if (g.NextWindowData.ScrollVal.y >= 0.0f)
7779 {
7780 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7781 window->ScrollTargetCenterRatio.y = 0.0f;
7782 }
7783 }
7784 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize)
7785 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7786 else if (first_begin_of_the_frame)
7787 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7788 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowClass)
7789 window->WindowClass = g.NextWindowData.WindowClass;
7790 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed)
7791 SetWindowCollapsed(window, collapsed: g.NextWindowData.CollapsedVal, cond: g.NextWindowData.CollapsedCond);
7792 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus)
7793 FocusWindow(window);
7794 if (window->Appearing)
7795 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: false);
7796
7797 // [EXPERIMENTAL] Skip Refresh mode
7798 UpdateWindowSkipRefresh(window);
7799
7800 // Nested root windows (typically tooltips) override disabled state
7801 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7802 BeginDisabledOverrideReenable();
7803
7804 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7805 g.CurrentWindow = NULL;
7806
7807 // When reusing window again multiple times a frame, just append content (don't need to setup again)
7808 if (first_begin_of_the_frame && !window->SkipRefresh)
7809 {
7810 // Initialize
7811 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7812 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7813 window->Active = true;
7814 window->HasCloseButton = (p_open != NULL);
7815 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7816 window->IDStack.resize(new_size: 1);
7817 window->DrawList->_ResetForNewFrame();
7818 window->DC.CurrentTableIdx = -1;
7819 if (flags & ImGuiWindowFlags_DockNodeHost)
7820 {
7821 window->DrawList->ChannelsSplit(count: 2);
7822 window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7823 }
7824
7825 // Restore buffer capacity when woken from a compacted state, to avoid
7826 if (window->MemoryCompacted)
7827 GcAwakeTransientWindowBuffers(window);
7828
7829 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7830 // 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.
7831 bool window_title_visible_elsewhere = false;
7832 if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7833 window_title_visible_elsewhere = true;
7834 else if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
7835 window_title_visible_elsewhere = true;
7836 else if (flags & ImGuiWindowFlags_ChildMenu)
7837 window_title_visible_elsewhere = true;
7838 if (window_title_visible_elsewhere && !window_just_created && strcmp(s1: name, s2: window->Name) != 0)
7839 {
7840 size_t buf_len = (size_t)window->NameBufLen;
7841 window->Name = ImStrdupcpy(dst: window->Name, p_dst_size: &buf_len, src: name);
7842 window->NameBufLen = (int)buf_len;
7843 }
7844
7845 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7846
7847 // Update contents size from last frame for auto-fitting (or use explicit size)
7848 CalcWindowContentSizes(window, content_size_current: &window->ContentSize, content_size_ideal: &window->ContentSizeIdeal);
7849
7850 // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7851 // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7852 // it has a single usage before this code block and may be set below before it is finally checked.
7853 if (window->HiddenFramesCanSkipItems > 0)
7854 window->HiddenFramesCanSkipItems--;
7855 if (window->HiddenFramesCannotSkipItems > 0)
7856 window->HiddenFramesCannotSkipItems--;
7857 if (window->HiddenFramesForRenderOnly > 0)
7858 window->HiddenFramesForRenderOnly--;
7859
7860 // Hide new windows for one frame until they calculate their size
7861 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7862 window->HiddenFramesCannotSkipItems = 1;
7863
7864 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7865 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7866 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7867 {
7868 window->HiddenFramesCannotSkipItems = 1;
7869 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7870 {
7871 if (!window_size_x_set_by_api)
7872 window->Size.x = window->SizeFull.x = 0.f;
7873 if (!window_size_y_set_by_api)
7874 window->Size.y = window->SizeFull.y = 0.f;
7875 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7876 }
7877 }
7878
7879 // SELECT VIEWPORT
7880 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7881
7882 WindowSelectViewport(window);
7883 SetCurrentViewport(window, viewport: window->Viewport);
7884 SetCurrentWindow(window);
7885 flags = window->Flags;
7886
7887 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7888 // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7889
7890 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7891 window->WindowBorderSize = style.ChildBorderSize;
7892 else
7893 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7894 window->WindowPadding = style.WindowPadding;
7895 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7896 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7897
7898 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7899 window->DC.MenuBarOffset.x = ImMax(lhs: ImMax(lhs: window->WindowPadding.x, rhs: style.ItemSpacing.x), rhs: g.NextWindowData.MenuBarOffsetMinVal.x);
7900 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7901 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7902 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7903 window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window.
7904
7905 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7906 // Those flags will be altered further down in the function depending on more conditions.
7907 bool use_current_size_for_scrollbar_x = window_just_created;
7908 bool use_current_size_for_scrollbar_y = window_just_created;
7909 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7910 use_current_size_for_scrollbar_x = true;
7911 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7912 use_current_size_for_scrollbar_y = true;
7913
7914 // Collapse window by double-clicking on title bar
7915 // 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
7916 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7917 {
7918 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
7919 // so verify that we don't have items over the title bar.
7920 ImRect title_bar_rect = window->TitleBarRect();
7921 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max))
7922 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(key: ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7923 window->WantCollapseToggle = true;
7924 if (window->WantCollapseToggle)
7925 {
7926 window->Collapsed = !window->Collapsed;
7927 if (!window->Collapsed)
7928 use_current_size_for_scrollbar_y = true;
7929 MarkIniSettingsDirty(window);
7930 }
7931 }
7932 else
7933 {
7934 window->Collapsed = false;
7935 }
7936 window->WantCollapseToggle = false;
7937
7938 // SIZE
7939
7940 // Outer Decoration Sizes
7941 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7942 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7943 window->DecoOuterSizeX1 = 0.0f;
7944 window->DecoOuterSizeX2 = 0.0f;
7945 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7946 window->DecoOuterSizeY2 = 0.0f;
7947 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7948
7949 // Calculate auto-fit size, handle automatic resize
7950 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: window->ContentSizeIdeal);
7951 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7952 {
7953 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7954 if (!window_size_x_set_by_api)
7955 {
7956 window->SizeFull.x = size_auto_fit.x;
7957 use_current_size_for_scrollbar_x = true;
7958 }
7959 if (!window_size_y_set_by_api)
7960 {
7961 window->SizeFull.y = size_auto_fit.y;
7962 use_current_size_for_scrollbar_y = true;
7963 }
7964 }
7965 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7966 {
7967 // Auto-fit may only grow window during the first few frames
7968 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7969 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7970 {
7971 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.x, rhs: size_auto_fit.x) : size_auto_fit.x;
7972 use_current_size_for_scrollbar_x = true;
7973 }
7974 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7975 {
7976 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.y, rhs: size_auto_fit.y) : size_auto_fit.y;
7977 use_current_size_for_scrollbar_y = true;
7978 }
7979 if (!window->Collapsed)
7980 MarkIniSettingsDirty(window);
7981 }
7982
7983 // Apply minimum/maximum window size constraints and final size
7984 window->SizeFull = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull);
7985 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7986
7987 // POSITION
7988
7989 // Popup latch its initial position, will position itself when it appears next frame
7990 if (window_just_activated_by_user)
7991 {
7992 window->AutoPosLastDirection = ImGuiDir_None;
7993 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7994 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7995 }
7996
7997 // Position child window
7998 if (flags & ImGuiWindowFlags_ChildWindow)
7999 {
8000 IM_ASSERT(parent_window && parent_window->Active);
8001 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
8002 parent_window->DC.ChildWindows.push_back(v: window);
8003 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
8004 window->Pos = parent_window->DC.CursorPos;
8005 }
8006
8007 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
8008 if (window_pos_with_pivot)
8009 SetWindowPos(window, pos: window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, cond: 0); // Position given a pivot (e.g. for centering)
8010 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
8011 window->Pos = FindBestWindowPosForPopup(window);
8012 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
8013 window->Pos = FindBestWindowPosForPopup(window);
8014 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
8015 window->Pos = FindBestWindowPosForPopup(window);
8016
8017 // Late create viewport if we don't fit within our current host viewport.
8018 if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
8019 if (!window->Viewport->GetMainRect().Contains(r: window->Rect()))
8020 {
8021 // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
8022 //ImGuiViewport* old_viewport = window->Viewport;
8023 window->Viewport = AddUpdateViewport(window, id: window->ID, platform_pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_NoFocusOnAppearing);
8024
8025 // FIXME-DPI
8026 //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
8027 SetCurrentViewport(window, viewport: window->Viewport);
8028 SetCurrentWindow(window);
8029 }
8030
8031 if (window->ViewportOwned)
8032 WindowSyncOwnedViewport(window, parent_window_in_stack);
8033
8034 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
8035 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
8036 ImRect viewport_rect(window->Viewport->GetMainRect());
8037 ImRect viewport_work_rect(window->Viewport->GetWorkRect());
8038 ImVec2 visibility_padding = ImMax(lhs: style.DisplayWindowPadding, rhs: style.DisplaySafeAreaPadding);
8039 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
8040
8041 // Clamp position/size so window stays visible within its viewport or monitor
8042 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
8043 // FIXME: Similar to code in GetWindowAllowedExtentRect()
8044 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
8045 {
8046 if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
8047 {
8048 ClampWindowPos(window, visibility_rect);
8049 }
8050 else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
8051 {
8052 if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
8053 {
8054 // While moving windows we allow them to straddle monitors (#7299, #3071)
8055 visibility_rect = g.PlatformMonitorsFullWorkRect;
8056 }
8057 else
8058 {
8059 // When not moving ensure visible in its monitor
8060 // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
8061 const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(viewport: window->Viewport);
8062 visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
8063 }
8064 visibility_rect.Expand(amount: -visibility_padding);
8065 ClampWindowPos(window, visibility_rect);
8066 }
8067 }
8068 window->Pos = ImTrunc(v: window->Pos);
8069
8070 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
8071 // Large values tend to lead to variety of artifacts and are not recommended.
8072 if (window->ViewportOwned || window->DockIsActive)
8073 window->WindowRounding = 0.0f;
8074 else
8075 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
8076
8077 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
8078 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
8079 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
8080
8081 // Apply window focus (new and reactivated windows are moved to front)
8082 bool want_focus = false;
8083 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
8084 {
8085 if (flags & ImGuiWindowFlags_Popup)
8086 want_focus = true;
8087 else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
8088 want_focus = true;
8089 }
8090
8091 // [Test Engine] Register whole window in the item system (before submitting further decorations)
8092#ifdef IMGUI_ENABLE_TEST_ENGINE
8093 if (g.TestEngineHookItems)
8094 {
8095 IM_ASSERT(window->IDStack.Size == 1);
8096 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
8097 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8098 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
8099 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
8100 window->IDStack.Size = 1;
8101 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8102
8103 }
8104#endif
8105
8106 // Decide if we are going to handle borders and resize grips
8107 // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815)
8108 // Whenever we add support for full decorated child windows we will likely make this logic more general.
8109 bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
8110 if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems)
8111 handle_borders_and_resize_grips = false;
8112
8113 // Handle manual resize: Resize Grips, Borders, Gamepad
8114 int border_hovered = -1, border_held = -1;
8115 ImU32 resize_grip_col[4] = {};
8116 const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
8117 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
8118 if (handle_borders_and_resize_grips && !window->Collapsed)
8119 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, border_hovered: &border_hovered, border_held: &border_held, resize_grip_count, resize_grip_col: &resize_grip_col[0], visibility_rect))
8120 {
8121 if (auto_fit_mask & (1 << ImGuiAxis_X))
8122 use_current_size_for_scrollbar_x = true;
8123 if (auto_fit_mask & (1 << ImGuiAxis_Y))
8124 use_current_size_for_scrollbar_y = true;
8125 }
8126 window->ResizeBorderHovered = (signed char)border_hovered;
8127 window->ResizeBorderHeld = (signed char)border_held;
8128
8129 // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
8130 if (window->ViewportOwned)
8131 {
8132 if (!window->Viewport->PlatformRequestMove)
8133 window->Viewport->Pos = window->Pos;
8134 if (!window->Viewport->PlatformRequestResize)
8135 window->Viewport->Size = window->Size;
8136 window->Viewport->UpdateWorkRect();
8137 viewport_rect = window->Viewport->GetMainRect();
8138 }
8139
8140 // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
8141 window->ViewportPos = window->Viewport->Pos;
8142
8143 // SCROLLBAR VISIBILITY
8144
8145 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
8146 if (!window->Collapsed)
8147 {
8148 // When reading the current size we need to read it after size constraints have been applied.
8149 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
8150 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
8151 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
8152 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
8153 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
8154 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
8155 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
8156 bool scrollbar_x_prev = window->ScrollbarX;
8157 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
8158 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
8159 window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
8160
8161 // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
8162 // (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.
8163 // 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)
8164 window->ScrollbarXStabilizeToggledHistory <<= 1;
8165 window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00;
8166 const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(v: window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history.
8167 if (scrollbar_x_stabilize)
8168 window->ScrollbarX = true;
8169 //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled)
8170 // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name);
8171 window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize;
8172
8173 if (window->ScrollbarX && !window->ScrollbarY)
8174 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
8175 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
8176
8177 // Amend the partially filled window->DecorationXXX values.
8178 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
8179 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
8180 }
8181
8182 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
8183 // Update various regions. Variables they depend on should be set above in this function.
8184 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
8185
8186 // Outer rectangle
8187 // Not affected by window border size. Used by:
8188 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
8189 // - Begin() initial clipping rect for drawing window background and borders.
8190 // - Begin() clipping whole child
8191 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
8192 const ImRect outer_rect = window->Rect();
8193 const ImRect title_bar_rect = window->TitleBarRect();
8194 window->OuterRectClipped = outer_rect;
8195 if (window->DockIsActive)
8196 window->OuterRectClipped.Min.y += window->TitleBarHeight;
8197 window->OuterRectClipped.ClipWith(r: host_rect);
8198
8199 // Inner rectangle
8200 // Not affected by window border size. Used by:
8201 // - InnerClipRect
8202 // - ScrollToRectEx()
8203 // - NavUpdatePageUpPageDown()
8204 // - Scrollbar()
8205 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
8206 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
8207 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
8208 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
8209
8210 // Inner clipping rectangle.
8211 // - Extend a outside of normal work region up to borders.
8212 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
8213 // - It also makes clipped items be more noticeable.
8214 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
8215 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
8216 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
8217 // Affected by window/frame border size. Used by:
8218 // - Begin() initial clip rect
8219 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
8220
8221 // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner.
8222 // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize,
8223 // 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).
8224 window->InnerClipRect.Min.x = ImFloor(f: 0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f);
8225 window->InnerClipRect.Min.y = ImFloor(f: 0.5f + window->InnerRect.Min.y + top_border_size * 0.5f);
8226 window->InnerClipRect.Max.x = ImFloor(f: window->InnerRect.Max.x - window->WindowBorderSize * 0.5f);
8227 window->InnerClipRect.Max.y = ImFloor(f: window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
8228 window->InnerClipRect.ClipWithFull(r: host_rect);
8229
8230 // SCROLLING
8231
8232 // Lock down maximum scrolling
8233 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
8234 // for right/bottom aligned items without creating a scrollbar.
8235 window->ScrollMax.x = ImMax(lhs: 0.0f, rhs: window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
8236 window->ScrollMax.y = ImMax(lhs: 0.0f, rhs: window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
8237
8238 // Apply scrolling
8239 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
8240 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
8241 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
8242
8243 // DRAWING
8244
8245 // Setup draw list and outer clipping rectangle
8246 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
8247 window->DrawList->PushTexture(tex_ref: g.Font->ContainerAtlas->TexRef);
8248 PushClipRect(clip_rect_min: host_rect.Min, clip_rect_max: host_rect.Max, intersect_with_current_clip_rect: false);
8249
8250 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
8251 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
8252 // 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)
8253 const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
8254 if (is_undocked_or_docked_visible)
8255 {
8256 bool render_decorations_in_parent = false;
8257 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
8258 {
8259 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
8260 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
8261 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
8262 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(r: window->Rect()) : false;
8263 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
8264 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
8265 render_decorations_in_parent = true;
8266 }
8267 if (render_decorations_in_parent)
8268 window->DrawList = parent_window->DrawList;
8269
8270 // Handle title bar, scrollbar, resize grips and resize borders
8271 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
8272 const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
8273 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
8274
8275 if (render_decorations_in_parent)
8276 window->DrawList = &window->DrawListInst;
8277 }
8278
8279 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
8280
8281 // Work rectangle.
8282 // Affected by window padding and border size. Used by:
8283 // - Columns() for right-most edge
8284 // - TreeNode(), CollapsingHeader() for right-most edge
8285 // - BeginTabBar() for right-most edge
8286 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
8287 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
8288 const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(lhs: allow_scrollbar_x ? window->ContentSize.x : 0.0f, rhs: window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
8289 const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(lhs: allow_scrollbar_y ? window->ContentSize.y : 0.0f, rhs: window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
8290 window->WorkRect.Min.x = ImTrunc(f: window->InnerRect.Min.x - window->Scroll.x + ImMax(lhs: window->WindowPadding.x, rhs: window->WindowBorderSize));
8291 window->WorkRect.Min.y = ImTrunc(f: window->InnerRect.Min.y - window->Scroll.y + ImMax(lhs: window->WindowPadding.y, rhs: window->WindowBorderSize));
8292 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
8293 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
8294 window->ParentWorkRect = window->WorkRect;
8295
8296 // [LEGACY] Content Region
8297 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
8298 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
8299 // Used by:
8300 // - Mouse wheel scrolling + many other things
8301 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
8302 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
8303 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)));
8304 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)));
8305
8306 // Setup drawing context
8307 // (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.)
8308 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
8309 window->DC.GroupOffset.x = 0.0f;
8310 window->DC.ColumnsOffset.x = 0.0f;
8311
8312 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
8313 // 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.
8314 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
8315 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
8316 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
8317 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
8318 window->DC.CursorPos = window->DC.CursorStartPos;
8319 window->DC.CursorPosPrevLine = window->DC.CursorPos;
8320 window->DC.CursorMaxPos = window->DC.CursorStartPos;
8321 window->DC.IdealMaxPos = window->DC.CursorStartPos;
8322 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
8323 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
8324 window->DC.IsSameLine = window->DC.IsSetPos = false;
8325
8326 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8327 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
8328 window->DC.NavLayersActiveMaskNext = 0x00;
8329 window->DC.NavIsScrollPushableX = true;
8330 window->DC.NavHideHighlightOneFrame = false;
8331 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
8332
8333 window->DC.MenuBarAppending = false;
8334 window->DC.MenuColumns.Update(spacing: style.ItemSpacing.x, window_reappearing: window_just_activated_by_user);
8335 window->DC.TreeDepth = 0;
8336 window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00;
8337 window->DC.ChildWindows.resize(new_size: 0);
8338 window->DC.StateStorage = &window->StateStorage;
8339 window->DC.CurrentColumns = NULL;
8340 window->DC.LayoutType = ImGuiLayoutType_Vertical;
8341 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
8342
8343 // Default item width. Make it proportional to window size if window manually resizes
8344 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
8345 window->ItemWidthDefault = ImTrunc(f: window->Size.x * 0.65f);
8346 else
8347 window->ItemWidthDefault = ImTrunc(f: g.FontSize * 16.0f);
8348 window->DC.ItemWidth = window->ItemWidthDefault;
8349 window->DC.TextWrapPos = -1.0f; // disabled
8350 window->DC.ItemWidthStack.resize(new_size: 0);
8351 window->DC.TextWrapPosStack.resize(new_size: 0);
8352 if (flags & ImGuiWindowFlags_Modal)
8353 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(in: GetStyleColorVec4(idx: ImGuiCol_ModalWindowDimBg));
8354
8355 if (window->AutoFitFramesX > 0)
8356 window->AutoFitFramesX--;
8357 if (window->AutoFitFramesY > 0)
8358 window->AutoFitFramesY--;
8359
8360 // Clear SetNextWindowXXX data (can aim to move this higher in the function)
8361 g.NextWindowData.ClearFlags();
8362
8363 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
8364 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
8365 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
8366 // - Position window behind the modal that is not a begin-parent of this window.
8367 if (want_focus)
8368 FocusWindow(window, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
8369 if (want_focus && window == g.NavWindow)
8370 NavInitWindow(window, force_reinit: false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
8371
8372 // Close requested by platform window (apply to all windows in this viewport)
8373 if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
8374 {
8375 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
8376 *p_open = false;
8377 g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
8378 }
8379
8380 // Pressing CTRL+C copy window content into the clipboard
8381 // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
8382 // [EXPERIMENTAL] Text outputs has many issues.
8383 if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
8384 if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(key_chord: ImGuiMod_Ctrl | ImGuiKey_C))
8385 LogToClipboard(auto_open_depth: 0);
8386
8387 // Title bar
8388 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
8389 RenderWindowTitleBarContents(window, title_bar_rect: 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);
8390 else if (!(flags & ImGuiWindowFlags_NoTitleBar) && window->DockIsActive)
8391 LogText(fmt: "%.*s\n", (int)(FindRenderedTextEnd(text: window->Name) - window->Name), window->Name);
8392
8393 // Clear hit test shape every frame
8394 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
8395
8396 if (flags & ImGuiWindowFlags_Tooltip)
8397 g.TooltipPreviousWindow = window;
8398
8399 if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
8400 {
8401 // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
8402 // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
8403 if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
8404 BeginDockableDragDropSource(window);
8405
8406 // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
8407 if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
8408 if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
8409 if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
8410 BeginDockableDragDropTarget(window);
8411 }
8412
8413 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
8414 // This is useful to allow creating context menus on title bar only, etc.
8415 window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None;
8416 window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max, clip: false) ? ImGuiItemStatusFlags_HoveredRect : 0;
8417 SetLastItemDataForWindow(window, rect: title_bar_rect);
8418
8419 // [DEBUG]
8420#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8421 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
8422 DebugLocateItemResolveWithLastItem();
8423#endif
8424
8425 // [Test Engine] Register title bar / tab with MoveId.
8426#ifdef IMGUI_ENABLE_TEST_ENGINE
8427 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
8428 {
8429 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8430 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
8431 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8432 }
8433#endif
8434 }
8435 else
8436 {
8437 // Skip refresh always mark active
8438 if (window->SkipRefresh)
8439 SetWindowActiveForSkipRefresh(window);
8440
8441 // Append
8442 SetCurrentViewport(window, viewport: window->Viewport);
8443 SetCurrentWindow(window);
8444 g.NextWindowData.ClearFlags();
8445 SetLastItemDataForWindow(window, rect: window->TitleBarRect());
8446 }
8447
8448 if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
8449 PushClipRect(clip_rect_min: window->InnerClipRect.Min, clip_rect_max: window->InnerClipRect.Max, intersect_with_current_clip_rect: true);
8450
8451 // 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)
8452 window->WriteAccessed = false;
8453 window->BeginCount++;
8454
8455 // Update visibility
8456 if (first_begin_of_the_frame && !window->SkipRefresh)
8457 {
8458 // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
8459 // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
8460 // This is analogous to regular windows being hidden from one frame.
8461 // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
8462 if (window->DockIsActive && !window->DockTabIsVisible)
8463 {
8464 if (window->LastFrameJustFocused == g.FrameCount)
8465 window->HiddenFramesCannotSkipItems = 1;
8466 else
8467 window->HiddenFramesCanSkipItems = 1;
8468 }
8469
8470 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
8471 {
8472 // Child window can be out of sight and have "negative" clip windows.
8473 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
8474 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
8475 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
8476 if (!g.LogEnabled && !nav_request)
8477 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
8478 {
8479 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
8480 window->HiddenFramesCannotSkipItems = 1;
8481 else
8482 window->HiddenFramesCanSkipItems = 1;
8483 }
8484
8485 // Hide along with parent or if parent is collapsed
8486 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
8487 window->HiddenFramesCanSkipItems = 1;
8488 if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0)
8489 window->HiddenFramesCannotSkipItems = 1;
8490 }
8491
8492 // 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)
8493 if (style.Alpha <= 0.0f)
8494 window->HiddenFramesCanSkipItems = 1;
8495
8496 // Update the Hidden flag
8497 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
8498 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
8499
8500 // Disable inputs for requested number of frames
8501 if (window->DisableInputsFrames > 0)
8502 {
8503 window->DisableInputsFrames--;
8504 window->Flags |= ImGuiWindowFlags_NoInputs;
8505 }
8506
8507 // Update the SkipItems flag, used to early out of all items functions (no layout required)
8508 bool skip_items = false;
8509 if (window->Collapsed || !window->Active || hidden_regular)
8510 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
8511 skip_items = true;
8512 window->SkipItems = skip_items;
8513
8514 // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
8515 if (window->SkipItems)
8516 window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
8517
8518 // Sanity check: there are two spots which can set Appearing = true
8519 // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
8520 // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
8521 if (window->SkipItems && !window->Appearing)
8522 IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
8523 }
8524 else if (first_begin_of_the_frame)
8525 {
8526 // Skip refresh mode
8527 window->SkipItems = true;
8528 }
8529
8530 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
8531 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
8532#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8533 if (!window->IsFallbackWindow)
8534 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
8535 {
8536 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
8537 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
8538 return false;
8539 }
8540#endif
8541
8542 return !window->SkipItems;
8543}
8544
8545void ImGui::End()
8546{
8547 ImGuiContext& g = *GImGui;
8548 ImGuiWindow* window = g.CurrentWindow;
8549
8550 // Error checking: verify that user hasn't called End() too many times!
8551 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
8552 {
8553 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
8554 return;
8555 }
8556 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
8557
8558 // Error checking: verify that user doesn't directly call End() on a child window.
8559 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
8560 IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!");
8561
8562 // Close anything that is open
8563 if (window->DC.CurrentColumns)
8564 EndColumns();
8565 if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) // Pop inner window clip rectangle
8566 PopClipRect();
8567 PopFocusScope();
8568 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
8569 EndDisabledOverrideReenable();
8570
8571 if (window->SkipRefresh)
8572 {
8573 IM_ASSERT(window->DrawList == NULL);
8574 window->DrawList = &window->DrawListInst;
8575 }
8576
8577 // Stop logging
8578 if (g.LogWindow == window) // FIXME: add more options for scope of logging
8579 LogFinish();
8580
8581 if (window->DC.IsSetPos)
8582 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
8583
8584 // Docking: report contents sizes to parent to allow for auto-resize
8585 if (window->DockNode && window->DockTabIsVisible)
8586 if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
8587 host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
8588
8589 // Pop from window stack
8590 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
8591 if (window->Flags & ImGuiWindowFlags_ChildMenu)
8592 g.BeginMenuDepth--;
8593 if (window->Flags & ImGuiWindowFlags_Popup)
8594 g.BeginPopupStack.pop_back();
8595
8596 // Error handling, state recovery
8597 if (g.IO.ConfigErrorRecovery)
8598 ErrorRecoveryTryToRecoverWindowState(state_in: &window_stack_data.StackSizesInBegin);
8599
8600 g.CurrentWindowStack.pop_back();
8601 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
8602 if (g.CurrentWindow)
8603 SetCurrentViewport(window: g.CurrentWindow, viewport: g.CurrentWindow->Viewport);
8604}
8605
8606void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8607{
8608 ImGuiContext& g = *GImGui;
8609 ImGuiItemFlags item_flags = g.CurrentItemFlags;
8610 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8611 if (enabled)
8612 item_flags |= option;
8613 else
8614 item_flags &= ~option;
8615 g.CurrentItemFlags = item_flags;
8616 g.ItemFlagsStack.push_back(v: item_flags);
8617}
8618
8619void ImGui::PopItemFlag()
8620{
8621 ImGuiContext& g = *GImGui;
8622 if (g.ItemFlagsStack.Size <= 1)
8623 {
8624 IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!");
8625 return;
8626 }
8627 g.ItemFlagsStack.pop_back();
8628 g.CurrentItemFlags = g.ItemFlagsStack.back();
8629}
8630
8631// BeginDisabled()/EndDisabled()
8632// - 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)
8633// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8634// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8635// - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
8636// (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)
8637// - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
8638void ImGui::BeginDisabled(bool disabled)
8639{
8640 ImGuiContext& g = *GImGui;
8641 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8642 if (!was_disabled && disabled)
8643 {
8644 g.DisabledAlphaBackup = g.Style.Alpha;
8645 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8646 }
8647 if (was_disabled || disabled)
8648 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8649 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8650 g.DisabledStackSize++;
8651}
8652
8653void ImGui::EndDisabled()
8654{
8655 ImGuiContext& g = *GImGui;
8656 if (g.DisabledStackSize <= 0)
8657 {
8658 IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!");
8659 return;
8660 }
8661 g.DisabledStackSize--;
8662 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8663 //PopItemFlag();
8664 g.ItemFlagsStack.pop_back();
8665 g.CurrentItemFlags = g.ItemFlagsStack.back();
8666 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8667 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8668}
8669
8670// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8671// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8672// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8673void ImGui::BeginDisabledOverrideReenable()
8674{
8675 ImGuiContext& g = *GImGui;
8676 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8677 g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha;
8678 g.Style.Alpha = g.DisabledAlphaBackup;
8679 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8680 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags);
8681 g.DisabledStackSize++;
8682}
8683
8684void ImGui::EndDisabledOverrideReenable()
8685{
8686 ImGuiContext& g = *GImGui;
8687 g.DisabledStackSize--;
8688 IM_ASSERT(g.DisabledStackSize > 0);
8689 g.ItemFlagsStack.pop_back();
8690 g.CurrentItemFlags = g.ItemFlagsStack.back();
8691 g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup;
8692}
8693
8694void ImGui::PushTextWrapPos(float wrap_pos_x)
8695{
8696 ImGuiContext& g = *GImGui;
8697 ImGuiWindow* window = g.CurrentWindow;
8698 window->DC.TextWrapPosStack.push_back(v: window->DC.TextWrapPos);
8699 window->DC.TextWrapPos = wrap_pos_x;
8700}
8701
8702void ImGui::PopTextWrapPos()
8703{
8704 ImGuiContext& g = *GImGui;
8705 ImGuiWindow* window = g.CurrentWindow;
8706 if (window->DC.TextWrapPosStack.Size <= 0)
8707 {
8708 IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
8709 return;
8710 }
8711 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8712 window->DC.TextWrapPosStack.pop_back();
8713}
8714
8715static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8716{
8717 ImGuiWindow* last_window = NULL;
8718 while (last_window != window)
8719 {
8720 last_window = window;
8721 window = window->RootWindow;
8722 if (popup_hierarchy)
8723 window = window->RootWindowPopupTree;
8724 if (dock_hierarchy)
8725 window = window->RootWindowDockTree;
8726 }
8727 return window;
8728}
8729
8730bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8731{
8732 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8733 if (window_root == potential_parent)
8734 return true;
8735 while (window != NULL)
8736 {
8737 if (window == potential_parent)
8738 return true;
8739 if (window == window_root) // end of chain
8740 return false;
8741 window = window->ParentWindow;
8742 }
8743 return false;
8744}
8745
8746bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8747{
8748 if (window->RootWindow == potential_parent)
8749 return true;
8750 while (window != NULL)
8751 {
8752 if (window == potential_parent)
8753 return true;
8754 window = window->ParentWindowInBeginStack;
8755 }
8756 return false;
8757}
8758
8759bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8760{
8761 ImGuiContext& g = *GImGui;
8762
8763 // 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
8764 const int display_layer_delta = GetWindowDisplayLayer(window: potential_above) - GetWindowDisplayLayer(window: potential_below);
8765 if (display_layer_delta != 0)
8766 return display_layer_delta > 0;
8767
8768 for (int i = g.Windows.Size - 1; i >= 0; i--)
8769 {
8770 ImGuiWindow* candidate_window = g.Windows[i];
8771 if (candidate_window == potential_above)
8772 return true;
8773 if (candidate_window == potential_below)
8774 return false;
8775 }
8776 return false;
8777}
8778
8779// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8780// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8781// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8782// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8783bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8784{
8785 ImGuiContext& g = *GImGui;
8786 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
8787
8788 ImGuiWindow* ref_window = g.HoveredWindow;
8789 ImGuiWindow* cur_window = g.CurrentWindow;
8790 if (ref_window == NULL)
8791 return false;
8792
8793 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8794 {
8795 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8796 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8797 const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8798 if (flags & ImGuiHoveredFlags_RootWindow)
8799 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy, dock_hierarchy);
8800
8801 bool result;
8802 if (flags & ImGuiHoveredFlags_ChildWindows)
8803 result = IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy, dock_hierarchy);
8804 else
8805 result = (ref_window == cur_window);
8806 if (!result)
8807 return false;
8808 }
8809
8810 if (!IsWindowContentHoverable(window: ref_window, flags))
8811 return false;
8812 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8813 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8814 return false;
8815
8816 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8817 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8818 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8819 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8820 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8821 if (flags & ImGuiHoveredFlags_ForTooltip)
8822 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
8823 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8824 return false;
8825
8826 return true;
8827}
8828
8829ImGuiID ImGui::GetWindowDockID()
8830{
8831 ImGuiContext& g = *GImGui;
8832 return g.CurrentWindow->DockId;
8833}
8834
8835bool ImGui::IsWindowDocked()
8836{
8837 ImGuiContext& g = *GImGui;
8838 return g.CurrentWindow->DockIsActive;
8839}
8840
8841float ImGui::GetWindowWidth()
8842{
8843 ImGuiWindow* window = GImGui->CurrentWindow;
8844 return window->Size.x;
8845}
8846
8847float ImGui::GetWindowHeight()
8848{
8849 ImGuiWindow* window = GImGui->CurrentWindow;
8850 return window->Size.y;
8851}
8852
8853ImVec2 ImGui::GetWindowPos()
8854{
8855 ImGuiContext& g = *GImGui;
8856 ImGuiWindow* window = g.CurrentWindow;
8857 return window->Pos;
8858}
8859
8860void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8861{
8862 // Test condition (NB: bit 0 is always true) and clear flags for next time
8863 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8864 return;
8865
8866 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8867 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8868 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8869
8870 // Set
8871 const ImVec2 old_pos = window->Pos;
8872 window->Pos = ImTrunc(v: pos);
8873 ImVec2 offset = window->Pos - old_pos;
8874 if (offset.x == 0.0f && offset.y == 0.0f)
8875 return;
8876 MarkIniSettingsDirty(window);
8877 // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8878 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
8879 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8880 window->DC.IdealMaxPos += offset;
8881 window->DC.CursorStartPos += offset;
8882}
8883
8884void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8885{
8886 ImGuiWindow* window = GetCurrentWindowRead();
8887 SetWindowPos(window, pos, cond);
8888}
8889
8890void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8891{
8892 if (ImGuiWindow* window = FindWindowByName(name))
8893 SetWindowPos(window, pos, cond);
8894}
8895
8896ImVec2 ImGui::GetWindowSize()
8897{
8898 ImGuiWindow* window = GetCurrentWindowRead();
8899 return window->Size;
8900}
8901
8902void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8903{
8904 // Test condition (NB: bit 0 is always true) and clear flags for next time
8905 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8906 return;
8907
8908 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8909 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8910
8911 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8912 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8913 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8914 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8915 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8916
8917 // Set
8918 ImVec2 old_size = window->SizeFull;
8919 if (size.x <= 0.0f)
8920 window->AutoFitOnlyGrows = false;
8921 else
8922 window->SizeFull.x = IM_TRUNC(size.x);
8923 if (size.y <= 0.0f)
8924 window->AutoFitOnlyGrows = false;
8925 else
8926 window->SizeFull.y = IM_TRUNC(size.y);
8927 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8928 MarkIniSettingsDirty(window);
8929}
8930
8931void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8932{
8933 SetWindowSize(window: GImGui->CurrentWindow, size, cond);
8934}
8935
8936void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8937{
8938 if (ImGuiWindow* window = FindWindowByName(name))
8939 SetWindowSize(window, size, cond);
8940}
8941
8942void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8943{
8944 // Test condition (NB: bit 0 is always true) and clear flags for next time
8945 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8946 return;
8947 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8948
8949 // Queue applying in Begin()
8950 if (window->WantCollapseToggle)
8951 window->Collapsed ^= 1;
8952 window->WantCollapseToggle = (window->Collapsed != collapsed);
8953}
8954
8955void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8956{
8957 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8958 window->HitTestHoleSize = ImVec2ih(size);
8959 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8960}
8961
8962void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8963{
8964 window->Hidden = window->SkipItems = true;
8965 window->HiddenFramesCanSkipItems = 1;
8966}
8967
8968void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8969{
8970 SetWindowCollapsed(window: GImGui->CurrentWindow, collapsed, cond);
8971}
8972
8973bool ImGui::IsWindowCollapsed()
8974{
8975 ImGuiWindow* window = GetCurrentWindowRead();
8976 return window->Collapsed;
8977}
8978
8979bool ImGui::IsWindowAppearing()
8980{
8981 ImGuiWindow* window = GetCurrentWindowRead();
8982 return window->Appearing;
8983}
8984
8985void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8986{
8987 if (ImGuiWindow* window = FindWindowByName(name))
8988 SetWindowCollapsed(window, collapsed, cond);
8989}
8990
8991void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8992{
8993 ImGuiContext& g = *GImGui;
8994 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8995 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos;
8996 g.NextWindowData.PosVal = pos;
8997 g.NextWindowData.PosPivotVal = pivot;
8998 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8999 g.NextWindowData.PosUndock = true;
9000}
9001
9002void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
9003{
9004 ImGuiContext& g = *GImGui;
9005 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9006 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize;
9007 g.NextWindowData.SizeVal = size;
9008 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
9009}
9010
9011// For each axis:
9012// - 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.
9013// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
9014// - See "Demo->Examples->Constrained-resizing window" for examples.
9015void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
9016{
9017 ImGuiContext& g = *GImGui;
9018 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
9019 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
9020 g.NextWindowData.SizeCallback = custom_callback;
9021 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
9022}
9023
9024// Content size = inner scrollable rectangle, padded with WindowPadding.
9025// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
9026void ImGui::SetNextWindowContentSize(const ImVec2& size)
9027{
9028 ImGuiContext& g = *GImGui;
9029 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize;
9030 g.NextWindowData.ContentSizeVal = ImTrunc(v: size);
9031}
9032
9033void ImGui::SetNextWindowScroll(const ImVec2& scroll)
9034{
9035 ImGuiContext& g = *GImGui;
9036 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll;
9037 g.NextWindowData.ScrollVal = scroll;
9038}
9039
9040void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
9041{
9042 ImGuiContext& g = *GImGui;
9043 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9044 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed;
9045 g.NextWindowData.CollapsedVal = collapsed;
9046 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
9047}
9048
9049void ImGui::SetNextWindowBgAlpha(float alpha)
9050{
9051 ImGuiContext& g = *GImGui;
9052 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha;
9053 g.NextWindowData.BgAlphaVal = alpha;
9054}
9055
9056void ImGui::SetNextWindowViewport(ImGuiID id)
9057{
9058 ImGuiContext& g = *GImGui;
9059 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasViewport;
9060 g.NextWindowData.ViewportId = id;
9061}
9062
9063void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
9064{
9065 ImGuiContext& g = *GImGui;
9066 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasDock;
9067 g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
9068 g.NextWindowData.DockId = id;
9069}
9070
9071void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
9072{
9073 ImGuiContext& g = *GImGui;
9074 IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
9075 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasWindowClass;
9076 g.NextWindowData.WindowClass = *window_class;
9077}
9078
9079// This is experimental and meant to be a toy for exploring a future/wider range of features.
9080void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
9081{
9082 ImGuiContext& g = *GImGui;
9083 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
9084 g.NextWindowData.RefreshFlagsVal = flags;
9085}
9086
9087ImDrawList* ImGui::GetWindowDrawList()
9088{
9089 ImGuiWindow* window = GetCurrentWindow();
9090 return window->DrawList;
9091}
9092
9093float ImGui::GetWindowDpiScale()
9094{
9095 ImGuiContext& g = *GImGui;
9096 return g.CurrentDpiScale;
9097}
9098
9099ImGuiViewport* ImGui::GetWindowViewport()
9100{
9101 ImGuiContext& g = *GImGui;
9102 IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
9103 return g.CurrentViewport;
9104}
9105
9106ImFont* ImGui::GetFont()
9107{
9108 return GImGui->Font;
9109}
9110
9111ImFontBaked* ImGui::GetFontBaked()
9112{
9113 return GImGui->FontBaked;
9114}
9115
9116// Get current font size (= height in pixels) of current font, with global scale factors applied.
9117// - Use style.FontSizeBase to get value before global scale factors.
9118// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors)
9119float ImGui::GetFontSize()
9120{
9121 return GImGui->FontSize;
9122}
9123
9124ImVec2 ImGui::GetFontTexUvWhitePixel()
9125{
9126 return GImGui->DrawListSharedData.TexUvWhitePixel;
9127}
9128
9129// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows.
9130#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9131void ImGui::SetWindowFontScale(float scale)
9132{
9133 IM_ASSERT(scale > 0.0f);
9134 ImGuiWindow* window = GetCurrentWindow();
9135 window->FontWindowScale = scale;
9136 UpdateCurrentFontSize(restore_font_size_after_scaling: 0.0f);
9137}
9138#endif
9139
9140void ImGui::PushFocusScope(ImGuiID id)
9141{
9142 ImGuiContext& g = *GImGui;
9143 ImGuiFocusScopeData data;
9144 data.ID = id;
9145 data.WindowID = g.CurrentWindow->ID;
9146 g.FocusScopeStack.push_back(v: data);
9147 g.CurrentFocusScopeId = id;
9148}
9149
9150void ImGui::PopFocusScope()
9151{
9152 ImGuiContext& g = *GImGui;
9153 if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack)
9154 {
9155 IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
9156 return;
9157 }
9158 g.FocusScopeStack.pop_back();
9159 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
9160}
9161
9162void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
9163{
9164 ImGuiContext& g = *GImGui;
9165 g.NavFocusScopeId = focus_scope_id;
9166 g.NavFocusRoute.resize(new_size: 0); // Invalidate
9167 if (focus_scope_id == 0)
9168 return;
9169 IM_ASSERT(g.NavWindow != NULL);
9170
9171 // Store current path (in reverse order)
9172 if (focus_scope_id == g.CurrentFocusScopeId)
9173 {
9174 // Top of focus stack contains local focus scopes inside current window
9175 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
9176 g.NavFocusRoute.push_back(v: g.FocusScopeStack.Data[n]);
9177 }
9178 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
9179 g.NavFocusRoute.push_back(v: { .ID: focus_scope_id, .WindowID: g.NavWindow->ID });
9180 else
9181 return;
9182
9183 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
9184 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
9185 g.NavFocusRoute.push_back(v: { .ID: window->NavRootFocusScopeId, .WindowID: window->ID });
9186 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
9187}
9188
9189// Focus = move navigation cursor, set scrolling, set focus window.
9190void ImGui::FocusItem()
9191{
9192 ImGuiContext& g = *GImGui;
9193 ImGuiWindow* window = g.CurrentWindow;
9194 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
9195 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
9196 {
9197 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
9198 return;
9199 }
9200
9201 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
9202 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9203 SetNavWindow(window);
9204 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: ImGuiDir_Up, move_flags, scroll_flags);
9205 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
9206}
9207
9208void ImGui::ActivateItemByID(ImGuiID id)
9209{
9210 ImGuiContext& g = *GImGui;
9211 g.NavNextActivateId = id;
9212 g.NavNextActivateFlags = ImGuiActivateFlags_None;
9213}
9214
9215// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
9216// But ActivateItem() should function without altering scroll/focus?
9217void ImGui::SetKeyboardFocusHere(int offset)
9218{
9219 ImGuiContext& g = *GImGui;
9220 ImGuiWindow* window = g.CurrentWindow;
9221 IM_ASSERT(offset >= -1); // -1 is allowed but not below
9222 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
9223
9224 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
9225 // When we refactor this function into ActivateItem() we may want to make this an option.
9226 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
9227 // is also automatically dropped in the event g.ActiveId is stolen.
9228 if (g.DragDropActive || g.MovingWindow != NULL)
9229 {
9230 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
9231 return;
9232 }
9233
9234 SetNavWindow(window);
9235
9236 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
9237 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9238 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
9239 if (offset == -1)
9240 {
9241 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
9242 }
9243 else
9244 {
9245 g.NavTabbingDir = 1;
9246 g.NavTabbingCounter = offset + 1;
9247 }
9248}
9249
9250void ImGui::SetItemDefaultFocus()
9251{
9252 ImGuiContext& g = *GImGui;
9253 ImGuiWindow* window = g.CurrentWindow;
9254 if (!window->Appearing)
9255 return;
9256 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
9257 return;
9258
9259 g.NavInitRequest = false;
9260 NavApplyItemToResult(result: &g.NavInitResult);
9261 NavUpdateAnyRequestFlag();
9262
9263 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
9264 if (!window->ClipRect.Contains(r: g.LastItemData.Rect))
9265 ScrollToRectEx(window, rect: g.LastItemData.Rect, flags: ImGuiScrollFlags_None);
9266}
9267
9268void ImGui::SetStateStorage(ImGuiStorage* tree)
9269{
9270 ImGuiWindow* window = GImGui->CurrentWindow;
9271 window->DC.StateStorage = tree ? tree : &window->StateStorage;
9272}
9273
9274ImGuiStorage* ImGui::GetStateStorage()
9275{
9276 ImGuiWindow* window = GImGui->CurrentWindow;
9277 return window->DC.StateStorage;
9278}
9279
9280bool ImGui::IsRectVisible(const ImVec2& size)
9281{
9282 ImGuiWindow* window = GImGui->CurrentWindow;
9283 return window->ClipRect.Overlaps(r: ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
9284}
9285
9286bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
9287{
9288 ImGuiWindow* window = GImGui->CurrentWindow;
9289 return window->ClipRect.Overlaps(r: ImRect(rect_min, rect_max));
9290}
9291
9292//-----------------------------------------------------------------------------
9293// [SECTION] FONTS, TEXTURES
9294//-----------------------------------------------------------------------------
9295// Most of the relevant font logic is in imgui_draw.cpp.
9296// Those are high-level support functions.
9297//-----------------------------------------------------------------------------
9298// - UpdateTexturesNewFrame() [Internal]
9299// - UpdateTexturesEndFrame() [Internal]
9300// - UpdateFontsNewFrame() [Internal]
9301// - UpdateFontsEndFrame() [Internal]
9302// - GetDefaultFont() [Internal]
9303// - RegisterUserTexture() [Internal]
9304// - UnregisterUserTexture() [Internal]
9305// - RegisterFontAtlas() [Internal]
9306// - UnregisterFontAtlas() [Internal]
9307// - SetCurrentFont() [Internal]
9308// - UpdateCurrentFontSize() [Internal]
9309// - SetFontRasterizerDensity() [Internal]
9310// - PushFont()
9311// - PopFont()
9312//-----------------------------------------------------------------------------
9313
9314static void ImGui::UpdateTexturesNewFrame()
9315{
9316 // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count.
9317 ImGuiContext& g = *GImGui;
9318 const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
9319 for (ImFontAtlas* atlas : g.FontAtlases)
9320 {
9321 if (atlas->OwnerContext == &g)
9322 {
9323 ImFontAtlasUpdateNewFrame(atlas, frame_count: g.FrameCount, renderer_has_textures: has_textures);
9324 }
9325 else
9326 {
9327 // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it.
9328 // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context.
9329 // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that.
9330 // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures.
9331 IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1);
9332 IM_ASSERT(atlas->RendererHasTextures == has_textures);
9333 }
9334 }
9335}
9336
9337// Build a single texture list
9338static void ImGui::UpdateTexturesEndFrame()
9339{
9340 ImGuiContext& g = *GImGui;
9341 g.PlatformIO.Textures.resize(new_size: 0);
9342 for (ImFontAtlas* atlas : g.FontAtlases)
9343 for (ImTextureData* tex : atlas->TexList)
9344 {
9345 // We provide this information so backends can decide whether to destroy textures.
9346 // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized.
9347 tex->RefCount = (unsigned short)atlas->RefCount;
9348 g.PlatformIO.Textures.push_back(v: tex);
9349 }
9350 for (ImTextureData* tex : g.UserTextures)
9351 g.PlatformIO.Textures.push_back(v: tex);
9352}
9353
9354void ImGui::UpdateFontsNewFrame()
9355{
9356 ImGuiContext& g = *GImGui;
9357 if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
9358 for (ImFontAtlas* atlas : g.FontAtlases)
9359 atlas->Locked = true;
9360
9361 if (g.Style._NextFrameFontSizeBase != 0.0f)
9362 {
9363 g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase;
9364 g.Style._NextFrameFontSizeBase = 0.0f;
9365 }
9366
9367 // Apply default font size the first time
9368 ImFont* font = ImGui::GetDefaultFont();
9369 if (g.Style.FontSizeBase <= 0.0f)
9370 g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE);
9371
9372 // Set initial font
9373 g.Font = font;
9374 g.FontSizeBase = g.Style.FontSizeBase;
9375 g.FontSize = 0.0f;
9376 ImFontStackData font_stack_data = { .Font: font, .FontSizeBeforeScaling: g.Style.FontSizeBase, .FontSizeAfterScaling: g.Style.FontSizeBase }; // <--- Will restore FontSize
9377 SetCurrentFont(font: font_stack_data.Font, font_size_before_scaling: font_stack_data.FontSizeBeforeScaling, font_size_after_scaling: 0.0f); // <--- but use 0.0f to enable scale
9378 g.FontStack.push_back(v: font_stack_data);
9379 IM_ASSERT(g.Font->IsLoaded());
9380}
9381
9382void ImGui::UpdateFontsEndFrame()
9383{
9384 PopFont();
9385}
9386
9387ImFont* ImGui::GetDefaultFont()
9388{
9389 ImGuiContext& g = *GImGui;
9390 ImFontAtlas* atlas = g.IO.Fonts;
9391 if (atlas->Builder == NULL || atlas->Fonts.Size == 0)
9392 ImFontAtlasBuildMain(atlas);
9393 return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0];
9394}
9395
9396// EXPERIMENTAL: DO NOT USE YET.
9397void ImGui::RegisterUserTexture(ImTextureData* tex)
9398{
9399 ImGuiContext& g = *GImGui;
9400 tex->RefCount++;
9401 g.UserTextures.push_back(v: tex);
9402}
9403
9404void ImGui::UnregisterUserTexture(ImTextureData* tex)
9405{
9406 ImGuiContext& g = *GImGui;
9407 IM_ASSERT(tex->RefCount > 0);
9408 tex->RefCount--;
9409 g.UserTextures.find_erase(v: tex);
9410}
9411
9412void ImGui::RegisterFontAtlas(ImFontAtlas* atlas)
9413{
9414 ImGuiContext& g = *GImGui;
9415 if (g.FontAtlases.Size == 0)
9416 IM_ASSERT(atlas == g.IO.Fonts);
9417 atlas->RefCount++;
9418 g.FontAtlases.push_back(v: atlas);
9419 ImFontAtlasAddDrawListSharedData(atlas, data: &g.DrawListSharedData);
9420}
9421
9422void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas)
9423{
9424 ImGuiContext& g = *GImGui;
9425 IM_ASSERT(atlas->RefCount > 0);
9426 ImFontAtlasRemoveDrawListSharedData(atlas, data: &g.DrawListSharedData);
9427 g.FontAtlases.find_erase(v: atlas);
9428 atlas->RefCount--;
9429}
9430
9431// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList.
9432// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls.
9433// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
9434// - Some code paths never really fully worked with multiple atlas textures.
9435// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture()
9436// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
9437// because we have a concrete need and a test bed for multiple atlas textures.
9438// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ?
9439void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling)
9440{
9441 ImGuiContext& g = *GImGui;
9442 g.Font = font;
9443 g.FontSizeBase = font_size_before_scaling;
9444 UpdateCurrentFontSize(restore_font_size_after_scaling: font_size_after_scaling);
9445
9446 if (font != NULL)
9447 {
9448 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
9449#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9450 IM_ASSERT(font->Scale > 0.0f);
9451#endif
9452 ImFontAtlas* atlas = font->ContainerAtlas;
9453 g.DrawListSharedData.FontAtlas = atlas;
9454 g.DrawListSharedData.Font = font;
9455 ImFontAtlasUpdateDrawListsSharedData(atlas);
9456 if (g.CurrentWindow != NULL)
9457 g.CurrentWindow->DrawList->_SetTexture(tex_ref: atlas->TexRef);
9458 }
9459}
9460
9461void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling)
9462{
9463 ImGuiContext& g = *GImGui;
9464 ImGuiWindow* window = g.CurrentWindow;
9465
9466 g.Style.FontSizeBase = g.FontSizeBase;
9467
9468 // Early out to avoid hidden window keeping bakes referenced and out of GC reach.
9469 // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching.
9470 // FIXME: perhaps g.FontSize should be updated?
9471 if (window != NULL && window->SkipItems)
9472 {
9473 ImGuiTable* table = g.CurrentTable;
9474 if (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.
9475 return;
9476 }
9477
9478 // Restoring is pretty much only used by PopFont()
9479 float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f;
9480 if (final_size == 0.0f)
9481 {
9482 final_size = g.FontSizeBase;
9483
9484 // Global scale factors
9485 final_size *= g.Style.FontScaleMain; // Main global scale factor
9486 final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled.
9487
9488 // Window scale (mostly obsolete now)
9489 if (window != NULL)
9490 final_size *= window->FontWindowScale;
9491
9492 // Legacy scale factors
9493#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9494 final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead!
9495 if (g.Font != NULL)
9496 final_size *= g.Font->Scale; // Was never really useful.
9497#endif
9498 }
9499
9500 // Round font size
9501 // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
9502 // - We may support it better later and remove this rounding.
9503 final_size = GetRoundedFontSize(size: final_size);
9504 final_size = ImClamp(v: final_size, mn: 1.0f, IMGUI_FONT_SIZE_MAX);
9505 if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures))
9506 g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity;
9507 g.FontSize = final_size;
9508 g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(font_size: final_size) : NULL;
9509 g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f;
9510 g.DrawListSharedData.FontSize = g.FontSize;
9511 g.DrawListSharedData.FontScale = g.FontBakedScale;
9512}
9513
9514// Exposed in case user may want to override setting density.
9515// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it.
9516void ImGui::SetFontRasterizerDensity(float rasterizer_density)
9517{
9518 ImGuiContext& g = *GImGui;
9519 IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures);
9520 if (g.FontRasterizerDensity == rasterizer_density)
9521 return;
9522 g.FontRasterizerDensity = rasterizer_density;
9523 UpdateCurrentFontSize(restore_font_size_after_scaling: 0.0f);
9524}
9525
9526// If you want to scale an existing font size! Read comments in imgui.h!
9527void ImGui::PushFont(ImFont* font, float font_size_base)
9528{
9529 ImGuiContext& g = *GImGui;
9530 if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont())
9531 font = g.Font;
9532 IM_ASSERT(font != NULL);
9533 IM_ASSERT(font_size_base >= 0.0f);
9534
9535 g.FontStack.push_back(v: { .Font: g.Font, .FontSizeBeforeScaling: g.FontSizeBase, .FontSizeAfterScaling: g.FontSize });
9536 if (font_size_base == 0.0f)
9537 font_size_base = g.FontSizeBase; // Keep current font size
9538 SetCurrentFont(font, font_size_before_scaling: font_size_base, font_size_after_scaling: 0.0f);
9539}
9540
9541void ImGui::PopFont()
9542{
9543 ImGuiContext& g = *GImGui;
9544 if (g.FontStack.Size <= 0)
9545 {
9546 IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
9547 return;
9548 }
9549 ImFontStackData* font_stack_data = &g.FontStack.back();
9550 SetCurrentFont(font: font_stack_data->Font, font_size_before_scaling: font_stack_data->FontSizeBeforeScaling, font_size_after_scaling: font_stack_data->FontSizeAfterScaling);
9551 g.FontStack.pop_back();
9552}
9553
9554//-----------------------------------------------------------------------------
9555// [SECTION] ID STACK
9556//-----------------------------------------------------------------------------
9557
9558// This is one of the very rare legacy case where we use ImGuiWindow methods,
9559// it should ideally be flattened at some point but it's been used a lots by widgets.
9560IM_MSVC_RUNTIME_CHECKS_OFF
9561ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
9562{
9563 ImGuiID seed = IDStack.back();
9564 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
9565#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9566 ImGuiContext& g = *Ctx;
9567 if (g.DebugHookIdInfo == id)
9568 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
9569#endif
9570 return id;
9571}
9572
9573ImGuiID ImGuiWindow::GetID(const void* ptr)
9574{
9575 ImGuiID seed = IDStack.back();
9576 ImGuiID id = ImHashData(data_p: &ptr, data_size: sizeof(void*), seed);
9577#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9578 ImGuiContext& g = *Ctx;
9579 if (g.DebugHookIdInfo == id)
9580 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_Pointer, data_id: ptr, NULL);
9581#endif
9582 return id;
9583}
9584
9585ImGuiID ImGuiWindow::GetID(int n)
9586{
9587 ImGuiID seed = IDStack.back();
9588 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
9589#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9590 ImGuiContext& g = *Ctx;
9591 if (g.DebugHookIdInfo == id)
9592 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
9593#endif
9594 return id;
9595}
9596
9597// This is only used in rare/specific situations to manufacture an ID out of nowhere.
9598// FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
9599ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs)
9600{
9601 ImGuiID seed = IDStack.back();
9602 ImVec2 p_rel = ImGui::WindowPosAbsToRel(window: this, p: p_abs);
9603 ImGuiID id = ImHashData(data_p: &p_rel, data_size: sizeof(p_rel), seed);
9604 return id;
9605}
9606
9607// "
9608ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
9609{
9610 ImGuiID seed = IDStack.back();
9611 ImRect r_rel = ImGui::WindowRectAbsToRel(window: this, r: r_abs);
9612 ImGuiID id = ImHashData(data_p: &r_rel, data_size: sizeof(r_rel), seed);
9613 return id;
9614}
9615
9616void ImGui::PushID(const char* str_id)
9617{
9618 ImGuiContext& g = *GImGui;
9619 ImGuiWindow* window = g.CurrentWindow;
9620 ImGuiID id = window->GetID(str: str_id);
9621 window->IDStack.push_back(v: id);
9622}
9623
9624void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
9625{
9626 ImGuiContext& g = *GImGui;
9627 ImGuiWindow* window = g.CurrentWindow;
9628 ImGuiID id = window->GetID(str: str_id_begin, str_end: str_id_end);
9629 window->IDStack.push_back(v: id);
9630}
9631
9632void ImGui::PushID(const void* ptr_id)
9633{
9634 ImGuiContext& g = *GImGui;
9635 ImGuiWindow* window = g.CurrentWindow;
9636 ImGuiID id = window->GetID(ptr: ptr_id);
9637 window->IDStack.push_back(v: id);
9638}
9639
9640void ImGui::PushID(int int_id)
9641{
9642 ImGuiContext& g = *GImGui;
9643 ImGuiWindow* window = g.CurrentWindow;
9644 ImGuiID id = window->GetID(n: int_id);
9645 window->IDStack.push_back(v: id);
9646}
9647
9648// Push a given id value ignoring the ID stack as a seed.
9649void ImGui::PushOverrideID(ImGuiID id)
9650{
9651 ImGuiContext& g = *GImGui;
9652 ImGuiWindow* window = g.CurrentWindow;
9653#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9654 if (g.DebugHookIdInfo == id)
9655 DebugHookIdInfo(id, data_type: ImGuiDataType_ID, NULL, NULL);
9656#endif
9657 window->IDStack.push_back(v: id);
9658}
9659
9660// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
9661// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
9662// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
9663ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
9664{
9665 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
9666#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9667 ImGuiContext& g = *GImGui;
9668 if (g.DebugHookIdInfo == id)
9669 DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
9670#endif
9671 return id;
9672}
9673
9674ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
9675{
9676 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
9677#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9678 ImGuiContext& g = *GImGui;
9679 if (g.DebugHookIdInfo == id)
9680 DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
9681#endif
9682 return id;
9683}
9684
9685void ImGui::PopID()
9686{
9687 ImGuiWindow* window = GImGui->CurrentWindow;
9688 if (window->IDStack.Size <= 1)
9689 {
9690 IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!");
9691 return;
9692 }
9693 window->IDStack.pop_back();
9694}
9695
9696ImGuiID ImGui::GetID(const char* str_id)
9697{
9698 ImGuiWindow* window = GImGui->CurrentWindow;
9699 return window->GetID(str: str_id);
9700}
9701
9702ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9703{
9704 ImGuiWindow* window = GImGui->CurrentWindow;
9705 return window->GetID(str: str_id_begin, str_end: str_id_end);
9706}
9707
9708ImGuiID ImGui::GetID(const void* ptr_id)
9709{
9710 ImGuiWindow* window = GImGui->CurrentWindow;
9711 return window->GetID(ptr: ptr_id);
9712}
9713
9714ImGuiID ImGui::GetID(int int_id)
9715{
9716 ImGuiWindow* window = GImGui->CurrentWindow;
9717 return window->GetID(n: int_id);
9718}
9719IM_MSVC_RUNTIME_CHECKS_RESTORE
9720
9721//-----------------------------------------------------------------------------
9722// [SECTION] INPUTS
9723//-----------------------------------------------------------------------------
9724// - GetModForLRModKey() [Internal]
9725// - FixupKeyChord() [Internal]
9726// - GetKeyData() [Internal]
9727// - GetKeyIndex() [Internal]
9728// - GetKeyName()
9729// - GetKeyChordName() [Internal]
9730// - CalcTypematicRepeatAmount() [Internal]
9731// - GetTypematicRepeatRate() [Internal]
9732// - GetKeyPressedAmount() [Internal]
9733// - GetKeyMagnitude2d() [Internal]
9734//-----------------------------------------------------------------------------
9735// - UpdateKeyRoutingTable() [Internal]
9736// - GetRoutingIdFromOwnerId() [Internal]
9737// - GetShortcutRoutingData() [Internal]
9738// - CalcRoutingScore() [Internal]
9739// - SetShortcutRouting() [Internal]
9740// - TestShortcutRouting() [Internal]
9741//-----------------------------------------------------------------------------
9742// - IsKeyDown()
9743// - IsKeyPressed()
9744// - IsKeyReleased()
9745//-----------------------------------------------------------------------------
9746// - IsMouseDown()
9747// - IsMouseClicked()
9748// - IsMouseReleased()
9749// - IsMouseDoubleClicked()
9750// - GetMouseClickedCount()
9751// - IsMouseHoveringRect() [Internal]
9752// - IsMouseDragPastThreshold() [Internal]
9753// - IsMouseDragging()
9754// - GetMousePos()
9755// - SetMousePos() [Internal]
9756// - GetMousePosOnOpeningCurrentPopup()
9757// - IsMousePosValid()
9758// - IsAnyMouseDown()
9759// - GetMouseDragDelta()
9760// - ResetMouseDragDelta()
9761// - GetMouseCursor()
9762// - SetMouseCursor()
9763//-----------------------------------------------------------------------------
9764// - UpdateAliasKey()
9765// - GetMergedModsFromKeys()
9766// - UpdateKeyboardInputs()
9767// - UpdateMouseInputs()
9768//-----------------------------------------------------------------------------
9769// - LockWheelingWindow [Internal]
9770// - FindBestWheelingWindow [Internal]
9771// - UpdateMouseWheel() [Internal]
9772//-----------------------------------------------------------------------------
9773// - SetNextFrameWantCaptureKeyboard()
9774// - SetNextFrameWantCaptureMouse()
9775//-----------------------------------------------------------------------------
9776// - GetInputSourceName() [Internal]
9777// - DebugPrintInputEvent() [Internal]
9778// - UpdateInputEvents() [Internal]
9779//-----------------------------------------------------------------------------
9780// - GetKeyOwner() [Internal]
9781// - TestKeyOwner() [Internal]
9782// - SetKeyOwner() [Internal]
9783// - SetItemKeyOwner() [Internal]
9784// - Shortcut() [Internal]
9785//-----------------------------------------------------------------------------
9786
9787static ImGuiKeyChord GetModForLRModKey(ImGuiKey key)
9788{
9789 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9790 return ImGuiMod_Ctrl;
9791 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9792 return ImGuiMod_Shift;
9793 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9794 return ImGuiMod_Alt;
9795 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9796 return ImGuiMod_Super;
9797 return ImGuiMod_None;
9798}
9799
9800ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9801{
9802 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9803 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9804 if (IsLRModKey(key))
9805 key_chord |= GetModForLRModKey(key);
9806 return key_chord;
9807}
9808
9809ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9810{
9811 ImGuiContext& g = *ctx;
9812
9813 // Special storage location for mods
9814 if (key & ImGuiMod_Mask_)
9815 key = ConvertSingleModFlagToKey(key);
9816
9817 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9818 return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
9819}
9820
9821// Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
9822static const char* const GKeyNames[] =
9823{
9824 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9825 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9826 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9827 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9828 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9829 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9830 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9831 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9832 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9833 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9834 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9835 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9836 "AppBack", "AppForward", "Oem102",
9837 "GamepadStart", "GamepadBack",
9838 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9839 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9840 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9841 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9842 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9843 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9844 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9845};
9846IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9847
9848const char* ImGui::GetKeyName(ImGuiKey key)
9849{
9850 if (key == ImGuiKey_None)
9851 return "None";
9852 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9853 if (key & ImGuiMod_Mask_)
9854 key = ConvertSingleModFlagToKey(key);
9855 if (!IsNamedKey(key))
9856 return "Unknown";
9857
9858 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9859}
9860
9861// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9862// Lifetime of return value: valid until next call to same function.
9863const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9864{
9865 ImGuiContext& g = *GImGui;
9866
9867 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9868 if (IsLRModKey(key))
9869 key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9870 ImFormatString(buf: g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), fmt: "%s%s%s%s%s",
9871 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9872 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9873 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9874 (key_chord & ImGuiMod_Super) ? "Super+" : "",
9875 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9876 size_t len;
9877 if (key == ImGuiKey_None && key_chord != 0)
9878 if ((len = ImStrlen(s: g.TempKeychordName)) != 0) // Remove trailing '+'
9879 g.TempKeychordName[len - 1] = 0;
9880 return g.TempKeychordName;
9881}
9882
9883// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9884// t1 = current time (e.g.: g.Time)
9885// An event is triggered at:
9886// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
9887int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9888{
9889 if (t1 == 0.0f)
9890 return 1;
9891 if (t0 >= t1)
9892 return 0;
9893 if (repeat_rate <= 0.0f)
9894 return (t0 < repeat_delay) && (t1 >= repeat_delay);
9895 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9896 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9897 const int count = count_t1 - count_t0;
9898 return count;
9899}
9900
9901void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9902{
9903 ImGuiContext& g = *GImGui;
9904 switch (flags & ImGuiInputFlags_RepeatRateMask_)
9905 {
9906 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9907 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9908 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9909 }
9910}
9911
9912// Return value representing the number of presses in the last time period, for the given repeat rate
9913// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9914int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9915{
9916 ImGuiContext& g = *GImGui;
9917 const ImGuiKeyData* key_data = GetKeyData(key);
9918 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)
9919 return 0;
9920 const float t = key_data->DownDuration;
9921 return CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay, repeat_rate);
9922}
9923
9924// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9925ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9926{
9927 return ImVec2(
9928 GetKeyData(key: key_right)->AnalogValue - GetKeyData(key: key_left)->AnalogValue,
9929 GetKeyData(key: key_down)->AnalogValue - GetKeyData(key: key_up)->AnalogValue);
9930}
9931
9932// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9933// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
9934// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
9935// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9936static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9937{
9938 ImGuiContext& g = *GImGui;
9939 rt->EntriesNext.resize(new_size: 0);
9940 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9941 {
9942 const int new_routing_start_idx = rt->EntriesNext.Size;
9943 ImGuiKeyRoutingData* routing_entry;
9944 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9945 {
9946 routing_entry = &rt->Entries[old_routing_idx];
9947 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9948 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9949 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9950 routing_entry->RoutingNextScore = 255;
9951 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9952 continue;
9953 rt->EntriesNext.push_back(v: *routing_entry); // Write alive ones into new buffer
9954
9955 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9956 // This is the result of previous frame's SetShortcutRouting() call.
9957 if (routing_entry->Mods == g.IO.KeyMods)
9958 {
9959 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
9960 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9961 {
9962 owner_data->OwnerCurr = routing_entry->RoutingCurr;
9963 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9964 }
9965 }
9966 }
9967
9968 // Rewrite linked-list
9969 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9970 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9971 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9972 }
9973 rt->Entries.swap(rhs&: rt->EntriesNext); // Swap new and old indexes
9974}
9975
9976// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9977static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9978{
9979 ImGuiContext& g = *GImGui;
9980 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9981}
9982
9983ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9984{
9985 // Majority of shortcuts will be Key + any number of Mods
9986 // We accept _Single_ mod with ImGuiKey_None.
9987 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
9988 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
9989 // - Shortcut(ImGuiMod_Ctrl); // Legal
9990 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
9991 ImGuiContext& g = *GImGui;
9992 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9993 ImGuiKeyRoutingData* routing_data;
9994 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9995 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9996 if (key == ImGuiKey_None)
9997 key = ConvertSingleModFlagToKey(key: mods);
9998 IM_ASSERT(IsNamedKey(key));
9999
10000 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
10001 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
10002 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
10003 {
10004 routing_data = &rt->Entries[idx];
10005 if (routing_data->Mods == mods)
10006 return routing_data;
10007 }
10008
10009 // Add to linked-list
10010 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
10011 rt->Entries.push_back(v: ImGuiKeyRoutingData());
10012 routing_data = &rt->Entries[routing_data_idx];
10013 routing_data->Mods = (ImU16)mods;
10014 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
10015 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
10016 return routing_data;
10017}
10018
10019// Current score encoding (lower is highest priority):
10020// - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
10021// - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
10022// - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
10023// - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
10024// - 254: ImGuiInputFlags_RouteGlobal
10025// - 255: never route
10026// 'flags' should include an explicit routing policy
10027static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
10028{
10029 ImGuiContext& g = *GImGui;
10030 if (flags & ImGuiInputFlags_RouteFocused)
10031 {
10032 // ActiveID gets top priority
10033 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
10034 if (owner_id != 0 && g.ActiveId == owner_id)
10035 return 1;
10036
10037 // Score based on distance to focused window (lower is better)
10038 // Assuming both windows are submitting a routing request,
10039 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
10040 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
10041 // Assuming only WindowA is submitting a routing request,
10042 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
10043 // This essentially follow the window->ParentWindowForFocusRoute chain.
10044 if (focus_scope_id == 0)
10045 return 255;
10046 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
10047 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
10048 return 3 + index_in_focus_path;
10049 return 255;
10050 }
10051 else if (flags & ImGuiInputFlags_RouteActive)
10052 {
10053 if (owner_id != 0 && g.ActiveId == owner_id)
10054 return 1;
10055 return 255;
10056 }
10057 else if (flags & ImGuiInputFlags_RouteGlobal)
10058 {
10059 if (flags & ImGuiInputFlags_RouteOverActive)
10060 return 0;
10061 if (flags & ImGuiInputFlags_RouteOverFocused)
10062 return 2;
10063 return 254;
10064 }
10065 IM_ASSERT(0);
10066 return 0;
10067}
10068
10069// - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
10070// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
10071// - 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.
10072static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
10073{
10074 // Mimic 'ignore_char_inputs' logic in InputText()
10075 ImGuiContext& g = *GImGui;
10076
10077 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
10078 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10079 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
10080 if (ignore_char_inputs)
10081 return false;
10082
10083 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
10084 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10085 if (key == ImGuiKey_None)
10086 return false;
10087 return g.KeysMayBeCharInput.TestBit(n: key);
10088}
10089
10090// Request a desired route for an input chord (key + mods).
10091// Return true if the route is available this frame.
10092// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
10093// (Conceptually this does a "Submit for next frame" + "Test for current frame".
10094// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
10095bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10096{
10097 ImGuiContext& g = *GImGui;
10098 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10099 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
10100 else
10101 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
10102 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
10103 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
10104 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
10105
10106 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
10107 key_chord = FixupKeyChord(key_chord);
10108
10109 // [DEBUG] Debug break requested by user
10110 if (g.DebugBreakInShortcutRouting == key_chord)
10111 IM_DEBUG_BREAK();
10112
10113 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
10114 if (g.NavWindow == NULL)
10115 return false;
10116
10117 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
10118 if (flags & ImGuiInputFlags_RouteAlways)
10119 {
10120 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
10121 return true;
10122 }
10123
10124 // Specific culling when there's an active item.
10125 if (g.ActiveId != 0 && g.ActiveId != owner_id)
10126 {
10127 if (flags & ImGuiInputFlags_RouteActive)
10128 return false;
10129
10130 // Cull shortcuts with no modifiers when it could generate a character.
10131 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
10132 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
10133 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
10134 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
10135 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
10136 {
10137 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
10138 return false;
10139 }
10140
10141 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
10142 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
10143 {
10144 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10145 if (key == ImGuiKey_None)
10146 key = ConvertSingleModFlagToKey(key: (ImGuiKey)(key_chord & ImGuiMod_Mask_));
10147 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10148 return false;
10149 }
10150 }
10151
10152 // Where do we evaluate route for?
10153 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
10154 if (flags & ImGuiInputFlags_RouteFromRootWindow)
10155 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
10156
10157 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
10158 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
10159 if (score == 255)
10160 return false;
10161
10162 // Submit routing for NEXT frame (assuming score is sufficient)
10163 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
10164 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
10165 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
10166 if (score < routing_data->RoutingNextScore)
10167 {
10168 routing_data->RoutingNext = owner_id;
10169 routing_data->RoutingNextScore = (ImU8)score;
10170 }
10171
10172 // Return routing state for CURRENT frame
10173 if (routing_data->RoutingCurr == owner_id)
10174 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
10175 return routing_data->RoutingCurr == owner_id;
10176}
10177
10178// Currently unused by core (but used by tests)
10179// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
10180bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
10181{
10182 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
10183 key_chord = FixupKeyChord(key_chord);
10184 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
10185 return routing_data->RoutingCurr == routing_id;
10186}
10187
10188// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
10189// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
10190bool ImGui::IsKeyDown(ImGuiKey key)
10191{
10192 return IsKeyDown(key, ImGuiKeyOwner_Any);
10193}
10194
10195bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
10196{
10197 const ImGuiKeyData* key_data = GetKeyData(key);
10198 if (!key_data->Down)
10199 return false;
10200 if (!TestKeyOwner(key, owner_id))
10201 return false;
10202 return true;
10203}
10204
10205bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
10206{
10207 return IsKeyPressed(key, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10208}
10209
10210// Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
10211bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
10212{
10213 const ImGuiKeyData* key_data = GetKeyData(key);
10214 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)
10215 return false;
10216 const float t = key_data->DownDuration;
10217 if (t < 0.0f)
10218 return false;
10219 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
10220 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
10221 flags |= ImGuiInputFlags_Repeat;
10222
10223 bool pressed = (t == 0.0f);
10224 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
10225 {
10226 float repeat_delay, repeat_rate;
10227 GetTypematicRepeatRate(flags, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
10228 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
10229 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
10230 {
10231 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
10232 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
10233 ImGuiContext& g = *GImGui;
10234 double key_pressed_time = g.Time - t + 0.00001f;
10235 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
10236 pressed = false;
10237 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
10238 pressed = false;
10239 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
10240 pressed = false;
10241 }
10242 }
10243 if (!pressed)
10244 return false;
10245 if (!TestKeyOwner(key, owner_id))
10246 return false;
10247 return true;
10248}
10249
10250bool ImGui::IsKeyReleased(ImGuiKey key)
10251{
10252 return IsKeyReleased(key, ImGuiKeyOwner_Any);
10253}
10254
10255bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
10256{
10257 const ImGuiKeyData* key_data = GetKeyData(key);
10258 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
10259 return false;
10260 if (!TestKeyOwner(key, owner_id))
10261 return false;
10262 return true;
10263}
10264
10265bool ImGui::IsMouseDown(ImGuiMouseButton button)
10266{
10267 ImGuiContext& g = *GImGui;
10268 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10269 return g.IO.MouseDown[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
10270}
10271
10272bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
10273{
10274 ImGuiContext& g = *GImGui;
10275 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10276 return g.IO.MouseDown[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
10277}
10278
10279bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
10280{
10281 return IsMouseClicked(button, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10282}
10283
10284bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
10285{
10286 ImGuiContext& g = *GImGui;
10287 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10288 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)
10289 return false;
10290 const float t = g.IO.MouseDownDuration[button];
10291 if (t < 0.0f)
10292 return false;
10293 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
10294
10295 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
10296 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay: g.IO.KeyRepeatDelay, repeat_rate: g.IO.KeyRepeatRate) > 0);
10297 if (!pressed)
10298 return false;
10299
10300 if (!TestKeyOwner(key: MouseButtonToKey(button), owner_id))
10301 return false;
10302
10303 return true;
10304}
10305
10306bool ImGui::IsMouseReleased(ImGuiMouseButton button)
10307{
10308 ImGuiContext& g = *GImGui;
10309 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10310 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
10311}
10312
10313bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
10314{
10315 ImGuiContext& g = *GImGui;
10316 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10317 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
10318}
10319
10320// Use if you absolutely need to distinguish single-click from double-click by introducing a delay.
10321// Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test.
10322// This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
10323bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay)
10324{
10325 ImGuiContext& g = *GImGui;
10326 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10327 const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]);
10328 return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay);
10329}
10330
10331bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
10332{
10333 ImGuiContext& g = *GImGui;
10334 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10335 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any);
10336}
10337
10338bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
10339{
10340 ImGuiContext& g = *GImGui;
10341 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10342 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), owner_id);
10343}
10344
10345int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
10346{
10347 ImGuiContext& g = *GImGui;
10348 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10349 return g.IO.MouseClickedCount[button];
10350}
10351
10352// Test if mouse cursor is hovering given rectangle
10353// NB- Rectangle is clipped by our current clip setting
10354// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
10355bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
10356{
10357 ImGuiContext& g = *GImGui;
10358
10359 // Clip
10360 ImRect rect_clipped(r_min, r_max);
10361 if (clip)
10362 rect_clipped.ClipWith(r: g.CurrentWindow->ClipRect);
10363
10364 // Hit testing, expanded for touch input
10365 if (!rect_clipped.ContainsWithPad(p: g.IO.MousePos, pad: g.Style.TouchExtraPadding))
10366 return false;
10367 if (!g.MouseViewport->GetMainRect().Overlaps(r: rect_clipped))
10368 return false;
10369 return true;
10370}
10371
10372// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
10373// [Internal] This doesn't test if the button is pressed
10374bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
10375{
10376 ImGuiContext& g = *GImGui;
10377 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10378 if (lock_threshold < 0.0f)
10379 lock_threshold = g.IO.MouseDragThreshold;
10380 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
10381}
10382
10383bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
10384{
10385 ImGuiContext& g = *GImGui;
10386 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10387 if (!g.IO.MouseDown[button])
10388 return false;
10389 return IsMouseDragPastThreshold(button, lock_threshold);
10390}
10391
10392ImVec2 ImGui::GetMousePos()
10393{
10394 ImGuiContext& g = *GImGui;
10395 return g.IO.MousePos;
10396}
10397
10398// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
10399// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
10400void ImGui::TeleportMousePos(const ImVec2& pos)
10401{
10402 ImGuiContext& g = *GImGui;
10403 g.IO.MousePos = g.IO.MousePosPrev = pos;
10404 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
10405 g.IO.WantSetMousePos = true;
10406 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
10407}
10408
10409// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
10410ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
10411{
10412 ImGuiContext& g = *GImGui;
10413 if (g.BeginPopupStack.Size > 0)
10414 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
10415 return g.IO.MousePos;
10416}
10417
10418// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
10419bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
10420{
10421 // The assert is only to silence a false-positive in XCode Static Analysis.
10422 // 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).
10423 IM_ASSERT(GImGui != NULL);
10424 const float MOUSE_INVALID = -256000.0f;
10425 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
10426 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
10427}
10428
10429// [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.
10430bool ImGui::IsAnyMouseDown()
10431{
10432 ImGuiContext& g = *GImGui;
10433 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
10434 if (g.IO.MouseDown[n])
10435 return true;
10436 return false;
10437}
10438
10439// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
10440// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
10441// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
10442ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
10443{
10444 ImGuiContext& g = *GImGui;
10445 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10446 if (lock_threshold < 0.0f)
10447 lock_threshold = g.IO.MouseDragThreshold;
10448 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
10449 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
10450 if (IsMousePosValid(mouse_pos: &g.IO.MousePos) && IsMousePosValid(mouse_pos: &g.IO.MouseClickedPos[button]))
10451 return g.IO.MousePos - g.IO.MouseClickedPos[button];
10452 return ImVec2(0.0f, 0.0f);
10453}
10454
10455void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
10456{
10457 ImGuiContext& g = *GImGui;
10458 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10459 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
10460 g.IO.MouseClickedPos[button] = g.IO.MousePos;
10461}
10462
10463// Get desired mouse cursor shape.
10464// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
10465// updated during the frame, and locked in EndFrame()/Render().
10466// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
10467ImGuiMouseCursor ImGui::GetMouseCursor()
10468{
10469 ImGuiContext& g = *GImGui;
10470 return g.MouseCursor;
10471}
10472
10473// We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
10474// 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
10475// handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
10476void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
10477{
10478 ImGuiContext& g = *GImGui;
10479 g.MouseCursor = cursor_type;
10480}
10481
10482static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
10483{
10484 IM_ASSERT(ImGui::IsAliasKey(key));
10485 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
10486 key_data->Down = v;
10487 key_data->AnalogValue = analog_value;
10488}
10489
10490// [Internal] Do not use directly
10491static ImGuiKeyChord GetMergedModsFromKeys()
10492{
10493 ImGuiKeyChord mods = 0;
10494 if (ImGui::IsKeyDown(key: ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
10495 if (ImGui::IsKeyDown(key: ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
10496 if (ImGui::IsKeyDown(key: ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
10497 if (ImGui::IsKeyDown(key: ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
10498 return mods;
10499}
10500
10501static void ImGui::UpdateKeyboardInputs()
10502{
10503 ImGuiContext& g = *GImGui;
10504 ImGuiIO& io = g.IO;
10505
10506 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10507 io.ClearInputKeys();
10508
10509 // Update aliases
10510 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
10511 UpdateAliasKey(key: MouseButtonToKey(button: n), v: io.MouseDown[n], analog_value: io.MouseDown[n] ? 1.0f : 0.0f);
10512 UpdateAliasKey(key: ImGuiKey_MouseWheelX, v: io.MouseWheelH != 0.0f, analog_value: io.MouseWheelH);
10513 UpdateAliasKey(key: ImGuiKey_MouseWheelY, v: io.MouseWheel != 0.0f, analog_value: io.MouseWheel);
10514
10515 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
10516 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10517 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10518 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
10519 const ImGuiKeyChord prev_key_mods = io.KeyMods;
10520 io.KeyMods = GetMergedModsFromKeys();
10521 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
10522 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
10523 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
10524 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
10525 if (prev_key_mods != io.KeyMods)
10526 g.LastKeyModsChangeTime = g.Time;
10527 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
10528 g.LastKeyModsChangeFromNoneTime = g.Time;
10529
10530 // Clear gamepad data if disabled
10531 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
10532 for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
10533 {
10534 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
10535 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
10536 }
10537
10538 // Update keys
10539 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
10540 {
10541 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10542 key_data->DownDurationPrev = key_data->DownDuration;
10543 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
10544 if (key_data->DownDuration == 0.0f)
10545 {
10546 if (IsKeyboardKey(key: (ImGuiKey)key))
10547 g.LastKeyboardKeyPressTime = g.Time;
10548 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
10549 g.LastKeyboardKeyPressTime = g.Time;
10550 }
10551 }
10552
10553 // Update keys/input owner (named keys only): one entry per key
10554 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
10555 {
10556 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10557 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
10558 owner_data->OwnerCurr = owner_data->OwnerNext;
10559 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.
10560 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
10561 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
10562 }
10563
10564 // Update key routing (for e.g. shortcuts)
10565 UpdateKeyRoutingTable(rt: &g.KeysRoutingTable);
10566}
10567
10568static void ImGui::UpdateMouseInputs()
10569{
10570 ImGuiContext& g = *GImGui;
10571 ImGuiIO& io = g.IO;
10572
10573 // Mouse Wheel swapping flag
10574 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
10575 // - We avoid doing it on OSX as it the OS input layer handles this already.
10576 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
10577 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
10578 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
10579
10580 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
10581 if (IsMousePosValid(mouse_pos: &io.MousePos))
10582 io.MousePos = g.MouseLastValidPos = ImFloor(v: io.MousePos);
10583
10584 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
10585 if (IsMousePosValid(mouse_pos: &io.MousePos) && IsMousePosValid(mouse_pos: &io.MousePosPrev))
10586 io.MouseDelta = io.MousePos - io.MousePosPrev;
10587 else
10588 io.MouseDelta = ImVec2(0.0f, 0.0f);
10589
10590 // Update stationary timer.
10591 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
10592 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
10593 const bool mouse_stationary = (ImLengthSqr(lhs: io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
10594 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
10595 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
10596
10597 // 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.
10598 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
10599 g.NavHighlightItemUnderNav = false;
10600
10601 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
10602 {
10603 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
10604 io.MouseClickedCount[i] = 0; // Will be filled below
10605 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
10606 if (io.MouseReleased[i])
10607 io.MouseReleasedTime[i] = g.Time;
10608 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
10609 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
10610 if (io.MouseClicked[i])
10611 {
10612 bool is_repeated_click = false;
10613 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
10614 {
10615 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10616 if (ImLengthSqr(lhs: delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
10617 is_repeated_click = true;
10618 }
10619 if (is_repeated_click)
10620 io.MouseClickedLastCount[i]++;
10621 else
10622 io.MouseClickedLastCount[i] = 1;
10623 io.MouseClickedTime[i] = g.Time;
10624 io.MouseClickedPos[i] = io.MousePos;
10625 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10626 io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10627 io.MouseDragMaxDistanceSqr[i] = 0.0f;
10628 }
10629 else if (io.MouseDown[i])
10630 {
10631 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10632 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10633 io.MouseDragMaxDistanceSqr[i] = ImMax(lhs: io.MouseDragMaxDistanceSqr[i], rhs: ImLengthSqr(lhs: delta_from_click_pos));
10634 io.MouseDragMaxDistanceAbs[i].x = ImMax(lhs: io.MouseDragMaxDistanceAbs[i].x, rhs: delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
10635 io.MouseDragMaxDistanceAbs[i].y = ImMax(lhs: io.MouseDragMaxDistanceAbs[i].y, rhs: delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
10636 }
10637
10638 // We provide io.MouseDoubleClicked[] as a legacy service
10639 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10640
10641 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
10642 if (io.MouseClicked[i])
10643 g.NavHighlightItemUnderNav = false;
10644 }
10645}
10646
10647static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10648{
10649 ImGuiContext& g = *GImGui;
10650 if (window)
10651 g.WheelingWindowReleaseTimer = ImMin(lhs: g.WheelingWindowReleaseTimer + ImAbs(x: wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, rhs: WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10652 else
10653 g.WheelingWindowReleaseTimer = 0.0f;
10654 if (g.WheelingWindow == window)
10655 return;
10656 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10657 g.WheelingWindow = window;
10658 g.WheelingWindowRefMousePos = g.IO.MousePos;
10659 if (window == NULL)
10660 {
10661 g.WheelingWindowStartFrame = -1;
10662 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10663 }
10664}
10665
10666static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10667{
10668 // For each axis, find window in the hierarchy that may want to use scrolling
10669 ImGuiContext& g = *GImGui;
10670 ImGuiWindow* windows[2] = { NULL, NULL };
10671 for (int axis = 0; axis < 2; axis++)
10672 if (wheel[axis] != 0.0f)
10673 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10674 {
10675 // Bubble up into parent window if:
10676 // - a child window doesn't allow any scrolling.
10677 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10678 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10679 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10680 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10681 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10682 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10683 break; // select this window
10684 }
10685 if (windows[0] == NULL && windows[1] == NULL)
10686 return NULL;
10687
10688 // If there's only one window or only one axis then there's no ambiguity
10689 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10690 return windows[1] ? windows[1] : windows[0];
10691
10692 // If candidate are different windows we need to decide which one to prioritize
10693 // - First frame: only find a winner if one axis is zero.
10694 // - Subsequent frames: only find a winner when one is more than the other.
10695 if (g.WheelingWindowStartFrame == -1)
10696 g.WheelingWindowStartFrame = g.FrameCount;
10697 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10698 {
10699 g.WheelingWindowWheelRemainder = wheel;
10700 return NULL;
10701 }
10702 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10703}
10704
10705// Called by NewFrame()
10706void ImGui::UpdateMouseWheel()
10707{
10708 // Reset the locked window if we move the mouse or after the timer elapses.
10709 // 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)
10710 ImGuiContext& g = *GImGui;
10711 if (g.WheelingWindow != NULL)
10712 {
10713 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10714 if (IsMousePosValid() && ImLengthSqr(lhs: g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10715 g.WheelingWindowReleaseTimer = 0.0f;
10716 if (g.WheelingWindowReleaseTimer <= 0.0f)
10717 LockWheelingWindow(NULL, wheel_amount: 0.0f);
10718 }
10719
10720 ImVec2 wheel;
10721 wheel.x = TestKeyOwner(key: ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10722 wheel.y = TestKeyOwner(key: ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10723
10724 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10725 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10726 if (!mouse_window || mouse_window->Collapsed)
10727 return;
10728
10729 // Zoom / Scale window
10730 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10731 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10732 {
10733 LockWheelingWindow(window: mouse_window, wheel_amount: wheel.y);
10734 ImGuiWindow* window = mouse_window;
10735 const float new_font_scale = ImClamp(v: window->FontWindowScale + g.IO.MouseWheel * 0.10f, mn: 0.50f, mx: 2.50f);
10736 const float scale = new_font_scale / window->FontWindowScale;
10737 window->FontWindowScale = new_font_scale;
10738 if (window == window->RootWindow)
10739 {
10740 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10741 SetWindowPos(window, pos: window->Pos + offset, cond: 0);
10742 window->Size = ImTrunc(v: window->Size * scale);
10743 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
10744 }
10745 return;
10746 }
10747 if (g.IO.KeyCtrl)
10748 return;
10749
10750 // Mouse wheel scrolling
10751 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10752 if (g.IO.MouseWheelRequestAxisSwap)
10753 wheel = ImVec2(wheel.y, 0.0f);
10754
10755 // Maintain a rough average of moving magnitude on both axes
10756 // FIXME: should by based on wall clock time rather than frame-counter
10757 g.WheelingAxisAvg.x = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.x, sample: ImAbs(x: wheel.x), n: 30);
10758 g.WheelingAxisAvg.y = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.y, sample: ImAbs(x: wheel.y), n: 30);
10759
10760 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10761 wheel += g.WheelingWindowWheelRemainder;
10762 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10763 if (wheel.x == 0.0f && wheel.y == 0.0f)
10764 return;
10765
10766 // Mouse wheel scrolling: find target and apply
10767 // - don't renew lock if axis doesn't apply on the window.
10768 // - select a main axis when both axes are being moved.
10769 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10770 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10771 {
10772 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10773 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10774 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10775 if (do_scroll[ImGuiAxis_X])
10776 {
10777 LockWheelingWindow(window, wheel_amount: wheel.x);
10778 float max_step = window->InnerRect.GetWidth() * 0.67f;
10779 float scroll_step = ImTrunc(f: ImMin(lhs: 2 * window->FontRefSize, rhs: max_step));
10780 SetScrollX(window, scroll_x: window->Scroll.x - wheel.x * scroll_step);
10781 g.WheelingWindowScrolledFrame = g.FrameCount;
10782 }
10783 if (do_scroll[ImGuiAxis_Y])
10784 {
10785 LockWheelingWindow(window, wheel_amount: wheel.y);
10786 float max_step = window->InnerRect.GetHeight() * 0.67f;
10787 float scroll_step = ImTrunc(f: ImMin(lhs: 5 * window->FontRefSize, rhs: max_step));
10788 SetScrollY(window, scroll_y: window->Scroll.y - wheel.y * scroll_step);
10789 g.WheelingWindowScrolledFrame = g.FrameCount;
10790 }
10791 }
10792}
10793
10794void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10795{
10796 ImGuiContext& g = *GImGui;
10797 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10798}
10799
10800void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10801{
10802 ImGuiContext& g = *GImGui;
10803 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10804}
10805
10806#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10807static const char* GetInputSourceName(ImGuiInputSource source)
10808{
10809 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10810 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
10811 if (source < 0 || source >= ImGuiInputSource_COUNT)
10812 return "Unknown";
10813 return input_source_names[source];
10814}
10815static const char* GetMouseSourceName(ImGuiMouseSource source)
10816{
10817 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10818 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT);
10819 if (source < 0 || source >= ImGuiMouseSource_COUNT)
10820 return "Unknown";
10821 return mouse_source_names[source];
10822}
10823static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10824{
10825 ImGuiContext& g = *GImGui;
10826 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; }
10827 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; }
10828 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; }
10829 if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10830 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; }
10831 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10832 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10833}
10834#endif
10835
10836// Process input queue
10837// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10838// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10839// - 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)
10840void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10841{
10842 ImGuiContext& g = *GImGui;
10843 ImGuiIO& io = g.IO;
10844
10845 // Only trickle chars<>key when working with InputText()
10846 // FIXME: InputText() could parse event trail?
10847 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10848 const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10849
10850 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
10851 int mouse_button_changed = 0x00;
10852 ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
10853
10854 int event_n = 0;
10855 for (; event_n < g.InputEventsQueue.Size; event_n++)
10856 {
10857 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10858 if (e->Type == ImGuiInputEventType_MousePos)
10859 {
10860 if (g.IO.WantSetMousePos)
10861 continue;
10862 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10863 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10864 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10865 break;
10866 io.MousePos = event_pos;
10867 io.MouseSource = e->MousePos.MouseSource;
10868 mouse_moved = true;
10869 }
10870 else if (e->Type == ImGuiInputEventType_MouseButton)
10871 {
10872 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10873 const ImGuiMouseButton button = e->MouseButton.Button;
10874 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10875 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10876 break;
10877 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10878 break;
10879 io.MouseDown[button] = e->MouseButton.Down;
10880 io.MouseSource = e->MouseButton.MouseSource;
10881 mouse_button_changed |= (1 << button);
10882 }
10883 else if (e->Type == ImGuiInputEventType_MouseWheel)
10884 {
10885 // Trickling Rule: Stop processing queued events if we got multiple action on the event
10886 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10887 break;
10888 io.MouseWheelH += e->MouseWheel.WheelX;
10889 io.MouseWheel += e->MouseWheel.WheelY;
10890 io.MouseSource = e->MouseWheel.MouseSource;
10891 mouse_wheeled = true;
10892 }
10893 else if (e->Type == ImGuiInputEventType_MouseViewport)
10894 {
10895 io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10896 }
10897 else if (e->Type == ImGuiInputEventType_Key)
10898 {
10899 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10900 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10901 continue;
10902 ImGuiKey key = e->Key.Key;
10903 IM_ASSERT(key != ImGuiKey_None);
10904 ImGuiKeyData* key_data = GetKeyData(key);
10905 const int key_data_index = (int)(key_data - g.IO.KeysData);
10906 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(n: key_data_index) || mouse_button_changed != 0))
10907 break;
10908
10909 const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(key_chord: GetMergedModsFromKeys() | key);
10910 if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
10911 break;
10912
10913 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.
10914 {
10915 key_changed = true;
10916 key_changed_mask.SetBit(key_data_index);
10917 if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
10918 key_changed_nonchar = true;
10919 }
10920
10921 key_data->Down = e->Key.Down;
10922 key_data->AnalogValue = e->Key.AnalogValue;
10923 }
10924 else if (e->Type == ImGuiInputEventType_Text)
10925 {
10926 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10927 continue;
10928 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10929 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10930 break;
10931 if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar)
10932 break;
10933 unsigned int c = e->Text.Char;
10934 io.InputQueueCharacters.push_back(v: c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10935 if (trickle_interleaved_nonchar_keys_and_text)
10936 text_inputted = true;
10937 }
10938 else if (e->Type == ImGuiInputEventType_Focus)
10939 {
10940 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10941 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10942 const bool focus_lost = !e->AppFocused.Focused;
10943 io.AppFocusLost = focus_lost;
10944 }
10945 else
10946 {
10947 IM_ASSERT(0 && "Unknown event!");
10948 }
10949 }
10950
10951 // Record trail (for domain-specific applications wanting to access a precise trail)
10952 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10953 for (int n = 0; n < event_n; n++)
10954 g.InputEventsTrail.push_back(v: g.InputEventsQueue[n]);
10955
10956 // [DEBUG]
10957#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10958 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10959 for (int n = 0; n < g.InputEventsQueue.Size; n++)
10960 DebugPrintInputEvent(prefix: n < event_n ? "Processed" : "Remaining", e: &g.InputEventsQueue[n]);
10961#endif
10962
10963 // Remaining events will be processed on the next frame
10964 if (event_n == g.InputEventsQueue.Size)
10965 g.InputEventsQueue.resize(new_size: 0);
10966 else
10967 g.InputEventsQueue.erase(it: g.InputEventsQueue.Data, it_last: g.InputEventsQueue.Data + event_n);
10968
10969 // Clear buttons state when focus is lost
10970 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10971 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10972 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10973 if (g.IO.AppFocusLost)
10974 {
10975 g.IO.ClearInputKeys();
10976 g.IO.ClearInputMouse();
10977 }
10978}
10979
10980ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10981{
10982 if (!IsNamedKeyOrMod(key))
10983 return ImGuiKeyOwner_NoOwner;
10984
10985 ImGuiContext& g = *GImGui;
10986 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
10987 ImGuiID owner_id = owner_data->OwnerCurr;
10988
10989 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10990 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10991 return ImGuiKeyOwner_NoOwner;
10992
10993 return owner_id;
10994}
10995
10996// TestKeyOwner(..., ID) : (owner == None || owner == ID)
10997// TestKeyOwner(..., None) : (owner == None)
10998// TestKeyOwner(..., Any) : no owner test
10999// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
11000bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
11001{
11002 if (!IsNamedKeyOrMod(key))
11003 return true;
11004
11005 ImGuiContext& g = *GImGui;
11006 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
11007 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
11008 return false;
11009
11010 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
11011 if (owner_id == ImGuiKeyOwner_Any)
11012 return (owner_data->LockThisFrame == false);
11013
11014 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
11015 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
11016 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
11017 if (owner_data->OwnerCurr != owner_id)
11018 {
11019 if (owner_data->LockThisFrame)
11020 return false;
11021 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
11022 return false;
11023 }
11024
11025 return true;
11026}
11027
11028// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
11029// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
11030// - SetKeyOwner(..., None) : clears owner
11031// - SetKeyOwner(..., Any, !Lock) : illegal (assert)
11032// - SetKeyOwner(..., Any or None, Lock) : set lock
11033void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
11034{
11035 ImGuiContext& g = *GImGui;
11036 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)
11037 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
11038 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
11039
11040 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
11041 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
11042
11043 // We cannot lock by default as it would likely break lots of legacy code.
11044 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
11045 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
11046 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
11047}
11048
11049// Rarely used helper
11050void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
11051{
11052 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(key: ImGuiMod_Ctrl, owner_id, flags); }
11053 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(key: ImGuiMod_Shift, owner_id, flags); }
11054 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(key: ImGuiMod_Alt, owner_id, flags); }
11055 if (key_chord & ImGuiMod_Super) { SetKeyOwner(key: ImGuiMod_Super, owner_id, flags); }
11056 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner(key: (ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
11057}
11058
11059// This is more or less equivalent to:
11060// if (IsItemHovered() || IsItemActive())
11061// SetKeyOwner(key, GetItemID());
11062// 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.
11063// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
11064// 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.
11065void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
11066{
11067 ImGuiContext& g = *GImGui;
11068 ImGuiID id = g.LastItemData.ID;
11069 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
11070 return;
11071 if ((flags & ImGuiInputFlags_CondMask_) == 0)
11072 flags |= ImGuiInputFlags_CondDefault_;
11073 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
11074 {
11075 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
11076 SetKeyOwner(key, owner_id: id, flags: flags & ~ImGuiInputFlags_CondMask_);
11077 }
11078}
11079
11080void ImGui::SetItemKeyOwner(ImGuiKey key)
11081{
11082 SetItemKeyOwner(key, flags: ImGuiInputFlags_None);
11083}
11084
11085// This is the only public API until we expose owner_id versions of the API as replacements.
11086bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
11087{
11088 return IsKeyChordPressed(key_chord, flags: ImGuiInputFlags_None, ImGuiKeyOwner_Any);
11089}
11090
11091// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
11092bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11093{
11094 ImGuiContext& g = *GImGui;
11095 key_chord = FixupKeyChord(key_chord);
11096 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
11097 if (g.IO.KeyMods != mods)
11098 return false;
11099
11100 // Special storage location for mods
11101 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
11102 if (key == ImGuiKey_None)
11103 key = ConvertSingleModFlagToKey(key: mods);
11104 if (!IsKeyPressed(key, flags: (flags & ImGuiInputFlags_RepeatMask_), owner_id))
11105 return false;
11106 return true;
11107}
11108
11109void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11110{
11111 ImGuiContext& g = *GImGui;
11112 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
11113 g.NextItemData.Shortcut = key_chord;
11114 g.NextItemData.ShortcutFlags = flags;
11115}
11116
11117// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
11118void ImGui::ItemHandleShortcut(ImGuiID id)
11119{
11120 ImGuiContext& g = *GImGui;
11121 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
11122 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
11123
11124 if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
11125 return;
11126 if (flags & ImGuiInputFlags_Tooltip)
11127 {
11128 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
11129 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
11130 }
11131 if (!Shortcut(key_chord: g.NextItemData.Shortcut, flags: flags & ImGuiInputFlags_SupportedByShortcut, owner_id: id) || g.NavActivateId != 0)
11132 return;
11133
11134 // FIXME: Generalize Activation queue?
11135 g.NavActivateId = id; // Will effectively disable clipping.
11136 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
11137 //if (g.ActiveId == 0 || g.ActiveId == id)
11138 g.NavActivateDownId = g.NavActivatePressedId = id;
11139 NavHighlightActivated(id);
11140}
11141
11142bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11143{
11144 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
11145}
11146
11147bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11148{
11149 ImGuiContext& g = *GImGui;
11150 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
11151
11152 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
11153 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
11154 flags |= ImGuiInputFlags_RouteFocused;
11155
11156 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
11157 // Effectively makes Shortcut() always input-owner aware.
11158 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
11159 owner_id = GetRoutingIdFromOwnerId(owner_id);
11160
11161 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11162 return false;
11163
11164 // Submit route
11165 if (!SetShortcutRouting(key_chord, flags, owner_id))
11166 return false;
11167
11168 // Default repeat behavior for Shortcut()
11169 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
11170 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
11171 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
11172
11173 if (!IsKeyChordPressed(key_chord, flags, owner_id))
11174 return false;
11175
11176 // Claim mods during the press
11177 SetKeyOwnersForKeyChord(key_chord: key_chord & ImGuiMod_Mask_, owner_id);
11178
11179 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
11180 return true;
11181}
11182
11183//-----------------------------------------------------------------------------
11184// [SECTION] ERROR CHECKING, STATE RECOVERY
11185//-----------------------------------------------------------------------------
11186// - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
11187// - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11188// - ErrorCheckNewFrameSanityChecks()
11189// - ErrorCheckEndFrameSanityChecks()
11190// - ErrorRecoveryStoreState()
11191// - ErrorRecoveryTryToRecoverState()
11192// - ErrorRecoveryTryToRecoverWindowState()
11193// - ErrorLog()
11194//-----------------------------------------------------------------------------
11195
11196// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
11197// Called by IMGUI_CHECKVERSION().
11198// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
11199// If this triggers you have mismatched headers and compiled code versions.
11200// - It could be because of a build issue (using new headers with old compiled code)
11201// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
11202// THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
11203// Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
11204// Otherwise it is possible that different compilation units would see different structure layout.
11205// If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
11206bool 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)
11207{
11208 bool error = false;
11209 if (strcmp(s1: version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
11210 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
11211 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
11212 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
11213 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
11214 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
11215 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
11216 return !error;
11217}
11218
11219// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos()
11220// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing
11221// windows, table column contents size used for auto-resizing columns, group size).
11222// This was causing issues and ambiguities and we needed to retire that.
11223// From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED.
11224//
11225// Previously this would make the window content size ~200x200:
11226// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE
11227// Instead, please submit an item:
11228// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
11229// Alternative:
11230// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
11231//
11232// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item,
11233// and with a position that would grow the parent contents size.
11234//
11235// Advanced:
11236// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos())
11237// had a side-effect on layout! In particular this caused problem to compute group boundaries.
11238// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the
11239// group to be taller because auto-sizing generally adds padding on bottom and right side.
11240// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect.
11241// Using vertical alignment patterns would frequently trigger this sorts of issue.
11242// - See https://github.com/ocornut/imgui/issues/5548 for more details.
11243void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11244{
11245 ImGuiContext& g = *GImGui;
11246 ImGuiWindow* window = g.CurrentWindow;
11247 IM_ASSERT(window->DC.IsSetPos);
11248 window->DC.IsSetPos = false;
11249 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
11250 return;
11251 if (window->SkipItems)
11252 return;
11253 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.");
11254
11255 // For reference, the old behavior was essentially:
11256 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11257}
11258
11259static void ImGui::ErrorCheckNewFrameSanityChecks()
11260{
11261 ImGuiContext& g = *GImGui;
11262
11263 // Check user IM_ASSERT macro
11264 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
11265 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
11266 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
11267 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
11268 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
11269 if (true) IM_ASSERT(1); else IM_ASSERT(0);
11270
11271 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
11272 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
11273#ifdef __EMSCRIPTEN__
11274 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
11275 g.IO.DeltaTime = 0.00001f;
11276#endif
11277
11278 // Check user data
11279 // (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)
11280 IM_ASSERT(g.Initialized);
11281 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
11282 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
11283 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
11284 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
11285 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
11286 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
11287 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!");
11288 IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders.
11289 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
11290 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
11291 IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes);
11292
11293 // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
11294 if (g.IO.ConfigErrorRecovery)
11295 IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
11296
11297#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11298 if (g.IO.FontGlobalScale > 1.0f)
11299 IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!");
11300
11301 // Remap legacy names
11302 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
11303 {
11304 g.IO.ConfigNavMoveSetMousePos = true;
11305 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
11306 }
11307 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
11308 {
11309 g.IO.ConfigNavCaptureKeyboard = false;
11310 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
11311 }
11312 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts)
11313 {
11314 g.IO.ConfigDpiScaleFonts = false;
11315 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts;
11316 }
11317 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
11318 {
11319 g.IO.ConfigDpiScaleViewports = false;
11320 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports;
11321 }
11322
11323 // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
11324 if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
11325 g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
11326 if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
11327 g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); };
11328#endif
11329
11330 // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
11331 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
11332 IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11333 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
11334 IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11335
11336 // Perform simple checks: multi-viewport and platform windows support
11337 if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
11338 {
11339 if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
11340 {
11341 IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
11342 IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
11343 IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
11344 IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
11345 IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
11346 IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
11347 IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
11348 IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
11349 IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
11350 if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
11351 IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
11352 }
11353 else
11354 {
11355 // Disable feature, our backends do not support it
11356 g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
11357 }
11358
11359 // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
11360 for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
11361 {
11362 IM_UNUSED(mon);
11363 IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
11364 IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
11365 IM_ASSERT(mon.DpiScale > 0.0f && mon.DpiScale < 99.0f && "Monitor DpiScale is invalid."); // Typical correct values would be between 1.0f and 4.0f
11366 }
11367 }
11368}
11369
11370static void ImGui::ErrorCheckEndFrameSanityChecks()
11371{
11372 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
11373 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
11374 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
11375 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
11376 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
11377 // while still correctly asserting on mid-frame key press events.
11378 ImGuiContext& g = *GImGui;
11379 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
11380 IM_UNUSED(g);
11381 IM_UNUSED(key_mods);
11382 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
11383 IM_UNUSED(key_mods);
11384
11385 IM_ASSERT(g.CurrentWindowStack.Size == 1);
11386 IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
11387}
11388
11389// Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
11390void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
11391{
11392 ImGuiContext& g = *GImGui;
11393 state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
11394 state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
11395 state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
11396 state_out->SizeOfColorStack = (short)g.ColorStack.Size;
11397 state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
11398 state_out->SizeOfFontStack = (short)g.FontStack.Size;
11399 state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
11400 state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
11401 state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
11402 state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
11403 state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
11404}
11405
11406// Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
11407// Called by e.g. EndFrame() but may be called for manual recovery.
11408// Attempt to recover full window stack.
11409void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
11410{
11411 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
11412 ImGuiContext& g = *GImGui;
11413 while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
11414 {
11415 // Recap:
11416 // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
11417 // - Always call a matching End() for each Begin() call, regardless of its return value!
11418 // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
11419 // - We will fix that in a future major update.
11420 ImGuiWindow* window = g.CurrentWindow;
11421 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11422 {
11423 if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
11424 {
11425 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11426 EndTable();
11427 }
11428 else
11429 {
11430 IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
11431 EndChild();
11432 }
11433 }
11434 else
11435 {
11436 IM_ASSERT_USER_ERROR(0, "Missing End()");
11437 End();
11438 }
11439 }
11440 if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
11441 ErrorRecoveryTryToRecoverWindowState(state_in);
11442}
11443
11444// Called by e.g. End() but may be called for manual recovery.
11445// Read '// Error Handling [BETA]' block in imgui_internal.h for details.
11446// Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
11447void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
11448{
11449 ImGuiContext& g = *GImGui;
11450
11451 while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
11452 {
11453 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11454 EndTable();
11455 }
11456
11457 ImGuiWindow* window = g.CurrentWindow;
11458
11459 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
11460 while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
11461 {
11462 IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
11463 EndTabBar();
11464 }
11465 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
11466 {
11467 IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
11468 EndMultiSelect();
11469 }
11470 if (window->DC.MenuBarAppending) //-V1044
11471 {
11472 IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()");
11473 EndMenuBar();
11474 }
11475 while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
11476 {
11477 IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
11478 TreePop();
11479 }
11480 while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
11481 {
11482 IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
11483 EndGroup();
11484 }
11485 IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
11486 while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
11487 {
11488 IM_ASSERT_USER_ERROR(0, "Missing PopID()");
11489 PopID();
11490 }
11491 while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
11492 {
11493 IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
11494 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11495 EndDisabled();
11496 else
11497 {
11498 EndDisabledOverrideReenable();
11499 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
11500 }
11501 }
11502 IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
11503 while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
11504 {
11505 IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
11506 PopStyleColor();
11507 }
11508 while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
11509 {
11510 IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
11511 PopItemFlag();
11512 }
11513 while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
11514 {
11515 IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
11516 PopStyleVar();
11517 }
11518 while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
11519 {
11520 IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
11521 PopFont();
11522 }
11523 while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
11524 {
11525 IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
11526 PopFocusScope();
11527 }
11528 //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
11529}
11530
11531bool ImGui::ErrorLog(const char* msg)
11532{
11533 ImGuiContext& g = *GImGui;
11534
11535 // Output to debug log
11536#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11537 ImGuiWindow* window = g.CurrentWindow;
11538
11539 if (g.IO.ConfigErrorRecoveryEnableDebugLog)
11540 {
11541 if (g.ErrorFirst)
11542 IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
11543 g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
11544 IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
11545 }
11546 g.ErrorFirst = false;
11547
11548 // Output to tooltip
11549 if (g.IO.ConfigErrorRecoveryEnableTooltip)
11550 {
11551 if (g.WithinFrameScope && BeginErrorTooltip())
11552 {
11553 if (g.ErrorCountCurrentFrame < 20)
11554 {
11555 Text(fmt: "In window '%s': %s", window ? window->Name : "NULL", msg);
11556 if (window && (!window->IsFallbackWindow || window->WasActive))
11557 GetForegroundDrawList(window)->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
11558 }
11559 if (g.ErrorCountCurrentFrame == 20)
11560 Text(fmt: "(and more errors)");
11561 // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
11562 EndErrorTooltip();
11563 }
11564 g.ErrorCountCurrentFrame++;
11565 }
11566#endif
11567
11568 // Output to callback
11569 if (g.ErrorCallback != NULL)
11570 g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
11571
11572 // Return whether we should assert
11573 return g.IO.ConfigErrorRecoveryEnableAssert;
11574}
11575
11576void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
11577{
11578#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11579 ImGuiContext& g = *GImGui;
11580 if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false)
11581 g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
11582 if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
11583 {
11584 Text(fmt: "Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
11585 BulletText(fmt: "Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
11586 BulletText(fmt: "Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
11587 //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.
11588 BulletText(fmt: "Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
11589 Separator();
11590 if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker)
11591 {
11592 Text(fmt: "(Hold CTRL to: use ");
11593 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11594 if (SmallButton(label: "Item Picker"))
11595 DebugStartItemPicker();
11596 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11597 Text(fmt: " to break in item call-stack, or ");
11598 }
11599 else
11600 {
11601 Text(fmt: "(Hold CTRL to ");
11602 }
11603 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11604 if (SmallButton(label: "Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
11605 g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
11606 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11607 Text(fmt: ")");
11608 EndErrorTooltip();
11609 }
11610
11611 if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
11612 {
11613 Separator();
11614 Text(fmt: "(Hold CTRL to:");
11615 SameLine();
11616 if (SmallButton(label: "Enable Asserts"))
11617 g.IO.ConfigErrorRecoveryEnableAssert = true;
11618 //SameLine();
11619 //if (SmallButton("Hide Error Tooltips"))
11620 // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
11621 SameLine(offset_from_start_x: 0, spacing: 0);
11622 Text(fmt: ")");
11623 EndErrorTooltip();
11624 }
11625#endif
11626}
11627
11628// Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it.
11629bool ImGui::BeginErrorTooltip()
11630{
11631 ImGuiContext& g = *GImGui;
11632 ImGuiWindow* window = FindWindowByName(name: "##Tooltip_Error");
11633 const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
11634 PushStyleColor(idx: ImGuiCol_PopupBg, col: ImLerp(a: g.Style.Colors[ImGuiCol_PopupBg], b: ImVec4(1.0f, 0.0f, 0.0f, 1.0f), t: 0.15f));
11635 if (use_locked_pos)
11636 SetNextWindowPos(pos: g.ErrorTooltipLockedPos);
11637 bool is_visible = Begin(name: "##Tooltip_Error", NULL, flags: ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
11638 PopStyleColor();
11639 if (is_visible && g.CurrentWindow->BeginCount == 1)
11640 {
11641 SeparatorText(label: "MESSAGE FROM DEAR IMGUI");
11642 BringWindowToDisplayFront(window: g.CurrentWindow);
11643 BringWindowToFocusFront(window: g.CurrentWindow);
11644 g.ErrorTooltipLockedPos = GetWindowPos();
11645 }
11646 else if (!is_visible)
11647 {
11648 End();
11649 }
11650 return is_visible;
11651}
11652
11653void ImGui::EndErrorTooltip()
11654{
11655 End();
11656}
11657
11658//-----------------------------------------------------------------------------
11659// [SECTION] ITEM SUBMISSION
11660//-----------------------------------------------------------------------------
11661// - KeepAliveID()
11662// - ItemAdd()
11663//-----------------------------------------------------------------------------
11664
11665// 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().
11666void ImGui::KeepAliveID(ImGuiID id)
11667{
11668 ImGuiContext& g = *GImGui;
11669 if (g.ActiveId == id)
11670 g.ActiveIdIsAlive = id;
11671 if (g.DeactivatedItemData.ID == id)
11672 g.DeactivatedItemData.IsAlive = true;
11673}
11674
11675// Declare item bounding box for clipping and interaction.
11676// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
11677// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
11678// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
11679IM_MSVC_RUNTIME_CHECKS_OFF
11680bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
11681{
11682 ImGuiContext& g = *GImGui;
11683 ImGuiWindow* window = g.CurrentWindow;
11684
11685 // Set item data
11686 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
11687 g.LastItemData.ID = id;
11688 g.LastItemData.Rect = bb;
11689 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
11690 g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
11691 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
11692 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
11693
11694 if (id != 0)
11695 {
11696 KeepAliveID(id);
11697
11698 // Directional navigation processing
11699 // Runs prior to clipping early-out
11700 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
11701 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
11702 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
11703 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
11704 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
11705 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
11706 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
11707 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
11708 if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
11709 {
11710 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
11711 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
11712 if (g.NavId == id || g.NavAnyRequest)
11713 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
11714 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
11715 NavProcessItem();
11716 }
11717
11718 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
11719 ItemHandleShortcut(id);
11720 }
11721
11722 // Lightweight clear of SetNextItemXXX data.
11723 g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
11724 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
11725
11726#ifdef IMGUI_ENABLE_TEST_ENGINE
11727 if (id != 0)
11728 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
11729#endif
11730
11731 // Clipping test
11732 // (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')
11733 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
11734 const bool is_rect_visible = bb.Overlaps(r: window->ClipRect);
11735 if (!is_rect_visible)
11736 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
11737 if (!g.ItemUnclipByLog)
11738 return false;
11739
11740 // [DEBUG]
11741#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11742 if (id != 0)
11743 {
11744 if (id == g.DebugLocateId)
11745 DebugLocateItemResolveWithLastItem();
11746
11747 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
11748 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
11749 // READ THE FAQ: https://dearimgui.com/faq
11750 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!");
11751
11752 // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED.
11753 // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd().
11754#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
11755 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0)
11756 {
11757 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.
11758 int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1);
11759 if (*p_alive == g.FrameCount)
11760 *p_highlight = g.FrameCount;
11761 *p_alive = g.FrameCount;
11762 if (*p_highlight >= g.FrameCount - 1)
11763 window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f);
11764 }
11765#endif
11766 }
11767 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
11768 //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
11769 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
11770#endif
11771
11772 if (id != 0 && g.DeactivatedItemData.ID == id)
11773 g.DeactivatedItemData.ElapseFrame = g.FrameCount;
11774
11775 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
11776 if (is_rect_visible)
11777 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
11778 if (IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
11779 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
11780 return true;
11781}
11782IM_MSVC_RUNTIME_CHECKS_RESTORE
11783
11784//-----------------------------------------------------------------------------
11785// [SECTION] LAYOUT
11786//-----------------------------------------------------------------------------
11787// - ItemSize()
11788// - SameLine()
11789// - GetCursorScreenPos()
11790// - SetCursorScreenPos()
11791// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
11792// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
11793// - GetCursorStartPos()
11794// - Indent()
11795// - Unindent()
11796// - SetNextItemWidth()
11797// - PushItemWidth()
11798// - PushMultiItemsWidths()
11799// - PopItemWidth()
11800// - CalcItemWidth()
11801// - CalcItemSize()
11802// - GetTextLineHeight()
11803// - GetTextLineHeightWithSpacing()
11804// - GetFrameHeight()
11805// - GetFrameHeightWithSpacing()
11806// - GetContentRegionMax()
11807// - GetContentRegionAvail(),
11808// - BeginGroup()
11809// - EndGroup()
11810// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11811//-----------------------------------------------------------------------------
11812
11813// Advance cursor given item size for layout.
11814// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11815// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11816// THIS IS IN THE PERFORMANCE CRITICAL PATH.
11817IM_MSVC_RUNTIME_CHECKS_OFF
11818void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11819{
11820 ImGuiContext& g = *GImGui;
11821 ImGuiWindow* window = g.CurrentWindow;
11822 if (window->SkipItems)
11823 return;
11824
11825 // We increase the height in this function to accommodate for baseline offset.
11826 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11827 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11828 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(lhs: 0.0f, rhs: window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11829
11830 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11831 const float line_height = ImMax(lhs: window->DC.CurrLineSize.y, /*ImMax(*/rhs: window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
11832
11833 // Always align ourselves on pixel boundaries
11834 //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]
11835 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11836 window->DC.CursorPosPrevLine.y = line_y1;
11837 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
11838 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
11839 window->DC.CursorMaxPos.x = ImMax(lhs: window->DC.CursorMaxPos.x, rhs: window->DC.CursorPosPrevLine.x);
11840 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11841 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11842
11843 window->DC.PrevLineSize.y = line_height;
11844 window->DC.CurrLineSize.y = 0.0f;
11845 window->DC.PrevLineTextBaseOffset = ImMax(lhs: window->DC.CurrLineTextBaseOffset, rhs: text_baseline_y);
11846 window->DC.CurrLineTextBaseOffset = 0.0f;
11847 window->DC.IsSameLine = window->DC.IsSetPos = false;
11848
11849 // Horizontal layout mode
11850 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11851 SameLine();
11852}
11853IM_MSVC_RUNTIME_CHECKS_RESTORE
11854
11855// Gets back to previous line and continue with horizontal layout
11856// offset_from_start_x == 0 : follow right after previous item
11857// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11858// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11859// spacing_w >= 0 : enforce spacing amount
11860void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11861{
11862 ImGuiContext& g = *GImGui;
11863 ImGuiWindow* window = g.CurrentWindow;
11864 if (window->SkipItems)
11865 return;
11866
11867 if (offset_from_start_x != 0.0f)
11868 {
11869 if (spacing_w < 0.0f)
11870 spacing_w = 0.0f;
11871 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11872 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11873 }
11874 else
11875 {
11876 if (spacing_w < 0.0f)
11877 spacing_w = g.Style.ItemSpacing.x;
11878 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11879 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11880 }
11881 window->DC.CurrLineSize = window->DC.PrevLineSize;
11882 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11883 window->DC.IsSameLine = true;
11884}
11885
11886ImVec2 ImGui::GetCursorScreenPos()
11887{
11888 ImGuiWindow* window = GetCurrentWindowRead();
11889 return window->DC.CursorPos;
11890}
11891
11892void ImGui::SetCursorScreenPos(const ImVec2& pos)
11893{
11894 ImGuiWindow* window = GetCurrentWindow();
11895 window->DC.CursorPos = pos;
11896 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11897 window->DC.IsSetPos = true;
11898}
11899
11900// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11901// 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'.
11902ImVec2 ImGui::GetCursorPos()
11903{
11904 ImGuiWindow* window = GetCurrentWindowRead();
11905 return window->DC.CursorPos - window->Pos + window->Scroll;
11906}
11907
11908float ImGui::GetCursorPosX()
11909{
11910 ImGuiWindow* window = GetCurrentWindowRead();
11911 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11912}
11913
11914float ImGui::GetCursorPosY()
11915{
11916 ImGuiWindow* window = GetCurrentWindowRead();
11917 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11918}
11919
11920void ImGui::SetCursorPos(const ImVec2& local_pos)
11921{
11922 ImGuiWindow* window = GetCurrentWindow();
11923 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11924 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11925 window->DC.IsSetPos = true;
11926}
11927
11928void ImGui::SetCursorPosX(float x)
11929{
11930 ImGuiWindow* window = GetCurrentWindow();
11931 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11932 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11933 window->DC.IsSetPos = true;
11934}
11935
11936void ImGui::SetCursorPosY(float y)
11937{
11938 ImGuiWindow* window = GetCurrentWindow();
11939 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11940 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11941 window->DC.IsSetPos = true;
11942}
11943
11944ImVec2 ImGui::GetCursorStartPos()
11945{
11946 ImGuiWindow* window = GetCurrentWindowRead();
11947 return window->DC.CursorStartPos - window->Pos;
11948}
11949
11950void ImGui::Indent(float indent_w)
11951{
11952 ImGuiContext& g = *GImGui;
11953 ImGuiWindow* window = GetCurrentWindow();
11954 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11955 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11956}
11957
11958void ImGui::Unindent(float indent_w)
11959{
11960 ImGuiContext& g = *GImGui;
11961 ImGuiWindow* window = GetCurrentWindow();
11962 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11963 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11964}
11965
11966// Affect large frame+labels widgets only.
11967void ImGui::SetNextItemWidth(float item_width)
11968{
11969 ImGuiContext& g = *GImGui;
11970 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
11971 g.NextItemData.Width = item_width;
11972}
11973
11974// FIXME: Remove the == 0.0f behavior?
11975void ImGui::PushItemWidth(float item_width)
11976{
11977 ImGuiContext& g = *GImGui;
11978 ImGuiWindow* window = g.CurrentWindow;
11979 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
11980 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11981 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
11982}
11983
11984void ImGui::PushMultiItemsWidths(int components, float w_full)
11985{
11986 ImGuiContext& g = *GImGui;
11987 ImGuiWindow* window = g.CurrentWindow;
11988 IM_ASSERT(components > 0);
11989 const ImGuiStyle& style = g.Style;
11990 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
11991 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11992 float prev_split = w_items;
11993 for (int i = components - 1; i > 0; i--)
11994 {
11995 float next_split = IM_TRUNC(w_items * i / components);
11996 window->DC.ItemWidthStack.push_back(v: ImMax(lhs: prev_split - next_split, rhs: 1.0f));
11997 prev_split = next_split;
11998 }
11999 window->DC.ItemWidth = ImMax(lhs: prev_split, rhs: 1.0f);
12000 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
12001}
12002
12003void ImGui::PopItemWidth()
12004{
12005 ImGuiContext& g = *GImGui;
12006 ImGuiWindow* window = g.CurrentWindow;
12007 if (window->DC.ItemWidthStack.Size <= 0)
12008 {
12009 IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
12010 return;
12011 }
12012 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
12013 window->DC.ItemWidthStack.pop_back();
12014}
12015
12016// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
12017// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
12018float ImGui::CalcItemWidth()
12019{
12020 ImGuiContext& g = *GImGui;
12021 ImGuiWindow* window = g.CurrentWindow;
12022 float w;
12023 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
12024 w = g.NextItemData.Width;
12025 else
12026 w = window->DC.ItemWidth;
12027 if (w < 0.0f)
12028 {
12029 float region_avail_x = GetContentRegionAvail().x;
12030 w = ImMax(lhs: 1.0f, rhs: region_avail_x + w);
12031 }
12032 w = IM_TRUNC(w);
12033 return w;
12034}
12035
12036// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
12037// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
12038// Note that only CalcItemWidth() is publicly exposed.
12039// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
12040ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
12041{
12042 ImVec2 avail;
12043 if (size.x < 0.0f || size.y < 0.0f)
12044 avail = GetContentRegionAvail();
12045
12046 if (size.x == 0.0f)
12047 size.x = default_w;
12048 else if (size.x < 0.0f)
12049 size.x = ImMax(lhs: 4.0f, rhs: avail.x + size.x); // <-- size.x is negative here so we are subtracting
12050
12051 if (size.y == 0.0f)
12052 size.y = default_h;
12053 else if (size.y < 0.0f)
12054 size.y = ImMax(lhs: 4.0f, rhs: avail.y + size.y); // <-- size.y is negative here so we are subtracting
12055
12056 return size;
12057}
12058
12059float ImGui::GetTextLineHeight()
12060{
12061 ImGuiContext& g = *GImGui;
12062 return g.FontSize;
12063}
12064
12065float ImGui::GetTextLineHeightWithSpacing()
12066{
12067 ImGuiContext& g = *GImGui;
12068 return g.FontSize + g.Style.ItemSpacing.y;
12069}
12070
12071float ImGui::GetFrameHeight()
12072{
12073 ImGuiContext& g = *GImGui;
12074 return g.FontSize + g.Style.FramePadding.y * 2.0f;
12075}
12076
12077float ImGui::GetFrameHeightWithSpacing()
12078{
12079 ImGuiContext& g = *GImGui;
12080 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
12081}
12082
12083ImVec2 ImGui::GetContentRegionAvail()
12084{
12085 ImGuiContext& g = *GImGui;
12086 ImGuiWindow* window = g.CurrentWindow;
12087 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
12088 return mx - window->DC.CursorPos;
12089}
12090
12091#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
12092
12093// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
12094// They are bizarre local-coordinates which don't play well with scrolling.
12095ImVec2 ImGui::GetContentRegionMax()
12096{
12097 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
12098}
12099
12100ImVec2 ImGui::GetWindowContentRegionMin()
12101{
12102 ImGuiWindow* window = GImGui->CurrentWindow;
12103 return window->ContentRegionRect.Min - window->Pos;
12104}
12105
12106ImVec2 ImGui::GetWindowContentRegionMax()
12107{
12108 ImGuiWindow* window = GImGui->CurrentWindow;
12109 return window->ContentRegionRect.Max - window->Pos;
12110}
12111#endif
12112
12113// 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.)
12114// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
12115// FIXME-OPT: Could we safely early out on ->SkipItems?
12116void ImGui::BeginGroup()
12117{
12118 ImGuiContext& g = *GImGui;
12119 ImGuiWindow* window = g.CurrentWindow;
12120
12121 g.GroupStack.resize(new_size: g.GroupStack.Size + 1);
12122 ImGuiGroupData& group_data = g.GroupStack.back();
12123 group_data.WindowID = window->ID;
12124 group_data.BackupCursorPos = window->DC.CursorPos;
12125 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
12126 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
12127 group_data.BackupIndent = window->DC.Indent;
12128 group_data.BackupGroupOffset = window->DC.GroupOffset;
12129 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
12130 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
12131 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
12132 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
12133 group_data.BackupIsSameLine = window->DC.IsSameLine;
12134 group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive;
12135 group_data.EmitItem = true;
12136
12137 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
12138 window->DC.Indent = window->DC.GroupOffset;
12139 window->DC.CursorMaxPos = window->DC.CursorPos;
12140 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
12141 if (g.LogEnabled)
12142 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12143}
12144
12145void ImGui::EndGroup()
12146{
12147 ImGuiContext& g = *GImGui;
12148 ImGuiWindow* window = g.CurrentWindow;
12149 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
12150
12151 ImGuiGroupData& group_data = g.GroupStack.back();
12152 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
12153
12154 if (window->DC.IsSetPos)
12155 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
12156
12157 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
12158 ImRect group_bb(group_data.BackupCursorPos, ImMax(lhs: ImMax(lhs: window->DC.CursorMaxPos, rhs: g.LastItemData.Rect.Max), rhs: group_data.BackupCursorPos));
12159 window->DC.CursorPos = group_data.BackupCursorPos;
12160 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
12161 window->DC.CursorMaxPos = ImMax(lhs: group_data.BackupCursorMaxPos, rhs: group_bb.Max);
12162 window->DC.Indent = group_data.BackupIndent;
12163 window->DC.GroupOffset = group_data.BackupGroupOffset;
12164 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
12165 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
12166 window->DC.IsSameLine = group_data.BackupIsSameLine;
12167 if (g.LogEnabled)
12168 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12169
12170 if (!group_data.EmitItem)
12171 {
12172 g.GroupStack.pop_back();
12173 return;
12174 }
12175
12176 window->DC.CurrLineTextBaseOffset = ImMax(lhs: window->DC.PrevLineTextBaseOffset, rhs: 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.
12177 ItemSize(size: group_bb.GetSize());
12178 ItemAdd(bb: group_bb, id: 0, NULL, extra_flags: ImGuiItemFlags_NoTabStop);
12179
12180 // 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.
12181 // 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.
12182 // Also if you grep for LastItemId you'll notice it is only used in that context.
12183 // (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.)
12184 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
12185 const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true);
12186 if (group_contains_curr_active_id)
12187 g.LastItemData.ID = g.ActiveId;
12188 else if (group_contains_deactivated_id)
12189 g.LastItemData.ID = g.DeactivatedItemData.ID;
12190 g.LastItemData.Rect = group_bb;
12191
12192 // Forward Hovered flag
12193 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
12194 if (group_contains_curr_hovered_id)
12195 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
12196
12197 // Forward Edited flag
12198 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
12199 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
12200
12201 // Forward Deactivated flag
12202 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
12203 if (group_contains_deactivated_id)
12204 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
12205
12206 g.GroupStack.pop_back();
12207 if (g.DebugShowGroupRects)
12208 window->DrawList->AddRect(p_min: group_bb.Min, p_max: group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
12209}
12210
12211
12212//-----------------------------------------------------------------------------
12213// [SECTION] SCROLLING
12214//-----------------------------------------------------------------------------
12215
12216// Helper to snap on edges when aiming at an item very close to the edge,
12217// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
12218// When we refactor the scrolling API this may be configurable with a flag?
12219// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
12220static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
12221{
12222 if (target <= snap_min + snap_threshold)
12223 return ImLerp(a: snap_min, b: target, t: center_ratio);
12224 if (target >= snap_max - snap_threshold)
12225 return ImLerp(a: target, b: snap_max, t: center_ratio);
12226 return target;
12227}
12228
12229static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
12230{
12231 ImVec2 scroll = window->Scroll;
12232 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
12233 for (int axis = 0; axis < 2; axis++)
12234 {
12235 if (window->ScrollTarget[axis] < FLT_MAX)
12236 {
12237 float center_ratio = window->ScrollTargetCenterRatio[axis];
12238 float scroll_target = window->ScrollTarget[axis];
12239 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
12240 {
12241 float snap_min = 0.0f;
12242 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
12243 scroll_target = CalcScrollEdgeSnap(target: scroll_target, snap_min, snap_max, snap_threshold: window->ScrollTargetEdgeSnapDist[axis], center_ratio);
12244 }
12245 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
12246 }
12247 scroll[axis] = ImRound64(f: ImMax(lhs: scroll[axis], rhs: 0.0f));
12248 if (!window->Collapsed && !window->SkipItems)
12249 scroll[axis] = ImMin(lhs: scroll[axis], rhs: window->ScrollMax[axis]);
12250 }
12251 return scroll;
12252}
12253
12254void ImGui::ScrollToItem(ImGuiScrollFlags flags)
12255{
12256 ImGuiContext& g = *GImGui;
12257 ImGuiWindow* window = g.CurrentWindow;
12258 ScrollToRectEx(window, rect: g.LastItemData.NavRect, flags);
12259}
12260
12261void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12262{
12263 ScrollToRectEx(window, rect: item_rect, flags);
12264}
12265
12266// Scroll to keep newly navigated item fully into view
12267ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12268{
12269 ImGuiContext& g = *GImGui;
12270 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
12271 scroll_rect.Min.x = ImMin(lhs: scroll_rect.Min.x + window->DecoInnerSizeX1, rhs: scroll_rect.Max.x);
12272 scroll_rect.Min.y = ImMin(lhs: scroll_rect.Min.y + window->DecoInnerSizeY1, rhs: scroll_rect.Max.y);
12273 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
12274 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
12275
12276 // Check that only one behavior is selected per axis
12277 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
12278 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
12279
12280 // Defaults
12281 ImGuiScrollFlags in_flags = flags;
12282 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
12283 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
12284 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
12285 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
12286
12287 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
12288 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
12289 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;
12290 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;
12291
12292 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
12293 {
12294 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
12295 SetScrollFromPosX(window, local_x: item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 0.0f);
12296 else if (item_rect.Max.x >= scroll_rect.Max.x)
12297 SetScrollFromPosX(window, local_x: item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 1.0f);
12298 }
12299 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
12300 {
12301 if (can_be_fully_visible_x)
12302 SetScrollFromPosX(window, local_x: ImTrunc(f: (item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, center_x_ratio: 0.5f);
12303 else
12304 SetScrollFromPosX(window, local_x: item_rect.Min.x - window->Pos.x, center_x_ratio: 0.0f);
12305 }
12306
12307 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
12308 {
12309 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
12310 SetScrollFromPosY(window, local_y: item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 0.0f);
12311 else if (item_rect.Max.y >= scroll_rect.Max.y)
12312 SetScrollFromPosY(window, local_y: item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 1.0f);
12313 }
12314 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
12315 {
12316 if (can_be_fully_visible_y)
12317 SetScrollFromPosY(window, local_y: ImTrunc(f: (item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, center_y_ratio: 0.5f);
12318 else
12319 SetScrollFromPosY(window, local_y: item_rect.Min.y - window->Pos.y, center_y_ratio: 0.0f);
12320 }
12321
12322 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12323 ImVec2 delta_scroll = next_scroll - window->Scroll;
12324
12325 // Also scroll parent window to keep us into view if necessary
12326 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
12327 {
12328 // FIXME-SCROLL: May be an option?
12329 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
12330 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
12331 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
12332 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
12333 delta_scroll += ScrollToRectEx(window: window->ParentWindow, item_rect: ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), flags: in_flags);
12334 }
12335
12336 return delta_scroll;
12337}
12338
12339float ImGui::GetScrollX()
12340{
12341 ImGuiWindow* window = GImGui->CurrentWindow;
12342 return window->Scroll.x;
12343}
12344
12345float ImGui::GetScrollY()
12346{
12347 ImGuiWindow* window = GImGui->CurrentWindow;
12348 return window->Scroll.y;
12349}
12350
12351float ImGui::GetScrollMaxX()
12352{
12353 ImGuiWindow* window = GImGui->CurrentWindow;
12354 return window->ScrollMax.x;
12355}
12356
12357float ImGui::GetScrollMaxY()
12358{
12359 ImGuiWindow* window = GImGui->CurrentWindow;
12360 return window->ScrollMax.y;
12361}
12362
12363void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
12364{
12365 window->ScrollTarget.x = scroll_x;
12366 window->ScrollTargetCenterRatio.x = 0.0f;
12367 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12368}
12369
12370void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
12371{
12372 window->ScrollTarget.y = scroll_y;
12373 window->ScrollTargetCenterRatio.y = 0.0f;
12374 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12375}
12376
12377void ImGui::SetScrollX(float scroll_x)
12378{
12379 ImGuiContext& g = *GImGui;
12380 SetScrollX(window: g.CurrentWindow, scroll_x);
12381}
12382
12383void ImGui::SetScrollY(float scroll_y)
12384{
12385 ImGuiContext& g = *GImGui;
12386 SetScrollY(window: g.CurrentWindow, scroll_y);
12387}
12388
12389// Note that a local position will vary depending on initial scroll value,
12390// This is a little bit confusing so bear with us:
12391// - local_pos = (absolution_pos - window->Pos)
12392// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
12393// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
12394// - They mostly exist because of legacy API.
12395// Following the rules above, when trying to work with scrolling code, consider that:
12396// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
12397// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
12398// 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
12399void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
12400{
12401 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
12402 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
12403 window->ScrollTargetCenterRatio.x = center_x_ratio;
12404 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12405}
12406
12407void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
12408{
12409 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
12410 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
12411 window->ScrollTargetCenterRatio.y = center_y_ratio;
12412 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12413}
12414
12415void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
12416{
12417 ImGuiContext& g = *GImGui;
12418 SetScrollFromPosX(window: g.CurrentWindow, local_x, center_x_ratio);
12419}
12420
12421void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
12422{
12423 ImGuiContext& g = *GImGui;
12424 SetScrollFromPosY(window: g.CurrentWindow, local_y, center_y_ratio);
12425}
12426
12427// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
12428void ImGui::SetScrollHereX(float center_x_ratio)
12429{
12430 ImGuiContext& g = *GImGui;
12431 ImGuiWindow* window = g.CurrentWindow;
12432 float spacing_x = ImMax(lhs: window->WindowPadding.x, rhs: g.Style.ItemSpacing.x);
12433 float target_pos_x = ImLerp(a: g.LastItemData.Rect.Min.x - spacing_x, b: g.LastItemData.Rect.Max.x + spacing_x, t: center_x_ratio);
12434 SetScrollFromPosX(window, local_x: target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
12435
12436 // Tweak: snap on edges when aiming at an item very close to the edge
12437 window->ScrollTargetEdgeSnapDist.x = ImMax(lhs: 0.0f, rhs: window->WindowPadding.x - spacing_x);
12438}
12439
12440// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
12441void ImGui::SetScrollHereY(float center_y_ratio)
12442{
12443 ImGuiContext& g = *GImGui;
12444 ImGuiWindow* window = g.CurrentWindow;
12445 float spacing_y = ImMax(lhs: window->WindowPadding.y, rhs: g.Style.ItemSpacing.y);
12446 float target_pos_y = ImLerp(a: window->DC.CursorPosPrevLine.y - spacing_y, b: window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, t: center_y_ratio);
12447 SetScrollFromPosY(window, local_y: target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
12448
12449 // Tweak: snap on edges when aiming at an item very close to the edge
12450 window->ScrollTargetEdgeSnapDist.y = ImMax(lhs: 0.0f, rhs: window->WindowPadding.y - spacing_y);
12451}
12452
12453//-----------------------------------------------------------------------------
12454// [SECTION] TOOLTIPS
12455//-----------------------------------------------------------------------------
12456
12457bool ImGui::BeginTooltip()
12458{
12459 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
12460}
12461
12462bool ImGui::BeginItemTooltip()
12463{
12464 if (!IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
12465 return false;
12466 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
12467}
12468
12469bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
12470{
12471 ImGuiContext& g = *GImGui;
12472
12473 const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
12474 if (is_dragdrop_tooltip)
12475 {
12476 // Drag and Drop tooltips are positioning differently than other tooltips:
12477 // - offset visibility to increase visibility around mouse.
12478 // - never clamp within outer viewport boundary.
12479 // We call SetNextWindowPos() to enforce position and disable clamping.
12480 // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones).
12481 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
12482 const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
12483 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12484 {
12485 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);
12486 ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
12487 SetNextWindowPos(pos: tooltip_pos, cond: ImGuiCond_None, pivot: tooltip_pivot);
12488 }
12489
12490 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
12491 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
12492 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
12493 }
12494
12495 const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
12496 char window_name[32];
12497 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: window_name_template, g.TooltipOverrideCount);
12498 if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active)
12499 {
12500 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
12501 //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
12502 SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
12503 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: window_name_template, ++g.TooltipOverrideCount);
12504 }
12505
12506 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
12507 Begin(name: window_name, NULL, flags: flags | extra_window_flags);
12508 // 2023-03-09: Added bool return value to the API, but currently always returning true.
12509 // If this ever returns false we need to update BeginDragDropSource() accordingly.
12510 //if (!ret)
12511 // End();
12512 //return ret;
12513 return true;
12514}
12515
12516void ImGui::EndTooltip()
12517{
12518 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
12519 End();
12520}
12521
12522void ImGui::SetTooltip(const char* fmt, ...)
12523{
12524 va_list args;
12525 va_start(args, fmt);
12526 SetTooltipV(fmt, args);
12527 va_end(args);
12528}
12529
12530void ImGui::SetTooltipV(const char* fmt, va_list args)
12531{
12532 if (!BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_OverridePrevious, extra_window_flags: ImGuiWindowFlags_None))
12533 return;
12534 TextV(fmt, args);
12535 EndTooltip();
12536}
12537
12538// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
12539// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
12540void ImGui::SetItemTooltip(const char* fmt, ...)
12541{
12542 va_list args;
12543 va_start(args, fmt);
12544 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
12545 SetTooltipV(fmt, args);
12546 va_end(args);
12547}
12548
12549void ImGui::SetItemTooltipV(const char* fmt, va_list args)
12550{
12551 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
12552 SetTooltipV(fmt, args);
12553}
12554
12555
12556//-----------------------------------------------------------------------------
12557// [SECTION] POPUPS
12558//-----------------------------------------------------------------------------
12559
12560// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
12561bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
12562{
12563 ImGuiContext& g = *GImGui;
12564 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
12565 {
12566 // Return true if any popup is open at the current BeginPopup() level of the popup stack
12567 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
12568 IM_ASSERT(id == 0);
12569 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12570 return g.OpenPopupStack.Size > 0;
12571 else
12572 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
12573 }
12574 else
12575 {
12576 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12577 {
12578 // Return true if the popup is open anywhere in the popup stack
12579 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12580 if (popup_data.PopupId == id)
12581 return true;
12582 return false;
12583 }
12584 else
12585 {
12586 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
12587 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
12588 }
12589 }
12590}
12591
12592bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
12593{
12594 ImGuiContext& g = *GImGui;
12595 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str: str_id);
12596 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
12597 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
12598 return IsPopupOpen(id, popup_flags);
12599}
12600
12601// Also see FindBlockingModal(NULL)
12602ImGuiWindow* ImGui::GetTopMostPopupModal()
12603{
12604 ImGuiContext& g = *GImGui;
12605 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12606 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12607 if (popup->Flags & ImGuiWindowFlags_Modal)
12608 return popup;
12609 return NULL;
12610}
12611
12612// See Demo->Stacked Modal to confirm what this is for.
12613ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
12614{
12615 ImGuiContext& g = *GImGui;
12616 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12617 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12618 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(window: popup))
12619 return popup;
12620 return NULL;
12621}
12622
12623
12624// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
12625// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
12626// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
12627// - WindowA // FindBlockingModal() returns Modal1
12628// - WindowB // .. returns Modal1
12629// - Modal1 // .. returns Modal2
12630// - WindowC // .. returns Modal2
12631// - WindowD // .. returns Modal2
12632// - Modal2 // .. returns Modal2
12633// - WindowE // .. returns NULL
12634// Notes:
12635// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
12636// Only difference is here we check for ->Active/WasActive but it may be unnecessary.
12637ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
12638{
12639 ImGuiContext& g = *GImGui;
12640 if (g.OpenPopupStack.Size <= 0)
12641 return NULL;
12642
12643 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
12644 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12645 {
12646 ImGuiWindow* popup_window = popup_data.Window;
12647 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
12648 continue;
12649 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.
12650 continue;
12651 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
12652 return popup_window;
12653 if (IsWindowWithinBeginStackOf(window, potential_parent: popup_window)) // Window may be over modal
12654 continue;
12655 return popup_window; // Place window right below first block modal
12656 }
12657 return NULL;
12658}
12659
12660void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
12661{
12662 ImGuiContext& g = *GImGui;
12663 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
12664 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
12665 OpenPopupEx(id, popup_flags);
12666}
12667
12668void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
12669{
12670 OpenPopupEx(id, popup_flags);
12671}
12672
12673// Mark popup as open (toggle toward open state).
12674// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
12675// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
12676// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
12677void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
12678{
12679 ImGuiContext& g = *GImGui;
12680 ImGuiWindow* parent_window = g.CurrentWindow;
12681 const int current_stack_size = g.BeginPopupStack.Size;
12682
12683 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
12684 if (IsPopupOpen(id: (ImGuiID)0, popup_flags: ImGuiPopupFlags_AnyPopupId))
12685 return;
12686
12687 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
12688 popup_ref.PopupId = id;
12689 popup_ref.Window = NULL;
12690 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
12691 popup_ref.OpenFrameCount = g.FrameCount;
12692 popup_ref.OpenParentId = parent_window->IDStack.back();
12693 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
12694 popup_ref.OpenMousePos = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
12695
12696 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
12697 if (g.OpenPopupStack.Size < current_stack_size + 1)
12698 {
12699 g.OpenPopupStack.push_back(v: popup_ref);
12700 }
12701 else
12702 {
12703 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
12704 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
12705 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
12706 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
12707 bool keep_existing = false;
12708 if (g.OpenPopupStack[current_stack_size].PopupId == id)
12709 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
12710 keep_existing = true;
12711 if (keep_existing)
12712 {
12713 // No reopen
12714 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
12715 }
12716 else
12717 {
12718 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
12719 ClosePopupToLevel(remaining: current_stack_size, restore_focus_to_window_under_popup: true);
12720 g.OpenPopupStack.push_back(v: popup_ref);
12721 }
12722
12723 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
12724 // This is equivalent to what ClosePopupToLevel() does.
12725 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
12726 // FocusWindow(parent_window);
12727 }
12728}
12729
12730// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
12731// This function closes any popups that are over 'ref_window'.
12732void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
12733{
12734 ImGuiContext& g = *GImGui;
12735 if (g.OpenPopupStack.Size == 0)
12736 return;
12737
12738 // Don't close our own child popup windows.
12739 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
12740 int popup_count_to_keep = 0;
12741 if (ref_window)
12742 {
12743 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
12744 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
12745 {
12746 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
12747 if (!popup.Window)
12748 continue;
12749 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
12750
12751 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
12752 // - Clicking/Focusing Window2 won't close Popup1:
12753 // Window -> Popup1 -> Window2(Ref)
12754 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
12755 // Window -> Popup1(Ref) -> Popup2 -> Popup3
12756 // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
12757 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
12758 // We step through every popup from bottom to top to validate their position relative to reference window.
12759 bool ref_window_is_descendent_of_popup = false;
12760 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
12761 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
12762 //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
12763 if (IsWindowWithinBeginStackOf(window: ref_window, potential_parent: popup_window))
12764 {
12765 ref_window_is_descendent_of_popup = true;
12766 break;
12767 }
12768 if (!ref_window_is_descendent_of_popup)
12769 break;
12770 }
12771 }
12772 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
12773 {
12774 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
12775 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup);
12776 }
12777}
12778
12779void ImGui::ClosePopupsExceptModals()
12780{
12781 ImGuiContext& g = *GImGui;
12782
12783 int popup_count_to_keep;
12784 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
12785 {
12786 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
12787 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
12788 break;
12789 }
12790 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
12791 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup: true);
12792}
12793
12794void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
12795{
12796 ImGuiContext& g = *GImGui;
12797 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
12798 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
12799 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)
12800 for (int n = remaining; n < g.OpenPopupStack.Size; n++)
12801 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);
12802
12803 // Trim open popup stack
12804 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
12805 g.OpenPopupStack.resize(new_size: remaining);
12806
12807 // 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)
12808 if (restore_focus_to_window_under_popup && prev_popup.Window)
12809 {
12810 ImGuiWindow* popup_window = prev_popup.Window;
12811 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
12812 if (focus_window && !focus_window->WasActive)
12813 FocusTopMostWindowUnderOne(under_this_window: popup_window, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
12814 else
12815 FocusWindow(window: focus_window, flags: (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
12816 }
12817}
12818
12819// Close the popup we have begin-ed into.
12820void ImGui::CloseCurrentPopup()
12821{
12822 ImGuiContext& g = *GImGui;
12823 int popup_idx = g.BeginPopupStack.Size - 1;
12824 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
12825 return;
12826
12827 // Closing a menu closes its top-most parent popup (unless a modal)
12828 while (popup_idx > 0)
12829 {
12830 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
12831 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
12832 bool close_parent = false;
12833 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
12834 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
12835 close_parent = true;
12836 if (!close_parent)
12837 break;
12838 popup_idx--;
12839 }
12840 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
12841 ClosePopupToLevel(remaining: popup_idx, restore_focus_to_window_under_popup: true);
12842
12843 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
12844 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
12845 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
12846 if (ImGuiWindow* window = g.NavWindow)
12847 window->DC.NavHideHighlightOneFrame = true;
12848}
12849
12850// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
12851bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
12852{
12853 ImGuiContext& g = *GImGui;
12854 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
12855 {
12856 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12857 return false;
12858 }
12859
12860 char name[20];
12861 IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx()
12862 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "##Popup_%08x", id); // No recycling, so we can close/open during the same frame
12863
12864 bool is_open = Begin(name, NULL, flags: extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
12865 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12866 EndPopup();
12867 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12868 return is_open;
12869}
12870
12871bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags)
12872{
12873 ImGuiContext& g = *GImGui;
12874 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
12875 {
12876 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12877 return false;
12878 }
12879
12880 char name[128];
12881 IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu);
12882 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth
12883 bool is_open = Begin(name, NULL, flags: extra_window_flags | ImGuiWindowFlags_Popup);
12884 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12885 EndPopup();
12886 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12887 return is_open;
12888}
12889
12890bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12891{
12892 ImGuiContext& g = *GImGui;
12893 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12894 {
12895 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12896 return false;
12897 }
12898 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12899 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
12900 return BeginPopupEx(id, extra_window_flags: flags);
12901}
12902
12903// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12904// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12905// - *p_open set back to false in BeginPopupModal() when popup is not open.
12906// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12907bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12908{
12909 ImGuiContext& g = *GImGui;
12910 ImGuiWindow* window = g.CurrentWindow;
12911 const ImGuiID id = window->GetID(str: name);
12912 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
12913 {
12914 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12915 if (p_open && *p_open)
12916 *p_open = false;
12917 return false;
12918 }
12919
12920 // Center modal windows by default for increased visibility
12921 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12922 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12923 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12924 {
12925 const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12926 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_FirstUseEver, pivot: ImVec2(0.5f, 0.5f));
12927 }
12928
12929 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12930 const bool is_open = Begin(name, p_open, flags);
12931 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12932 {
12933 EndPopup();
12934 if (is_open)
12935 ClosePopupToLevel(remaining: g.BeginPopupStack.Size, restore_focus_to_window_under_popup: true);
12936 return false;
12937 }
12938 return is_open;
12939}
12940
12941void ImGui::EndPopup()
12942{
12943 ImGuiContext& g = *GImGui;
12944 ImGuiWindow* window = g.CurrentWindow;
12945 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0)
12946 {
12947 IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!");
12948 return;
12949 }
12950
12951 // 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)
12952 if (g.NavWindow == window)
12953 NavMoveRequestTryWrapping(window, move_flags: ImGuiNavMoveFlags_LoopY);
12954
12955 // Child-popups don't need to be laid out
12956 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
12957 if (window->Flags & ImGuiWindowFlags_ChildWindow)
12958 g.WithinEndChildID = window->ID;
12959 End();
12960 g.WithinEndChildID = backup_within_end_child_id;
12961}
12962
12963// Helper to open a popup if mouse button is released over the item
12964// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12965void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12966{
12967 ImGuiContext& g = *GImGui;
12968 ImGuiWindow* window = g.CurrentWindow;
12969 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12970 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12971 {
12972 ImGuiID id = str_id ? window->GetID(str: 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!
12973 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12974 OpenPopupEx(id, popup_flags);
12975 }
12976}
12977
12978// This is a helper to handle the simplest case of associating one named popup to one given widget.
12979// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12980// - To create a popup with a specific identifier, pass it in str_id.
12981// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12982// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12983// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12984// This is essentially the same as:
12985// id = str_id ? GetID(str_id) : GetItemID();
12986// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12987// return BeginPopup(id);
12988// Which is essentially the same as:
12989// id = str_id ? GetID(str_id) : GetItemID();
12990// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12991// OpenPopup(id);
12992// return BeginPopup(id);
12993// The main difference being that this is tweaked to avoid computing the ID twice.
12994bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12995{
12996 ImGuiContext& g = *GImGui;
12997 ImGuiWindow* window = g.CurrentWindow;
12998 if (window->SkipItems)
12999 return false;
13000 ImGuiID id = str_id ? window->GetID(str: 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!
13001 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
13002 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13003 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13004 OpenPopupEx(id, popup_flags);
13005 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13006}
13007
13008bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
13009{
13010 ImGuiContext& g = *GImGui;
13011 ImGuiWindow* window = g.CurrentWindow;
13012 if (!str_id)
13013 str_id = "window_context";
13014 ImGuiID id = window->GetID(str: str_id);
13015 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13016 if (IsMouseReleased(button: mouse_button) && IsWindowHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13017 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
13018 OpenPopupEx(id, popup_flags);
13019 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13020}
13021
13022bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
13023{
13024 ImGuiContext& g = *GImGui;
13025 ImGuiWindow* window = g.CurrentWindow;
13026 if (!str_id)
13027 str_id = "void_context";
13028 ImGuiID id = window->GetID(str: str_id);
13029 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13030 if (IsMouseReleased(button: mouse_button) && !IsWindowHovered(flags: ImGuiHoveredFlags_AnyWindow))
13031 if (GetTopMostPopupModal() == NULL)
13032 OpenPopupEx(id, popup_flags);
13033 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13034}
13035
13036// 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.)
13037// 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.
13038// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
13039// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
13040// this allows us to have tooltips/popups displayed out of the parent viewport.)
13041ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
13042{
13043 ImVec2 base_pos_clamped = ImClamp(v: ref_pos, mn: r_outer.Min, mx: r_outer.Max - size);
13044 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
13045 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
13046
13047 // Combo Box policy (we want a connecting edge)
13048 if (policy == ImGuiPopupPositionPolicy_ComboBox)
13049 {
13050 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
13051 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13052 {
13053 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13054 if (n != -1 && dir == *last_dir) // Already tried this direction?
13055 continue;
13056 ImVec2 pos;
13057 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
13058 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
13059 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
13060 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
13061 if (!r_outer.Contains(r: ImRect(pos, pos + size)))
13062 continue;
13063 *last_dir = dir;
13064 return pos;
13065 }
13066 }
13067
13068 // Tooltip and Default popup policy
13069 // (Always first try the direction we used on the last frame, if any)
13070 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
13071 {
13072 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
13073 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13074 {
13075 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13076 if (n != -1 && dir == *last_dir) // Already tried this direction?
13077 continue;
13078
13079 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);
13080 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);
13081
13082 // 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)
13083 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
13084 continue;
13085 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
13086 continue;
13087
13088 ImVec2 pos;
13089 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
13090 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
13091
13092 // Clamp top-left corner of popup
13093 pos.x = ImMax(lhs: pos.x, rhs: r_outer.Min.x);
13094 pos.y = ImMax(lhs: pos.y, rhs: r_outer.Min.y);
13095
13096 *last_dir = dir;
13097 return pos;
13098 }
13099 }
13100
13101 // Fallback when not enough room:
13102 *last_dir = ImGuiDir_None;
13103
13104 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
13105 if (policy == ImGuiPopupPositionPolicy_Tooltip)
13106 return ref_pos + ImVec2(2, 2);
13107
13108 // Otherwise try to keep within display
13109 ImVec2 pos = ref_pos;
13110 pos.x = ImMax(lhs: ImMin(lhs: pos.x + size.x, rhs: r_outer.Max.x) - size.x, rhs: r_outer.Min.x);
13111 pos.y = ImMax(lhs: ImMin(lhs: pos.y + size.y, rhs: r_outer.Max.y) - size.y, rhs: r_outer.Min.y);
13112 return pos;
13113}
13114
13115// Note that this is used for popups, which can overlap the non work-area of individual viewports.
13116ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
13117{
13118 ImGuiContext& g = *GImGui;
13119 ImRect r_screen;
13120 if (window->ViewportAllowPlatformMonitorExtend >= 0)
13121 {
13122 // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
13123 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
13124 r_screen.Min = monitor.WorkPos;
13125 r_screen.Max = monitor.WorkPos + monitor.WorkSize;
13126 }
13127 else
13128 {
13129 // Use the full viewport area (not work area) for popups
13130 r_screen = window->Viewport->GetMainRect();
13131 }
13132 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
13133 r_screen.Expand(amount: ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
13134 return r_screen;
13135}
13136
13137ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
13138{
13139 ImGuiContext& g = *GImGui;
13140
13141 ImRect r_outer = GetPopupAllowedExtentRect(window);
13142 if (window->Flags & ImGuiWindowFlags_ChildMenu)
13143 {
13144 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
13145 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
13146 ImGuiWindow* parent_window = window->ParentWindow;
13147 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).
13148 ImRect r_avoid;
13149 if (parent_window->DC.MenuBarAppending)
13150 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
13151 else
13152 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);
13153 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Default);
13154 }
13155 if (window->Flags & ImGuiWindowFlags_Popup)
13156 {
13157 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid: ImRect(window->Pos, window->Pos), policy: ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
13158 }
13159 if (window->Flags & ImGuiWindowFlags_Tooltip)
13160 {
13161 // Position tooltip (always follows mouse + clamp within outer boundaries)
13162 // FIXME:
13163 // - 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).
13164 // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
13165 // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
13166 // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
13167 IM_ASSERT(g.CurrentWindow == window);
13168 const float scale = g.Style.MouseCursorScale;
13169 const ImVec2 ref_pos = NavCalcPreferredRefPos();
13170
13171 if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
13172 {
13173 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
13174 if (r_outer.Contains(r: ImRect(tooltip_pos, tooltip_pos + window->Size)))
13175 return tooltip_pos;
13176 }
13177
13178 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
13179 ImRect r_avoid;
13180 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
13181 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
13182 else
13183 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.
13184 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
13185
13186 return FindBestWindowPosForPopupEx(ref_pos: tooltip_pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Tooltip);
13187 }
13188 IM_ASSERT(0);
13189 return window->Pos;
13190}
13191
13192//-----------------------------------------------------------------------------
13193// [SECTION] WINDOW FOCUS
13194//----------------------------------------------------------------------------
13195// - SetWindowFocus()
13196// - SetNextWindowFocus()
13197// - IsWindowFocused()
13198// - UpdateWindowInFocusOrderList() [Internal]
13199// - BringWindowToFocusFront() [Internal]
13200// - BringWindowToDisplayFront() [Internal]
13201// - BringWindowToDisplayBack() [Internal]
13202// - BringWindowToDisplayBehind() [Internal]
13203// - FindWindowDisplayIndex() [Internal]
13204// - FocusWindow() [Internal]
13205// - FocusTopMostWindowUnderOne() [Internal]
13206//-----------------------------------------------------------------------------
13207
13208void ImGui::SetWindowFocus()
13209{
13210 FocusWindow(window: GImGui->CurrentWindow);
13211}
13212
13213void ImGui::SetWindowFocus(const char* name)
13214{
13215 if (name)
13216 {
13217 if (ImGuiWindow* window = FindWindowByName(name))
13218 FocusWindow(window);
13219 }
13220 else
13221 {
13222 FocusWindow(NULL);
13223 }
13224}
13225
13226void ImGui::SetNextWindowFocus()
13227{
13228 ImGuiContext& g = *GImGui;
13229 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus;
13230}
13231
13232// Similar to IsWindowHovered()
13233bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
13234{
13235 ImGuiContext& g = *GImGui;
13236 ImGuiWindow* ref_window = g.NavWindow;
13237 ImGuiWindow* cur_window = g.CurrentWindow;
13238
13239 if (ref_window == NULL)
13240 return false;
13241 if (flags & ImGuiFocusedFlags_AnyWindow)
13242 return true;
13243
13244 IM_ASSERT(cur_window); // Not inside a Begin()/End()
13245 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
13246 const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
13247 if (flags & ImGuiFocusedFlags_RootWindow)
13248 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy, dock_hierarchy);
13249
13250 if (flags & ImGuiFocusedFlags_ChildWindows)
13251 return IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy, dock_hierarchy);
13252 else
13253 return (ref_window == cur_window);
13254}
13255
13256static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13257{
13258 ImGuiContext& g = *GImGui;
13259 IM_UNUSED(g);
13260 int order = window->FocusOrder;
13261 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13262 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13263 return order;
13264}
13265
13266static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
13267{
13268 ImGuiContext& g = *GImGui;
13269
13270 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
13271 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
13272 if ((just_created || child_flag_changed) && !new_is_explicit_child)
13273 {
13274 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
13275 g.WindowsFocusOrder.push_back(v: window);
13276 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
13277 }
13278 else if (!just_created && child_flag_changed && new_is_explicit_child)
13279 {
13280 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
13281 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
13282 g.WindowsFocusOrder[n]->FocusOrder--;
13283 g.WindowsFocusOrder.erase(it: g.WindowsFocusOrder.Data + window->FocusOrder);
13284 window->FocusOrder = -1;
13285 }
13286 window->IsExplicitChild = new_is_explicit_child;
13287}
13288
13289void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
13290{
13291 ImGuiContext& g = *GImGui;
13292 IM_ASSERT(window == window->RootWindow);
13293
13294 const int cur_order = window->FocusOrder;
13295 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
13296 if (g.WindowsFocusOrder.back() == window)
13297 return;
13298
13299 const int new_order = g.WindowsFocusOrder.Size - 1;
13300 for (int n = cur_order; n < new_order; n++)
13301 {
13302 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
13303 g.WindowsFocusOrder[n]->FocusOrder--;
13304 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
13305 }
13306 g.WindowsFocusOrder[new_order] = window;
13307 window->FocusOrder = (short)new_order;
13308}
13309
13310// Note technically focus related but rather adjacent and close to BringWindowToFocusFront()
13311void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
13312{
13313 ImGuiContext& g = *GImGui;
13314 ImGuiWindow* current_front_window = g.Windows.back();
13315 if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
13316 return;
13317 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
13318 if (g.Windows[i] == window)
13319 {
13320 memmove(dest: &g.Windows[i], src: &g.Windows[i + 1], n: (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
13321 g.Windows[g.Windows.Size - 1] = window;
13322 break;
13323 }
13324}
13325
13326void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
13327{
13328 ImGuiContext& g = *GImGui;
13329 if (g.Windows[0] == window)
13330 return;
13331 for (int i = 0; i < g.Windows.Size; i++)
13332 if (g.Windows[i] == window)
13333 {
13334 memmove(dest: &g.Windows[1], src: &g.Windows[0], n: (size_t)i * sizeof(ImGuiWindow*));
13335 g.Windows[0] = window;
13336 break;
13337 }
13338}
13339
13340void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
13341{
13342 IM_ASSERT(window != NULL && behind_window != NULL);
13343 ImGuiContext& g = *GImGui;
13344 window = window->RootWindow;
13345 behind_window = behind_window->RootWindow;
13346 int pos_wnd = FindWindowDisplayIndex(window);
13347 int pos_beh = FindWindowDisplayIndex(window: behind_window);
13348 if (pos_wnd < pos_beh)
13349 {
13350 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
13351 memmove(dest: &g.Windows.Data[pos_wnd], src: &g.Windows.Data[pos_wnd + 1], n: copy_bytes);
13352 g.Windows[pos_beh - 1] = window;
13353 }
13354 else
13355 {
13356 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
13357 memmove(dest: &g.Windows.Data[pos_beh + 1], src: &g.Windows.Data[pos_beh], n: copy_bytes);
13358 g.Windows[pos_beh] = window;
13359 }
13360}
13361
13362int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
13363{
13364 ImGuiContext& g = *GImGui;
13365 return g.Windows.index_from_ptr(it: g.Windows.find(v: window));
13366}
13367
13368// Moving window to front of display and set focus (which happens to be back of our sorted list)
13369void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
13370{
13371 ImGuiContext& g = *GImGui;
13372
13373 // Modal check?
13374 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
13375 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
13376 {
13377 // This block would typically be reached in two situations:
13378 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
13379 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
13380 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
13381 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13382 BringWindowToDisplayBehind(window, behind_window: blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
13383 ClosePopupsOverWindow(ref_window: GetTopMostPopupModal(), restore_focus_to_window_under_popup: false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
13384 return;
13385 }
13386
13387 // Find last focused child (if any) and focus it instead.
13388 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
13389 window = NavRestoreLastChildNavWindow(window);
13390
13391 // Apply focus
13392 if (g.NavWindow != window)
13393 {
13394 SetNavWindow(window);
13395 if (window && g.NavHighlightItemUnderNav)
13396 g.NavMousePosDirty = true;
13397 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
13398 g.NavLayer = ImGuiNavLayer_Main;
13399 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
13400 g.NavIdIsAlive = false;
13401 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13402
13403 // Close popups if any
13404 ClosePopupsOverWindow(ref_window: window, restore_focus_to_window_under_popup: false);
13405 }
13406
13407 // Move the root window to the top of the pile
13408 IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
13409 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
13410 ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
13411 ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
13412 bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
13413
13414 // Steal active widgets. Some of the cases it triggers includes:
13415 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
13416 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
13417 // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
13418 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
13419 if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
13420 ClearActiveID();
13421
13422 // Passing NULL allow to disable keyboard focus
13423 if (!window)
13424 return;
13425 window->LastFrameJustFocused = g.FrameCount;
13426
13427 // Select in dock node
13428 // For #2304 we avoid applying focus immediately before the tabbar is visible.
13429 //if (dock_node && dock_node->TabBar)
13430 // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
13431
13432 // Bring to front
13433 BringWindowToFocusFront(window: focus_front_window);
13434 if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13435 BringWindowToDisplayFront(window: display_front_window);
13436}
13437
13438void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
13439{
13440 ImGuiContext& g = *GImGui;
13441 int start_idx = g.WindowsFocusOrder.Size - 1;
13442 if (under_this_window != NULL)
13443 {
13444 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
13445 int offset = -1;
13446 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
13447 {
13448 under_this_window = under_this_window->ParentWindow;
13449 offset = 0;
13450 }
13451 start_idx = FindWindowFocusIndex(window: under_this_window) + offset;
13452 }
13453 for (int i = start_idx; i >= 0; i--)
13454 {
13455 // 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.
13456 ImGuiWindow* window = g.WindowsFocusOrder[i];
13457 if (window == ignore_window || !window->WasActive)
13458 continue;
13459 if (filter_viewport != NULL && window->Viewport != filter_viewport)
13460 continue;
13461 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
13462 {
13463 // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
13464 // This is failing (lagging by one frame) for docked windows.
13465 // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
13466 // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
13467 // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
13468 FocusWindow(window, flags);
13469 return;
13470 }
13471 }
13472 FocusWindow(NULL, flags);
13473}
13474
13475//-----------------------------------------------------------------------------
13476// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
13477//-----------------------------------------------------------------------------
13478
13479// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
13480// In our terminology those should be interchangeable, yet right now this is super confusing.
13481// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
13482
13483void ImGui::SetNavCursorVisible(bool visible)
13484{
13485 ImGuiContext& g = *GImGui;
13486 if (g.IO.ConfigNavCursorVisibleAlways)
13487 visible = true;
13488 g.NavCursorVisible = visible;
13489}
13490
13491// (was called NavRestoreHighlightAfterMove() before 1.91.4)
13492void ImGui::SetNavCursorVisibleAfterMove()
13493{
13494 ImGuiContext& g = *GImGui;
13495 if (g.IO.ConfigNavCursorVisibleAuto)
13496 g.NavCursorVisible = true;
13497 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
13498}
13499
13500void ImGui::SetNavWindow(ImGuiWindow* window)
13501{
13502 ImGuiContext& g = *GImGui;
13503 if (g.NavWindow != window)
13504 {
13505 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
13506 g.NavWindow = window;
13507 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13508 }
13509 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13510 NavUpdateAnyRequestFlag();
13511}
13512
13513void ImGui::NavHighlightActivated(ImGuiID id)
13514{
13515 ImGuiContext& g = *GImGui;
13516 g.NavHighlightActivatedId = id;
13517 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
13518}
13519
13520void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
13521{
13522 ImGuiContext& g = *GImGui;
13523 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
13524}
13525
13526void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
13527{
13528 ImGuiContext& g = *GImGui;
13529 IM_ASSERT(g.NavWindow != NULL);
13530 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
13531 g.NavId = id;
13532 g.NavLayer = nav_layer;
13533 SetNavFocusScope(focus_scope_id);
13534 g.NavWindow->NavLastIds[nav_layer] = id;
13535 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
13536
13537 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13538 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
13539 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13540}
13541
13542void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
13543{
13544 ImGuiContext& g = *GImGui;
13545 IM_ASSERT(id != 0);
13546
13547 if (g.NavWindow != window)
13548 SetNavWindow(window);
13549
13550 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
13551 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
13552 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
13553 g.NavId = id;
13554 g.NavLayer = nav_layer;
13555 SetNavFocusScope(g.CurrentFocusScopeId);
13556 window->NavLastIds[nav_layer] = id;
13557 if (g.LastItemData.ID == id)
13558 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
13559
13560 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
13561 g.NavHighlightItemUnderNav = true;
13562 else if (g.IO.ConfigNavCursorVisibleAuto)
13563 g.NavCursorVisible = false;
13564
13565 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13566 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
13567 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13568}
13569
13570static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
13571{
13572 if (ImFabs(dx) > ImFabs(dy))
13573 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
13574 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
13575}
13576
13577static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
13578{
13579 if (cand_max < curr_min)
13580 return cand_max - curr_min;
13581 if (curr_max < cand_min)
13582 return cand_min - curr_max;
13583 return 0.0f;
13584}
13585
13586// Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
13587static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb)
13588{
13589 ImGuiContext& g = *GImGui;
13590 ImGuiWindow* window = g.CurrentWindow;
13591 if (g.NavLayer != window->DC.NavLayerCurrent)
13592 return false;
13593
13594 // FIXME: Those are not good variables names
13595 ImRect cand = nav_bb; // Current item nav rectangle
13596 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)
13597 g.NavScoringDebugCount++;
13598
13599 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
13600 if (window->ParentWindow == g.NavWindow)
13601 {
13602 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
13603 if (!window->ClipRect.Overlaps(r: cand))
13604 return false;
13605 cand.ClipWithFull(r: window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
13606 }
13607
13608 // Compute distance between boxes
13609 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
13610 float dbx = NavScoreItemDistInterval(cand_min: cand.Min.x, cand_max: cand.Max.x, curr_min: curr.Min.x, curr_max: curr.Max.x);
13611 float dby = NavScoreItemDistInterval(cand_min: ImLerp(a: cand.Min.y, b: cand.Max.y, t: 0.2f), cand_max: ImLerp(a: cand.Min.y, b: cand.Max.y, t: 0.8f), curr_min: ImLerp(a: curr.Min.y, b: curr.Max.y, t: 0.2f), curr_max: ImLerp(a: curr.Min.y, b: curr.Max.y, t: 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
13612 if (dby != 0.0f && dbx != 0.0f)
13613 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
13614 float dist_box = ImFabs(dbx) + ImFabs(dby);
13615
13616 // 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)
13617 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
13618 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
13619 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
13620
13621 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
13622 ImGuiDir quadrant;
13623 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
13624 if (dbx != 0.0f || dby != 0.0f)
13625 {
13626 // For non-overlapping boxes, use distance between boxes
13627 // 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
13628 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
13629 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
13630 dax = dbx;
13631 day = dby;
13632 dist_axial = dist_box;
13633 quadrant = ImGetDirQuadrantFromDelta(dx: dbx, dy: dby);
13634 }
13635 else if (dcx != 0.0f || dcy != 0.0f)
13636 {
13637 // For overlapping boxes with different centers, use distance between centers
13638 dax = dcx;
13639 day = dcy;
13640 dist_axial = dist_center;
13641 quadrant = ImGetDirQuadrantFromDelta(dx: dcx, dy: dcy);
13642 }
13643 else
13644 {
13645 // 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)
13646 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
13647 }
13648
13649 const ImGuiDir move_dir = g.NavMoveDir;
13650#if IMGUI_DEBUG_NAV_SCORING
13651 char buf[200];
13652 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
13653 {
13654 if (quadrant == move_dir)
13655 {
13656 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
13657 ImDrawList* draw_list = GetForegroundDrawList(window);
13658 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
13659 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
13660 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
13661 }
13662 }
13663 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
13664 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
13665 if (debug_hovering || debug_tty)
13666 {
13667 ImFormatString(buf, IM_ARRAYSIZE(buf),
13668 "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",
13669 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
13670 if (debug_hovering)
13671 {
13672 ImDrawList* draw_list = GetForegroundDrawList(window);
13673 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
13674 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
13675 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
13676 draw_list->AddText(cand.Max, ~0U, buf);
13677 }
13678 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
13679 }
13680#endif
13681
13682 // Is it in the quadrant we're interested in moving to?
13683 bool new_best = false;
13684 if (quadrant == move_dir)
13685 {
13686 // Does it beat the current best candidate?
13687 if (dist_box < result->DistBox)
13688 {
13689 result->DistBox = dist_box;
13690 result->DistCenter = dist_center;
13691 return true;
13692 }
13693 if (dist_box == result->DistBox)
13694 {
13695 // Try using distance between center points to break ties
13696 if (dist_center < result->DistCenter)
13697 {
13698 result->DistCenter = dist_center;
13699 new_best = true;
13700 }
13701 else if (dist_center == result->DistCenter)
13702 {
13703 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
13704 // (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),
13705 // 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.
13706 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
13707 new_best = true;
13708 }
13709 }
13710 }
13711
13712 // 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
13713 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
13714 // 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.
13715 // 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.
13716 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
13717 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
13718 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
13719 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))
13720 {
13721 result->DistAxial = dist_axial;
13722 new_best = true;
13723 }
13724
13725 return new_best;
13726}
13727
13728static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
13729{
13730 ImGuiContext& g = *GImGui;
13731 ImGuiWindow* window = g.CurrentWindow;
13732 result->Window = window;
13733 result->ID = g.LastItemData.ID;
13734 result->FocusScopeId = g.CurrentFocusScopeId;
13735 result->ItemFlags = g.LastItemData.ItemFlags;
13736 result->RectRel = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
13737 if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13738 {
13739 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13740 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13741 }
13742}
13743
13744// True when current work location may be scrolled horizontally when moving left / right.
13745// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
13746void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
13747{
13748 ImGuiContext& g = *GImGui;
13749 ImGuiWindow* window = g.CurrentWindow;
13750 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
13751}
13752
13753// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
13754// This is called after LastItemData is set, but NextItemData is also still valid.
13755static void ImGui::NavProcessItem()
13756{
13757 ImGuiContext& g = *GImGui;
13758 ImGuiWindow* window = g.CurrentWindow;
13759 const ImGuiID id = g.LastItemData.ID;
13760 const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
13761
13762 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816)
13763 ImRect nav_bb = g.LastItemData.NavRect;
13764 if (window->DC.NavIsScrollPushableX == false)
13765 {
13766 nav_bb.Min.x = ImClamp(v: nav_bb.Min.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
13767 nav_bb.Max.x = ImClamp(v: nav_bb.Max.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
13768 }
13769
13770 // Process Init Request
13771 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
13772 {
13773 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
13774 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
13775 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
13776 {
13777 NavApplyItemToResult(result: &g.NavInitResult);
13778 }
13779 if (candidate_for_nav_default_focus)
13780 {
13781 g.NavInitRequest = false; // Found a match, clear request
13782 NavUpdateAnyRequestFlag();
13783 }
13784 }
13785
13786 // Process Move Request (scoring for navigation)
13787 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
13788 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
13789 {
13790 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
13791 {
13792 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13793 if (is_tabbing)
13794 {
13795 NavProcessItemForTabbingRequest(id, item_flags, move_flags: g.NavMoveFlags);
13796 }
13797 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
13798 {
13799 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
13800 if (NavScoreItem(result, nav_bb))
13801 NavApplyItemToResult(result);
13802
13803 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
13804 const float VISIBLE_RATIO = 0.70f;
13805 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(r: nav_bb))
13806 if (ImClamp(v: nav_bb.Max.y, mn: window->ClipRect.Min.y, mx: window->ClipRect.Max.y) - ImClamp(v: nav_bb.Min.y, mn: window->ClipRect.Min.y, mx: window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
13807 if (NavScoreItem(result: &g.NavMoveResultLocalVisible, nav_bb))
13808 NavApplyItemToResult(result: &g.NavMoveResultLocalVisible);
13809 }
13810 }
13811 }
13812
13813 // Update information for currently focused/navigated item
13814 if (g.NavId == id)
13815 {
13816 if (g.NavWindow != window)
13817 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
13818 g.NavLayer = window->DC.NavLayerCurrent;
13819 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
13820 g.NavFocusScopeId = g.CurrentFocusScopeId;
13821 g.NavIdIsAlive = true;
13822 if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13823 {
13824 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13825 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13826 }
13827 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, r: nav_bb); // Store item bounding box (relative to window position)
13828 }
13829}
13830
13831// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
13832// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
13833// - Case 1: no nav/active id: set result to first eligible item, stop storing.
13834// - Case 2: tab forward: on ref id set counter, on counter elapse store result
13835// - 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
13836// - Case 4: tab backward: store all results, on ref id pick prev, stop storing
13837// - 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
13838void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
13839{
13840 ImGuiContext& g = *GImGui;
13841
13842 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
13843 {
13844 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
13845 return;
13846 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
13847 return;
13848 }
13849
13850 // - Can always land on an item when using API call.
13851 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
13852 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
13853 bool can_stop;
13854 if (move_flags & ImGuiNavMoveFlags_FocusApi)
13855 can_stop = true;
13856 else
13857 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
13858
13859 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
13860 ImGuiNavItemData* result = &g.NavMoveResultLocal;
13861 if (g.NavTabbingDir == +1)
13862 {
13863 // Tab Forward or SetKeyboardFocusHere() with >= 0
13864 if (can_stop && g.NavTabbingResultFirst.ID == 0)
13865 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
13866 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
13867 NavMoveRequestResolveWithLastItem(result);
13868 else if (g.NavId == id)
13869 g.NavTabbingCounter = 1;
13870 }
13871 else if (g.NavTabbingDir == -1)
13872 {
13873 // Tab Backward
13874 if (g.NavId == id)
13875 {
13876 if (result->ID)
13877 {
13878 g.NavMoveScoringItems = false;
13879 NavUpdateAnyRequestFlag();
13880 }
13881 }
13882 else if (can_stop)
13883 {
13884 // Keep applying until reaching NavId
13885 NavApplyItemToResult(result);
13886 }
13887 }
13888 else if (g.NavTabbingDir == 0)
13889 {
13890 if (can_stop && g.NavId == id)
13891 NavMoveRequestResolveWithLastItem(result);
13892 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
13893 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
13894 }
13895}
13896
13897bool ImGui::NavMoveRequestButNoResultYet()
13898{
13899 ImGuiContext& g = *GImGui;
13900 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
13901}
13902
13903// FIXME: ScoringRect is not set
13904void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13905{
13906 ImGuiContext& g = *GImGui;
13907 IM_ASSERT(g.NavWindow != NULL);
13908 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
13909
13910 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
13911 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
13912
13913 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
13914 g.NavMoveDir = move_dir;
13915 g.NavMoveDirForDebug = move_dir;
13916 g.NavMoveClipDir = clip_dir;
13917 g.NavMoveFlags = move_flags;
13918 g.NavMoveScrollFlags = scroll_flags;
13919 g.NavMoveForwardToNextFrame = false;
13920 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
13921 g.NavMoveResultLocal.Clear();
13922 g.NavMoveResultLocalVisible.Clear();
13923 g.NavMoveResultOther.Clear();
13924 g.NavTabbingCounter = 0;
13925 g.NavTabbingResultFirst.Clear();
13926 NavUpdateAnyRequestFlag();
13927}
13928
13929void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
13930{
13931 ImGuiContext& g = *GImGui;
13932 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
13933 NavApplyItemToResult(result);
13934 NavUpdateAnyRequestFlag();
13935}
13936
13937// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent
13938void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data)
13939{
13940 ImGuiContext& g = *GImGui;
13941 g.NavMoveScoringItems = false;
13942 g.LastItemData.ID = tree_node_data->ID;
13943 g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
13944 g.LastItemData.NavRect = tree_node_data->NavRect;
13945 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
13946 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13947 NavUpdateAnyRequestFlag();
13948}
13949
13950void ImGui::NavMoveRequestCancel()
13951{
13952 ImGuiContext& g = *GImGui;
13953 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13954 NavUpdateAnyRequestFlag();
13955}
13956
13957// Forward will reuse the move request again on the next frame (generally with modifications done to it)
13958void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13959{
13960 ImGuiContext& g = *GImGui;
13961 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
13962 NavMoveRequestCancel();
13963 g.NavMoveForwardToNextFrame = true;
13964 g.NavMoveDir = move_dir;
13965 g.NavMoveClipDir = clip_dir;
13966 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
13967 g.NavMoveScrollFlags = scroll_flags;
13968}
13969
13970// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
13971// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
13972void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
13973{
13974 ImGuiContext& g = *GImGui;
13975 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
13976
13977 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
13978 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
13979 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
13980 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
13981}
13982
13983// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
13984// This way we could find the last focused window among our children. It would be much less confusing this way?
13985static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
13986{
13987 ImGuiWindow* parent = nav_window;
13988 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13989 parent = parent->ParentWindow;
13990 if (parent && parent != nav_window)
13991 parent->NavLastChildNavWindow = nav_window;
13992}
13993
13994// Restore the last focused child.
13995// Call when we are expected to land on the Main Layer (0) after FocusWindow()
13996static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
13997{
13998 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
13999 return window->NavLastChildNavWindow;
14000 if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
14001 if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar: window->DockNodeAsHost->TabBar))
14002 return tab->Window;
14003 return window;
14004}
14005
14006void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
14007{
14008 ImGuiContext& g = *GImGui;
14009 if (layer == ImGuiNavLayer_Main)
14010 {
14011 ImGuiWindow* prev_nav_window = g.NavWindow;
14012 g.NavWindow = NavRestoreLastChildNavWindow(window: g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
14013 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14014 if (prev_nav_window)
14015 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
14016 }
14017 ImGuiWindow* window = g.NavWindow;
14018 if (window->NavLastIds[layer] != 0)
14019 {
14020 SetNavID(id: window->NavLastIds[layer], nav_layer: layer, focus_scope_id: 0, rect_rel: window->NavRectRel[layer]);
14021 }
14022 else
14023 {
14024 g.NavLayer = layer;
14025 NavInitWindow(window, force_reinit: true);
14026 }
14027}
14028
14029static inline void ImGui::NavUpdateAnyRequestFlag()
14030{
14031 ImGuiContext& g = *GImGui;
14032 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
14033 if (g.NavAnyRequest)
14034 IM_ASSERT(g.NavWindow != NULL);
14035}
14036
14037// This needs to be called before we submit any widget (aka in or before Begin)
14038void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
14039{
14040 // FIXME: ChildWindow test here is wrong for docking
14041 ImGuiContext& g = *GImGui;
14042 IM_ASSERT(window == g.NavWindow);
14043
14044 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
14045 {
14046 g.NavId = 0;
14047 SetNavFocusScope(window->NavRootFocusScopeId);
14048 return;
14049 }
14050
14051 bool init_for_nav = false;
14052 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
14053 init_for_nav = true;
14054 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
14055 if (init_for_nav)
14056 {
14057 SetNavID(id: 0, nav_layer: g.NavLayer, focus_scope_id: window->NavRootFocusScopeId, rect_rel: ImRect());
14058 g.NavInitRequest = true;
14059 g.NavInitRequestFromMove = false;
14060 g.NavInitResult.ID = 0;
14061 NavUpdateAnyRequestFlag();
14062 }
14063 else
14064 {
14065 g.NavId = window->NavLastIds[0];
14066 SetNavFocusScope(window->NavRootFocusScopeId);
14067 }
14068}
14069
14070static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
14071{
14072 ImGuiContext& g = *GImGui;
14073 ImGuiWindow* window = g.NavWindow;
14074 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14075
14076 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
14077 if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut)
14078 return ImGuiInputSource_Mouse;
14079 else
14080 return ImGuiInputSource_Keyboard; // or Nav in general
14081}
14082
14083static ImVec2 ImGui::NavCalcPreferredRefPos()
14084{
14085 ImGuiContext& g = *GImGui;
14086 ImGuiWindow* window = g.NavWindow;
14087 ImGuiInputSource source = NavCalcPreferredRefPosSource();
14088
14089 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14090
14091 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
14092 if (source == ImGuiInputSource_Mouse)
14093 {
14094 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
14095 // 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.
14096 // In theory we could move that +1.0f offset in OpenPopupEx()
14097 ImVec2 p = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
14098 return ImVec2(p.x + 1.0f, p.y);
14099 }
14100 else
14101 {
14102 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
14103 ImRect ref_rect;
14104 if (activated_shortcut)
14105 ref_rect = g.LastItemData.NavRect;
14106 else
14107 ref_rect = WindowRectRelToAbs(window, r: window->NavRectRel[g.NavLayer]);
14108
14109 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
14110 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
14111 {
14112 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
14113 ref_rect.Translate(d: window->Scroll - next_scroll);
14114 }
14115 ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(lhs: g.Style.FramePadding.x * 4, rhs: ref_rect.GetWidth()), ref_rect.Max.y - ImMin(lhs: g.Style.FramePadding.y, rhs: ref_rect.GetHeight()));
14116 ImGuiViewport* viewport = window->Viewport;
14117 return ImTrunc(v: ImClamp(v: pos, mn: viewport->Pos, mx: 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.
14118 }
14119}
14120
14121float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
14122{
14123 ImGuiContext& g = *GImGui;
14124 float repeat_delay, repeat_rate;
14125 GetTypematicRepeatRate(flags: ImGuiInputFlags_RepeatRateNavTweak, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
14126
14127 ImGuiKey key_less, key_more;
14128 if (g.NavInputSource == ImGuiInputSource_Gamepad)
14129 {
14130 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
14131 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
14132 }
14133 else
14134 {
14135 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
14136 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
14137 }
14138 float amount = (float)GetKeyPressedAmount(key: key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key: key_less, repeat_delay, repeat_rate);
14139 if (amount != 0.0f && IsKeyDown(key: key_less) && IsKeyDown(key: key_more)) // Cancel when opposite directions are held, regardless of repeat phase
14140 amount = 0.0f;
14141 return amount;
14142}
14143
14144static void ImGui::NavUpdate()
14145{
14146 ImGuiContext& g = *GImGui;
14147 ImGuiIO& io = g.IO;
14148
14149 io.WantSetMousePos = false;
14150 //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);
14151
14152 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
14153 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
14154 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14155 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
14156 if (nav_gamepad_active)
14157 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
14158 if (IsKeyDown(key))
14159 g.NavInputSource = ImGuiInputSource_Gamepad;
14160 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14161 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
14162 if (nav_keyboard_active)
14163 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
14164 if (IsKeyDown(key))
14165 g.NavInputSource = ImGuiInputSource_Keyboard;
14166
14167 // Process navigation init request (select first/default focus)
14168 g.NavJustMovedToId = 0;
14169 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
14170 if (g.NavInitResult.ID != 0)
14171 NavInitRequestApplyResult();
14172 g.NavInitRequest = false;
14173 g.NavInitRequestFromMove = false;
14174 g.NavInitResult.ID = 0;
14175
14176 // Process navigation move request
14177 if (g.NavMoveSubmitted)
14178 NavMoveRequestApplyResult();
14179 g.NavTabbingCounter = 0;
14180 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
14181 if (g.NavCursorHideFrames > 0)
14182 if (--g.NavCursorHideFrames == 0)
14183 g.NavCursorVisible = true;
14184
14185 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
14186 bool set_mouse_pos = false;
14187 if (g.NavMousePosDirty && g.NavIdIsAlive)
14188 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
14189 set_mouse_pos = true;
14190 g.NavMousePosDirty = false;
14191 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
14192
14193 // 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
14194 if (g.NavWindow)
14195 NavSaveLastChildNavWindowIntoParent(nav_window: g.NavWindow);
14196 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
14197 g.NavWindow->NavLastChildNavWindow = NULL;
14198
14199 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
14200 NavUpdateWindowing();
14201
14202 // Set output flags for user application
14203 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
14204 io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
14205
14206 // Process NavCancel input (to close a popup, get back to parent, clear focus)
14207 NavUpdateCancelRequest();
14208
14209 // Process manual activation request
14210 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
14211 g.NavActivateFlags = ImGuiActivateFlags_None;
14212 if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14213 {
14214 const bool activate_down = (nav_keyboard_active && IsKeyDown(key: ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
14215 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Space, flags: 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, flags: 0, ImGuiKeyOwner_NoOwner)));
14216 const bool input_down = (nav_keyboard_active && (IsKeyDown(key: ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(key: ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
14217 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(key: ImGuiKey_Enter, flags: 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(key: ImGuiKey_KeypadEnter, flags: 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, flags: 0, ImGuiKeyOwner_NoOwner)));
14218 if (g.ActiveId == 0 && activate_pressed)
14219 {
14220 g.NavActivateId = g.NavId;
14221 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
14222 }
14223 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
14224 {
14225 g.NavActivateId = g.NavId;
14226 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
14227 }
14228 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
14229 g.NavActivateDownId = g.NavId;
14230 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
14231 {
14232 g.NavActivatePressedId = g.NavId;
14233 NavHighlightActivated(id: g.NavId);
14234 }
14235 }
14236 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14237 g.NavCursorVisible = false;
14238 else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
14239 g.NavCursorVisible = true;
14240 if (g.NavActivateId != 0)
14241 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
14242
14243 // Highlight
14244 if (g.NavHighlightActivatedTimer > 0.0f)
14245 g.NavHighlightActivatedTimer = ImMax(lhs: 0.0f, rhs: g.NavHighlightActivatedTimer - io.DeltaTime);
14246 if (g.NavHighlightActivatedTimer == 0.0f)
14247 g.NavHighlightActivatedId = 0;
14248
14249 // Process programmatic activation request
14250 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
14251 if (g.NavNextActivateId != 0)
14252 {
14253 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
14254 g.NavActivateFlags = g.NavNextActivateFlags;
14255 }
14256 g.NavNextActivateId = 0;
14257
14258 // Process move requests
14259 NavUpdateCreateMoveRequest();
14260 if (g.NavMoveDir == ImGuiDir_None)
14261 NavUpdateCreateTabbingRequest();
14262 NavUpdateAnyRequestFlag();
14263 g.NavIdIsAlive = false;
14264
14265 // Scrolling
14266 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
14267 {
14268 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
14269 ImGuiWindow* window = g.NavWindow;
14270 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.
14271 const ImGuiDir move_dir = g.NavMoveDir;
14272 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
14273 {
14274 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
14275 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
14276 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
14277 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
14278 }
14279
14280 // *Normal* Manual scroll with LStick
14281 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
14282 if (nav_gamepad_active)
14283 {
14284 const ImVec2 scroll_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
14285 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
14286 if (scroll_dir.x != 0.0f && window->ScrollbarX)
14287 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
14288 if (scroll_dir.y != 0.0f)
14289 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
14290 }
14291 }
14292
14293 // Always prioritize mouse highlight if navigation is disabled
14294 if (!nav_keyboard_active && !nav_gamepad_active)
14295 {
14296 g.NavCursorVisible = false;
14297 g.NavHighlightItemUnderNav = set_mouse_pos = false;
14298 }
14299
14300 // Update mouse position if requested
14301 // (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)
14302 if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
14303 TeleportMousePos(pos: NavCalcPreferredRefPos());
14304
14305 // [DEBUG]
14306 g.NavScoringDebugCount = 0;
14307#if IMGUI_DEBUG_NAV_RECTS
14308 if (ImGuiWindow* debug_window = g.NavWindow)
14309 {
14310 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
14311 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)); }
14312 //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); }
14313 }
14314#endif
14315}
14316
14317void ImGui::NavInitRequestApplyResult()
14318{
14319 // 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)
14320 ImGuiContext& g = *GImGui;
14321 if (!g.NavWindow)
14322 return;
14323
14324 ImGuiNavItemData* result = &g.NavInitResult;
14325 if (g.NavId != result->ID)
14326 {
14327 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14328 g.NavJustMovedToId = result->ID;
14329 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14330 g.NavJustMovedToKeyMods = 0;
14331 g.NavJustMovedToIsTabbing = false;
14332 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14333 }
14334
14335 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
14336 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
14337 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14338 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
14339 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
14340 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14341 g.NavLastValidSelectionUserData = result->SelectionUserData;
14342 if (g.NavInitRequestFromMove)
14343 SetNavCursorVisibleAfterMove();
14344}
14345
14346// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
14347static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
14348{
14349 // Bias initial rect
14350 ImGuiContext& g = *GImGui;
14351 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
14352
14353 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
14354 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
14355 // - But each successful move sets new bias on one axis, only cleared when using mouse.
14356 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
14357 {
14358 if (preferred_pos_rel.x == FLT_MAX)
14359 preferred_pos_rel.x = ImMin(lhs: r.Min.x + 1.0f, rhs: r.Max.x) - rel_to_abs_offset.x;
14360 if (preferred_pos_rel.y == FLT_MAX)
14361 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
14362 }
14363
14364 // Apply general bias on the other axis
14365 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
14366 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
14367 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
14368 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
14369}
14370
14371void ImGui::NavUpdateCreateMoveRequest()
14372{
14373 ImGuiContext& g = *GImGui;
14374 ImGuiIO& io = g.IO;
14375 ImGuiWindow* window = g.NavWindow;
14376 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14377 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14378
14379 if (g.NavMoveForwardToNextFrame && window != NULL)
14380 {
14381 // 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)
14382 // (preserve most state, which were already set by the NavMoveRequestForward() function)
14383 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
14384 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
14385 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
14386 }
14387 else
14388 {
14389 // Initiate directional inputs request
14390 g.NavMoveDir = ImGuiDir_None;
14391 g.NavMoveFlags = ImGuiNavMoveFlags_None;
14392 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
14393 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
14394 {
14395 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
14396 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadLeft, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_LeftArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
14397 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadRight, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_RightArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
14398 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadUp, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_UpArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
14399 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadDown, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_DownArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
14400 }
14401 g.NavMoveClipDir = g.NavMoveDir;
14402 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14403 }
14404
14405 // Update PageUp/PageDown/Home/End scroll
14406 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
14407 float scoring_rect_offset_y = 0.0f;
14408 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
14409 scoring_rect_offset_y = NavUpdatePageUpPageDown();
14410 if (scoring_rect_offset_y != 0.0f)
14411 {
14412 g.NavScoringNoClipRect = window->InnerRect;
14413 g.NavScoringNoClipRect.TranslateY(dy: scoring_rect_offset_y);
14414 }
14415
14416 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
14417#if IMGUI_DEBUG_NAV_SCORING
14418 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
14419 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
14420 if (io.KeyCtrl)
14421 {
14422 if (g.NavMoveDir == ImGuiDir_None)
14423 g.NavMoveDir = g.NavMoveDirForDebug;
14424 g.NavMoveClipDir = g.NavMoveDir;
14425 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
14426 }
14427#endif
14428
14429 // Submit
14430 g.NavMoveForwardToNextFrame = false;
14431 if (g.NavMoveDir != ImGuiDir_None)
14432 NavMoveRequestSubmit(move_dir: g.NavMoveDir, clip_dir: g.NavMoveClipDir, move_flags: g.NavMoveFlags, scroll_flags: g.NavMoveScrollFlags);
14433
14434 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
14435 if (g.NavMoveSubmitted && g.NavId == 0)
14436 {
14437 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
14438 g.NavInitRequest = g.NavInitRequestFromMove = true;
14439 g.NavInitResult.ID = 0;
14440 if (g.IO.ConfigNavCursorVisibleAuto)
14441 g.NavCursorVisible = true;
14442 }
14443
14444 // When using gamepad, we project the reference nav bounding box into window visible area.
14445 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
14446 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
14447 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
14448 {
14449 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
14450 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
14451 ImRect inner_rect_rel = WindowRectAbsToRel(window, r: ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
14452
14453 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
14454 // Otherwise 'inner_rect_rel' would be off on the move result frame.
14455 inner_rect_rel.Translate(d: CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
14456
14457 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(r: window->NavRectRel[g.NavLayer]))
14458 {
14459 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
14460 float pad_x = ImMin(lhs: inner_rect_rel.GetWidth(), rhs: window->FontRefSize * 0.5f);
14461 float pad_y = ImMin(lhs: inner_rect_rel.GetHeight(), rhs: window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
14462 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
14463 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
14464 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
14465 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
14466 window->NavRectRel[g.NavLayer].ClipWithFull(r: inner_rect_rel);
14467 g.NavId = 0;
14468 }
14469 }
14470
14471 // Prepare scoring rectangle.
14472 // 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)
14473 ImRect scoring_rect;
14474 if (window != NULL)
14475 {
14476 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
14477 scoring_rect = WindowRectRelToAbs(window, r: nav_rect_rel);
14478 scoring_rect.TranslateY(dy: scoring_rect_offset_y);
14479 if (g.NavMoveSubmitted)
14480 NavBiasScoringRect(r&: scoring_rect, preferred_pos_rel&: window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], move_dir: g.NavMoveDir, move_flags: g.NavMoveFlags);
14481 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
14482 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
14483 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
14484 }
14485 g.NavScoringRect = scoring_rect;
14486 //g.NavScoringNoClipRect.Add(scoring_rect);
14487}
14488
14489void ImGui::NavUpdateCreateTabbingRequest()
14490{
14491 ImGuiContext& g = *GImGui;
14492 ImGuiWindow* window = g.NavWindow;
14493 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
14494 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
14495 return;
14496
14497 const bool tab_pressed = IsKeyPressed(key: ImGuiKey_Tab, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
14498 if (!tab_pressed)
14499 return;
14500
14501 // Initiate tabbing request
14502 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
14503 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
14504 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14505 if (nav_keyboard_active)
14506 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
14507 else
14508 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
14509 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
14510 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
14511 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
14512 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
14513 g.NavTabbingCounter = -1;
14514}
14515
14516// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
14517void ImGui::NavMoveRequestApplyResult()
14518{
14519 ImGuiContext& g = *GImGui;
14520#if IMGUI_DEBUG_NAV_SCORING
14521 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
14522 return;
14523#endif
14524
14525 // Select which result to use
14526 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
14527
14528 // Tabbing forward wrap
14529 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
14530 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
14531 result = &g.NavTabbingResultFirst;
14532
14533 // 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)
14534 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14535 if (result == NULL)
14536 {
14537 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14538 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
14539 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14540 SetNavCursorVisibleAfterMove();
14541 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
14542 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
14543 return;
14544 }
14545
14546 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
14547 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
14548 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
14549 result = &g.NavMoveResultLocalVisible;
14550
14551 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
14552 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
14553 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
14554 result = &g.NavMoveResultOther;
14555 IM_ASSERT(g.NavWindow && result->Window);
14556
14557 // Scroll to keep newly navigated item fully into view.
14558 if (g.NavLayer == ImGuiNavLayer_Main)
14559 {
14560 ImRect rect_abs = WindowRectRelToAbs(window: result->Window, r: result->RectRel);
14561 ScrollToRectEx(window: result->Window, item_rect: rect_abs, flags: g.NavMoveScrollFlags);
14562
14563 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
14564 {
14565 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
14566 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
14567 SetScrollY(window: result->Window, scroll_y: scroll_target);
14568 }
14569 }
14570
14571 if (g.NavWindow != result->Window)
14572 {
14573 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
14574 g.NavWindow = result->Window;
14575 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14576 }
14577
14578 // Clear active id unless requested not to
14579 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
14580 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
14581 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
14582 ClearActiveID();
14583
14584 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
14585 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
14586 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
14587 {
14588 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14589 g.NavJustMovedToId = result->ID;
14590 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14591 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
14592 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
14593 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14594 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
14595 }
14596
14597 // Apply new NavID/Focus
14598 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14599 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
14600 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
14601 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14602 g.NavLastValidSelectionUserData = result->SelectionUserData;
14603
14604 // Restore last preferred position for current axis
14605 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
14606 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
14607 {
14608 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
14609 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
14610 }
14611
14612 // Tabbing: Activates Inputable, otherwise only Focus
14613 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
14614 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
14615
14616 // Activate
14617 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
14618 {
14619 g.NavNextActivateId = result->ID;
14620 g.NavNextActivateFlags = ImGuiActivateFlags_None;
14621 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14622 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
14623 }
14624
14625 // Make nav cursor visible
14626 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14627 SetNavCursorVisibleAfterMove();
14628}
14629
14630// Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
14631// FIXME: In order to support e.g. Escape to clear a selection we'll need:
14632// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
14633// - 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
14634static void ImGui::NavUpdateCancelRequest()
14635{
14636 ImGuiContext& g = *GImGui;
14637 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14638 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14639 if (!(nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Escape, flags: 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, flags: 0, ImGuiKeyOwner_NoOwner)))
14640 return;
14641
14642 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
14643 if (g.ActiveId != 0)
14644 {
14645 ClearActiveID();
14646 }
14647 else if (g.NavLayer != ImGuiNavLayer_Main)
14648 {
14649 // Leave the "menu" layer
14650 NavRestoreLayer(layer: ImGuiNavLayer_Main);
14651 SetNavCursorVisibleAfterMove();
14652 }
14653 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
14654 {
14655 // Exit child window
14656 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
14657 ImGuiWindow* parent_window = child_window->ParentWindow;
14658 IM_ASSERT(child_window->ChildId != 0);
14659 FocusWindow(window: parent_window);
14660 SetNavID(id: child_window->ChildId, nav_layer: ImGuiNavLayer_Main, focus_scope_id: 0, rect_rel: WindowRectAbsToRel(window: parent_window, r: child_window->Rect()));
14661 SetNavCursorVisibleAfterMove();
14662 }
14663 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
14664 {
14665 // Close open popup/menu
14666 ClosePopupToLevel(remaining: g.OpenPopupStack.Size - 1, restore_focus_to_window_under_popup: true);
14667 }
14668 else
14669 {
14670 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
14671 // FIXME-NAV: This should happen on window appearing.
14672 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14673 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
14674 g.NavWindow->NavLastIds[0] = 0;
14675
14676 // Clear nav focus
14677 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14678 g.NavId = 0;
14679 if (g.IO.ConfigNavEscapeClearFocusWindow)
14680 FocusWindow(NULL);
14681 }
14682}
14683
14684// Handle PageUp/PageDown/Home/End keys
14685// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
14686// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
14687// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
14688static float ImGui::NavUpdatePageUpPageDown()
14689{
14690 ImGuiContext& g = *GImGui;
14691 ImGuiWindow* window = g.NavWindow;
14692 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
14693 return 0.0f;
14694
14695 const bool page_up_held = IsKeyDown(key: ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
14696 const bool page_down_held = IsKeyDown(key: ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
14697 const bool home_pressed = IsKeyPressed(key: ImGuiKey_Home, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14698 const bool end_pressed = IsKeyPressed(key: ImGuiKey_End, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14699 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
14700 return 0.0f;
14701
14702 if (g.NavLayer != ImGuiNavLayer_Main)
14703 NavRestoreLayer(layer: ImGuiNavLayer_Main);
14704
14705 if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY)
14706 {
14707 // Fallback manual-scroll when window has no navigable item
14708 if (IsKeyPressed(key: ImGuiKey_PageUp, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14709 SetScrollY(window, scroll_y: window->Scroll.y - window->InnerRect.GetHeight());
14710 else if (IsKeyPressed(key: ImGuiKey_PageDown, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14711 SetScrollY(window, scroll_y: window->Scroll.y + window->InnerRect.GetHeight());
14712 else if (home_pressed)
14713 SetScrollY(window, scroll_y: 0.0f);
14714 else if (end_pressed)
14715 SetScrollY(window, scroll_y: window->ScrollMax.y);
14716 }
14717 else
14718 {
14719 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
14720 const float page_offset_y = ImMax(lhs: 0.0f, rhs: window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight());
14721 float nav_scoring_rect_offset_y = 0.0f;
14722 if (IsKeyPressed(key: ImGuiKey_PageUp, repeat: true))
14723 {
14724 nav_scoring_rect_offset_y = -page_offset_y;
14725 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)
14726 g.NavMoveClipDir = ImGuiDir_Up;
14727 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
14728 }
14729 else if (IsKeyPressed(key: ImGuiKey_PageDown, repeat: true))
14730 {
14731 nav_scoring_rect_offset_y = +page_offset_y;
14732 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)
14733 g.NavMoveClipDir = ImGuiDir_Down;
14734 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
14735 }
14736 else if (home_pressed)
14737 {
14738 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
14739 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
14740 // Preserve current horizontal position if we have any.
14741 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
14742 if (nav_rect_rel.IsInverted())
14743 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14744 g.NavMoveDir = ImGuiDir_Down;
14745 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14746 // FIXME-NAV: MoveClipDir left to _None, intentional?
14747 }
14748 else if (end_pressed)
14749 {
14750 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
14751 if (nav_rect_rel.IsInverted())
14752 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14753 g.NavMoveDir = ImGuiDir_Up;
14754 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14755 // FIXME-NAV: MoveClipDir left to _None, intentional?
14756 }
14757 return nav_scoring_rect_offset_y;
14758 }
14759 return 0.0f;
14760}
14761
14762static void ImGui::NavEndFrame()
14763{
14764 ImGuiContext& g = *GImGui;
14765
14766 // Show CTRL+TAB list window
14767 if (g.NavWindowingTarget != NULL)
14768 NavUpdateWindowingOverlay();
14769
14770 // Perform wrap-around in menus
14771 // 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.
14772 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
14773 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
14774 NavUpdateCreateWrappingRequest();
14775}
14776
14777static void ImGui::NavUpdateCreateWrappingRequest()
14778{
14779 ImGuiContext& g = *GImGui;
14780 ImGuiWindow* window = g.NavWindow;
14781
14782 bool do_forward = false;
14783 ImRect bb_rel = window->NavRectRel[g.NavLayer];
14784 ImGuiDir clip_dir = g.NavMoveDir;
14785
14786 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
14787 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14788 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14789 {
14790 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
14791 if (move_flags & ImGuiNavMoveFlags_WrapX)
14792 {
14793 bb_rel.TranslateY(dy: -bb_rel.GetHeight()); // Previous row
14794 clip_dir = ImGuiDir_Up;
14795 }
14796 do_forward = true;
14797 }
14798 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14799 {
14800 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
14801 if (move_flags & ImGuiNavMoveFlags_WrapX)
14802 {
14803 bb_rel.TranslateY(dy: +bb_rel.GetHeight()); // Next row
14804 clip_dir = ImGuiDir_Down;
14805 }
14806 do_forward = true;
14807 }
14808 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14809 {
14810 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
14811 if (move_flags & ImGuiNavMoveFlags_WrapY)
14812 {
14813 bb_rel.TranslateX(dx: -bb_rel.GetWidth()); // Previous column
14814 clip_dir = ImGuiDir_Left;
14815 }
14816 do_forward = true;
14817 }
14818 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14819 {
14820 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
14821 if (move_flags & ImGuiNavMoveFlags_WrapY)
14822 {
14823 bb_rel.TranslateX(dx: +bb_rel.GetWidth()); // Next column
14824 clip_dir = ImGuiDir_Right;
14825 }
14826 do_forward = true;
14827 }
14828 if (!do_forward)
14829 return;
14830 window->NavRectRel[g.NavLayer] = bb_rel;
14831 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
14832 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
14833 NavMoveRequestForward(move_dir: g.NavMoveDir, clip_dir, move_flags, scroll_flags: g.NavMoveScrollFlags);
14834}
14835
14836// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
14837// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
14838// If you want a window to never be focused, you may use the e.g. NoInputs flag.
14839bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
14840{
14841 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
14842}
14843
14844static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
14845{
14846 ImGuiContext& g = *GImGui;
14847 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
14848 if (ImGui::IsWindowNavFocusable(window: g.WindowsFocusOrder[i]))
14849 return g.WindowsFocusOrder[i];
14850 return NULL;
14851}
14852
14853static void NavUpdateWindowingTarget(int focus_change_dir)
14854{
14855 ImGuiContext& g = *GImGui;
14856 IM_ASSERT(g.NavWindowingTarget);
14857 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
14858 return;
14859
14860 const int i_current = ImGui::FindWindowFocusIndex(window: g.NavWindowingTarget);
14861 ImGuiWindow* window_target = FindWindowNavFocusable(i_start: i_current + focus_change_dir, i_stop: -INT_MAX, dir: focus_change_dir);
14862 if (!window_target)
14863 window_target = FindWindowNavFocusable(i_start: (focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_stop: i_current, dir: focus_change_dir);
14864 if (window_target) // Don't reset windowing target if there's a single window in the list
14865 {
14866 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
14867 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14868 }
14869 g.NavWindowingToggleLayer = false;
14870}
14871
14872// Apply focus and close overlay
14873static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window)
14874{
14875 // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ?
14876 // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
14877 ImGuiContext& g = *GImGui;
14878 if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)
14879 {
14880 ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
14881 ClearActiveID();
14882 SetNavCursorVisibleAfterMove();
14883 ClosePopupsOverWindow(ref_window: apply_focus_window, restore_focus_to_window_under_popup: false);
14884 FocusWindow(window: apply_focus_window, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
14885 IM_ASSERT(g.NavWindow != NULL);
14886 apply_focus_window = g.NavWindow;
14887 if (apply_focus_window->NavLastIds[0] == 0)
14888 NavInitWindow(window: apply_focus_window, force_reinit: false);
14889
14890 // If the window has ONLY a menu layer (no main layer), select it directly
14891 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
14892 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
14893 // the target window as already been previewed once.
14894 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
14895 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
14896 // won't be valid.
14897 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
14898 g.NavLayer = ImGuiNavLayer_Menu;
14899
14900 // Request OS level focus
14901 if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
14902 g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
14903 }
14904 g.NavWindowingTarget = NULL;
14905}
14906
14907// Windowing management mode
14908// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
14909// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
14910static void ImGui::NavUpdateWindowing()
14911{
14912 ImGuiContext& g = *GImGui;
14913 ImGuiIO& io = g.IO;
14914
14915 ImGuiWindow* apply_focus_window = NULL;
14916 bool apply_toggle_layer = false;
14917
14918 ImGuiWindow* modal_window = GetTopMostPopupModal();
14919 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.
14920 if (!allow_windowing)
14921 g.NavWindowingTarget = NULL;
14922
14923 // Fade out
14924 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
14925 {
14926 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, rhs: 0.0f);
14927 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
14928 g.NavWindowingTargetAnim = NULL;
14929 }
14930
14931 // Start CTRL+Tab or Square+L/R window selection
14932 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
14933 const ImGuiID owner_id = ImHashStr(data_p: "##NavUpdateWindowing");
14934 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14935 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14936 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(key_chord: g.ConfigNavWindowingKeyNext, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14937 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(key_chord: g.ConfigNavWindowingKeyPrev, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14938 const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, flags: ImGuiInputFlags_RouteAlways, owner_id);
14939 const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad;
14940 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
14941 bool just_started_windowing_from_null_focus = false;
14942 if (start_toggling_with_gamepad)
14943 {
14944 g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer
14945 g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu;
14946 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad;
14947 }
14948 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
14949 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(i_start: g.WindowsFocusOrder.Size - 1, i_stop: -INT_MAX, dir: -1))
14950 {
14951 if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad)
14952 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
14953 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
14954 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14955 g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
14956 if (g.NavWindow == NULL)
14957 just_started_windowing_from_null_focus = true;
14958
14959 // 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.
14960 if (keyboard_next_window || keyboard_prev_window)
14961 SetKeyOwnersForKeyChord(key_chord: (g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
14962 }
14963
14964 // Gamepad update
14965 if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad)
14966 {
14967 if (g.NavWindowingTarget != NULL)
14968 {
14969 // 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
14970 // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast.
14971 g.NavWindowingTimer += io.DeltaTime;
14972 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha, rhs: ImSaturate(f: (g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
14973
14974 // Select window to focus
14975 const int focus_change_dir = (int)IsKeyPressed(key: ImGuiKey_GamepadL1) - (int)IsKeyPressed(key: ImGuiKey_GamepadR1);
14976 if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
14977 {
14978 NavUpdateWindowingTarget(focus_change_dir);
14979 g.NavWindowingHighlightAlpha = 1.0f;
14980 }
14981 }
14982
14983 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
14984 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
14985 {
14986 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
14987 if (g.NavWindowingToggleLayer && g.NavWindow)
14988 apply_toggle_layer = true;
14989 else if (!g.NavWindowingToggleLayer)
14990 apply_focus_window = g.NavWindowingTarget;
14991 g.NavWindowingTarget = NULL;
14992 g.NavWindowingToggleLayer = false;
14993 }
14994 }
14995
14996 // Keyboard: Focus
14997 if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
14998 {
14999 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
15000 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
15001 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
15002 g.NavWindowingTimer += io.DeltaTime;
15003 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha, rhs: ImSaturate(f: (g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
15004 if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
15005 NavUpdateWindowingTarget(focus_change_dir: keyboard_next_window ? -1 : +1);
15006 else if ((io.KeyMods & shared_mods) != shared_mods)
15007 apply_focus_window = g.NavWindowingTarget;
15008 }
15009
15010 // Keyboard: Press and Release ALT to toggle menu layer
15011 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
15012 bool windowing_toggle_layer_start = false;
15013 if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
15014 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
15015 if (nav_keyboard_active && IsKeyPressed(key: windowing_toggle_key, flags: 0, ImGuiKeyOwner_NoOwner))
15016 {
15017 windowing_toggle_layer_start = true;
15018 g.NavWindowingToggleLayer = true;
15019 g.NavWindowingToggleKey = windowing_toggle_key;
15020 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard;
15021 break;
15022 }
15023 if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
15024 {
15025 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
15026 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
15027 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
15028 // We cancel toggling nav layer if an owner has claimed the key.
15029 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
15030 g.NavWindowingToggleLayer = false;
15031 else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time)
15032 g.NavWindowingToggleLayer = false;
15033 else if (TestKeyOwner(key: g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(key: ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
15034 g.NavWindowingToggleLayer = false;
15035
15036 // Apply layer toggle on Alt release
15037 // 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.
15038 if (IsKeyReleased(key: g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
15039 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
15040 if (IsMousePosValid(mouse_pos: &io.MousePos) == IsMousePosValid(mouse_pos: &io.MousePosPrev))
15041 apply_toggle_layer = true;
15042 if (!IsKeyDown(key: g.NavWindowingToggleKey))
15043 g.NavWindowingToggleLayer = false;
15044 }
15045
15046 // Move window
15047 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
15048 {
15049 ImVec2 nav_move_dir;
15050 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
15051 nav_move_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
15052 if (g.NavInputSource == ImGuiInputSource_Gamepad)
15053 nav_move_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
15054 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
15055 {
15056 const float NAV_MOVE_SPEED = 800.0f;
15057 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(lhs: io.DisplayFramebufferScale.x, rhs: io.DisplayFramebufferScale.y);
15058 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
15059 g.NavHighlightItemUnderNav = true;
15060 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaPos);
15061 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
15062 {
15063 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
15064 SetWindowPos(window: moving_window, pos: moving_window->Pos + accum_floored, cond: ImGuiCond_Always);
15065 g.NavWindowingAccumDeltaPos -= accum_floored;
15066 }
15067 }
15068 }
15069
15070 // Apply final focus
15071 if (apply_focus_window)
15072 NavUpdateWindowingApplyFocus(apply_focus_window);
15073
15074 // Apply menu/layer toggle
15075 if (apply_toggle_layer && g.NavWindow)
15076 {
15077 ClearActiveID();
15078
15079 // Move to parent menu if necessary
15080 ImGuiWindow* new_nav_window = g.NavWindow;
15081 while (new_nav_window->ParentWindow
15082 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
15083 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
15084 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
15085 new_nav_window = new_nav_window->ParentWindow;
15086 if (new_nav_window != g.NavWindow)
15087 {
15088 ImGuiWindow* old_nav_window = g.NavWindow;
15089 FocusWindow(window: new_nav_window);
15090 new_nav_window->NavLastChildNavWindow = old_nav_window;
15091 }
15092
15093 // Toggle layer
15094 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
15095 if (new_nav_layer != g.NavLayer)
15096 {
15097 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
15098 const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
15099 if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
15100 g.NavWindow->NavLastIds[new_nav_layer] = 0;
15101 NavRestoreLayer(layer: new_nav_layer);
15102 SetNavCursorVisibleAfterMove();
15103 }
15104 }
15105}
15106
15107// Window has already passed the IsWindowNavFocusable()
15108static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
15109{
15110 if (window->Flags & ImGuiWindowFlags_Popup)
15111 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingPopup);
15112 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(s1: window->Name, s2: "##MainMenuBar") == 0)
15113 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingMainMenuBar);
15114 if (window->DockNodeAsHost)
15115 return "(Dock node)"; // Not normally shown to user.
15116 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingUntitled);
15117}
15118
15119// Overlay displayed when using CTRL+TAB. Called by EndFrame().
15120void ImGui::NavUpdateWindowingOverlay()
15121{
15122 ImGuiContext& g = *GImGui;
15123 IM_ASSERT(g.NavWindowingTarget != NULL);
15124
15125 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
15126 return;
15127
15128 if (g.NavWindowingListWindow == NULL)
15129 g.NavWindowingListWindow = FindWindowByName(name: "##NavWindowingOverlay");
15130 const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
15131 SetNextWindowSizeConstraints(size_min: ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), size_max: ImVec2(FLT_MAX, FLT_MAX));
15132 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_Always, pivot: ImVec2(0.5f, 0.5f));
15133 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.WindowPadding * 2.0f);
15134 Begin(name: "##NavWindowingOverlay", NULL, flags: ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
15135 if (g.ContextName[0] != 0)
15136 SeparatorText(label: g.ContextName);
15137 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
15138 {
15139 ImGuiWindow* window = g.WindowsFocusOrder[n];
15140 IM_ASSERT(window != NULL); // Fix static analyzers
15141 if (!IsWindowNavFocusable(window))
15142 continue;
15143 const char* label = window->Name;
15144 if (label == FindRenderedTextEnd(text: label))
15145 label = GetFallbackWindowNameForWindowingList(window);
15146 Selectable(label, selected: g.NavWindowingTarget == window);
15147 }
15148 End();
15149 PopStyleVar();
15150}
15151
15152//-----------------------------------------------------------------------------
15153// [SECTION] DRAG AND DROP
15154//-----------------------------------------------------------------------------
15155
15156bool ImGui::IsDragDropActive()
15157{
15158 ImGuiContext& g = *GImGui;
15159 return g.DragDropActive;
15160}
15161
15162void ImGui::ClearDragDrop()
15163{
15164 ImGuiContext& g = *GImGui;
15165 if (g.DragDropActive)
15166 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
15167 g.DragDropActive = false;
15168 g.DragDropPayload.Clear();
15169 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
15170 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
15171 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
15172 g.DragDropAcceptFrameCount = -1;
15173
15174 g.DragDropPayloadBufHeap.clear();
15175 memset(s: &g.DragDropPayloadBufLocal, c: 0, n: sizeof(g.DragDropPayloadBufLocal));
15176}
15177
15178bool ImGui::BeginTooltipHidden()
15179{
15180 ImGuiContext& g = *GImGui;
15181 bool ret = Begin(name: "##Tooltip_Hidden", NULL, flags: ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
15182 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
15183 return ret;
15184}
15185
15186// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
15187// If the item has an identifier:
15188// - This assume/require the item to be activated (typically via ButtonBehavior).
15189// - 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.
15190// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
15191// If the item has no identifier:
15192// - Currently always assume left mouse button.
15193bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
15194{
15195 ImGuiContext& g = *GImGui;
15196 ImGuiWindow* window = g.CurrentWindow;
15197
15198 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
15199 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
15200 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
15201
15202 bool source_drag_active = false;
15203 ImGuiID source_id = 0;
15204 ImGuiID source_parent_id = 0;
15205 if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
15206 {
15207 source_id = g.LastItemData.ID;
15208 if (source_id != 0)
15209 {
15210 // Common path: items with ID
15211 if (g.ActiveId != source_id)
15212 return false;
15213 if (g.ActiveIdMouseButton != -1)
15214 mouse_button = g.ActiveIdMouseButton;
15215 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15216 return false;
15217 g.ActiveIdAllowOverlap = false;
15218 }
15219 else
15220 {
15221 // Uncommon path: items without ID
15222 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15223 return false;
15224 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
15225 return false;
15226
15227 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
15228 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
15229 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
15230 {
15231 IM_ASSERT(0);
15232 return false;
15233 }
15234
15235 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
15236 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
15237 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
15238 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
15239 // Rely on keeping other window->LastItemXXX fields intact.
15240 source_id = g.LastItemData.ID = window->GetIDFromRectangle(r_abs: g.LastItemData.Rect);
15241 KeepAliveID(id: source_id);
15242 bool is_hovered = ItemHoverable(bb: g.LastItemData.Rect, id: source_id, item_flags: g.LastItemData.ItemFlags);
15243 if (is_hovered && g.IO.MouseClicked[mouse_button])
15244 {
15245 SetActiveID(id: source_id, window);
15246 FocusWindow(window);
15247 }
15248 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
15249 g.ActiveIdAllowOverlap = is_hovered;
15250 }
15251 if (g.ActiveId != source_id)
15252 return false;
15253 source_parent_id = window->IDStack.back();
15254 source_drag_active = IsMouseDragging(button: mouse_button);
15255
15256 // Disable navigation and key inputs while dragging + cancel existing request if any
15257 SetActiveIdUsingAllKeyboardKeys();
15258 }
15259 else
15260 {
15261 // When ImGuiDragDropFlags_SourceExtern is set:
15262 window = NULL;
15263 source_id = ImHashStr(data_p: "#SourceExtern");
15264 source_drag_active = true;
15265 mouse_button = g.IO.MouseDown[0] ? 0 : -1;
15266 KeepAliveID(id: source_id);
15267 SetActiveID(id: source_id, NULL);
15268 }
15269
15270 IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15271 if (!source_drag_active)
15272 return false;
15273
15274 // Activate drag and drop
15275 if (!g.DragDropActive)
15276 {
15277 IM_ASSERT(source_id != 0);
15278 ClearDragDrop();
15279 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
15280 source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
15281 ImGuiPayload& payload = g.DragDropPayload;
15282 payload.SourceId = source_id;
15283 payload.SourceParentId = source_parent_id;
15284 g.DragDropActive = true;
15285 g.DragDropSourceFlags = flags;
15286 g.DragDropMouseButton = mouse_button;
15287 if (payload.SourceId == g.ActiveId)
15288 g.ActiveIdNoClearOnFocusLoss = true;
15289 }
15290 g.DragDropSourceFrameCount = g.FrameCount;
15291 g.DragDropWithinSource = true;
15292
15293 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15294 {
15295 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
15296 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
15297 bool ret;
15298 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
15299 ret = BeginTooltipHidden();
15300 else
15301 ret = BeginTooltip();
15302 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
15303 IM_UNUSED(ret);
15304 }
15305
15306 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
15307 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
15308
15309 return true;
15310}
15311
15312void ImGui::EndDragDropSource()
15313{
15314 ImGuiContext& g = *GImGui;
15315 IM_ASSERT(g.DragDropActive);
15316 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
15317
15318 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15319 EndTooltip();
15320
15321 // Discard the drag if have not called SetDragDropPayload()
15322 if (g.DragDropPayload.DataFrameCount == -1)
15323 ClearDragDrop();
15324 g.DragDropWithinSource = false;
15325}
15326
15327// Use 'cond' to choose to submit payload on drag start or every frame
15328bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
15329{
15330 ImGuiContext& g = *GImGui;
15331 ImGuiPayload& payload = g.DragDropPayload;
15332 if (cond == 0)
15333 cond = ImGuiCond_Always;
15334
15335 IM_ASSERT(type != NULL);
15336 IM_ASSERT(ImStrlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
15337 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
15338 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
15339 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
15340
15341 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
15342 {
15343 // Copy payload
15344 ImStrncpy(dst: payload.DataType, src: type, IM_ARRAYSIZE(payload.DataType));
15345 g.DragDropPayloadBufHeap.resize(new_size: 0);
15346 if (data_size > sizeof(g.DragDropPayloadBufLocal))
15347 {
15348 // Store in heap
15349 g.DragDropPayloadBufHeap.resize(new_size: (int)data_size);
15350 payload.Data = g.DragDropPayloadBufHeap.Data;
15351 memcpy(dest: payload.Data, src: data, n: data_size);
15352 }
15353 else if (data_size > 0)
15354 {
15355 // Store locally
15356 memset(s: &g.DragDropPayloadBufLocal, c: 0, n: sizeof(g.DragDropPayloadBufLocal));
15357 payload.Data = g.DragDropPayloadBufLocal;
15358 memcpy(dest: payload.Data, src: data, n: data_size);
15359 }
15360 else
15361 {
15362 payload.Data = NULL;
15363 }
15364 payload.DataSize = (int)data_size;
15365 }
15366 payload.DataFrameCount = g.FrameCount;
15367
15368 // Return whether the payload has been accepted
15369 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
15370}
15371
15372bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
15373{
15374 ImGuiContext& g = *GImGui;
15375 if (!g.DragDropActive)
15376 return false;
15377
15378 ImGuiWindow* window = g.CurrentWindow;
15379 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15380 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
15381 return false;
15382 IM_ASSERT(id != 0);
15383 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max) || (id == g.DragDropPayload.SourceId))
15384 return false;
15385 if (window->SkipItems)
15386 return false;
15387
15388 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15389 g.DragDropTargetRect = bb;
15390 g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
15391 g.DragDropTargetId = id;
15392 g.DragDropWithinTarget = true;
15393 return true;
15394}
15395
15396// We don't use BeginDragDropTargetCustom() and duplicate its code because:
15397// 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.
15398// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
15399// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
15400bool ImGui::BeginDragDropTarget()
15401{
15402 ImGuiContext& g = *GImGui;
15403 if (!g.DragDropActive)
15404 return false;
15405
15406 ImGuiWindow* window = g.CurrentWindow;
15407 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
15408 return false;
15409 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15410 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
15411 return false;
15412
15413 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
15414 ImGuiID id = g.LastItemData.ID;
15415 if (id == 0)
15416 {
15417 id = window->GetIDFromRectangle(r_abs: display_rect);
15418 KeepAliveID(id);
15419 }
15420 if (g.DragDropPayload.SourceId == id)
15421 return false;
15422
15423 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15424 g.DragDropTargetRect = display_rect;
15425 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
15426 g.DragDropTargetId = id;
15427 g.DragDropWithinTarget = true;
15428 return true;
15429}
15430
15431bool ImGui::IsDragDropPayloadBeingAccepted()
15432{
15433 ImGuiContext& g = *GImGui;
15434 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
15435}
15436
15437const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
15438{
15439 ImGuiContext& g = *GImGui;
15440 ImGuiPayload& payload = g.DragDropPayload;
15441 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
15442 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
15443 if (type != NULL && !payload.IsDataType(type))
15444 return NULL;
15445
15446 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
15447 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
15448 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
15449 ImRect r = g.DragDropTargetRect;
15450 float r_surface = r.GetWidth() * r.GetHeight();
15451 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
15452 return NULL;
15453
15454 g.DragDropAcceptFlags = flags;
15455 g.DragDropAcceptIdCurr = g.DragDropTargetId;
15456 g.DragDropAcceptIdCurrRectSurface = r_surface;
15457 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
15458
15459 // Render default drop visuals
15460 payload.Preview = was_accepted_previously;
15461 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
15462 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
15463 RenderDragDropTargetRect(bb: r, item_clip_rect: g.DragDropTargetClipRect);
15464
15465 g.DragDropAcceptFrameCount = g.FrameCount;
15466 if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
15467 payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
15468 else
15469 payload.Delivery = was_accepted_previously && !IsMouseDown(button: g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
15470 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
15471 return NULL;
15472
15473 if (payload.Delivery)
15474 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
15475 return &payload;
15476}
15477
15478// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
15479void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
15480{
15481 ImGuiContext& g = *GImGui;
15482 ImGuiWindow* window = g.CurrentWindow;
15483 ImRect bb_display = bb;
15484 bb_display.ClipWith(r: item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
15485 bb_display.Expand(amount: 3.5f);
15486 bool push_clip_rect = !window->ClipRect.Contains(r: bb_display);
15487 if (push_clip_rect)
15488 window->DrawList->PushClipRectFullScreen();
15489 window->DrawList->AddRect(p_min: bb_display.Min, p_max: bb_display.Max, col: GetColorU32(idx: ImGuiCol_DragDropTarget), rounding: 0.0f, flags: 0, thickness: 2.0f); // FIXME-DPI
15490 if (push_clip_rect)
15491 window->DrawList->PopClipRect();
15492}
15493
15494const ImGuiPayload* ImGui::GetDragDropPayload()
15495{
15496 ImGuiContext& g = *GImGui;
15497 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
15498}
15499
15500void ImGui::EndDragDropTarget()
15501{
15502 ImGuiContext& g = *GImGui;
15503 IM_ASSERT(g.DragDropActive);
15504 IM_ASSERT(g.DragDropWithinTarget);
15505 g.DragDropWithinTarget = false;
15506
15507 // Clear drag and drop state payload right after delivery
15508 if (g.DragDropPayload.Delivery)
15509 ClearDragDrop();
15510}
15511
15512//-----------------------------------------------------------------------------
15513// [SECTION] LOGGING/CAPTURING
15514//-----------------------------------------------------------------------------
15515// All text output from the interface can be captured into tty/file/clipboard.
15516// By default, tree nodes are automatically opened during logging.
15517//-----------------------------------------------------------------------------
15518
15519// Pass text data straight to log (without being displayed)
15520static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
15521{
15522 if (g.LogFile)
15523 {
15524 g.LogBuffer.Buf.resize(new_size: 0);
15525 g.LogBuffer.appendfv(fmt, args);
15526 ImFileWrite(data: g.LogBuffer.c_str(), sz: sizeof(char), count: (ImU64)g.LogBuffer.size(), f: g.LogFile);
15527 }
15528 else
15529 {
15530 g.LogBuffer.appendfv(fmt, args);
15531 }
15532}
15533
15534void ImGui::LogText(const char* fmt, ...)
15535{
15536 ImGuiContext& g = *GImGui;
15537 if (!g.LogEnabled)
15538 return;
15539
15540 va_list args;
15541 va_start(args, fmt);
15542 LogTextV(g, fmt, args);
15543 va_end(args);
15544}
15545
15546void ImGui::LogTextV(const char* fmt, va_list args)
15547{
15548 ImGuiContext& g = *GImGui;
15549 if (!g.LogEnabled)
15550 return;
15551
15552 LogTextV(g, fmt, args);
15553}
15554
15555// Internal version that takes a position to decide on newline placement and pad items according to their depth.
15556// We split text into individual lines to add current tree level padding
15557// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
15558void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
15559{
15560 ImGuiContext& g = *GImGui;
15561 ImGuiWindow* window = g.CurrentWindow;
15562
15563 const char* prefix = g.LogNextPrefix;
15564 const char* suffix = g.LogNextSuffix;
15565 g.LogNextPrefix = g.LogNextSuffix = NULL;
15566
15567 if (!text_end)
15568 text_end = FindRenderedTextEnd(text, text_end);
15569
15570 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
15571 if (ref_pos)
15572 g.LogLinePosY = ref_pos->y;
15573 if (log_new_line)
15574 {
15575 LogText(IM_NEWLINE);
15576 g.LogLineFirstItem = true;
15577 }
15578
15579 if (prefix)
15580 LogRenderedText(ref_pos, text: prefix, text_end: prefix + ImStrlen(s: prefix)); // Calculate end ourself to ensure "##" are included here.
15581
15582 // Re-adjust padding if we have popped out of our starting depth
15583 if (g.LogDepthRef > window->DC.TreeDepth)
15584 g.LogDepthRef = window->DC.TreeDepth;
15585 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
15586
15587 const char* text_remaining = text;
15588 for (;;)
15589 {
15590 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
15591 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
15592 const char* line_start = text_remaining;
15593 const char* line_end = ImStreolRange(str: line_start, str_end: text_end);
15594 const bool is_last_line = (line_end == text_end);
15595 if (line_start != line_end || !is_last_line)
15596 {
15597 const int line_length = (int)(line_end - line_start);
15598 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
15599 LogText(fmt: "%*s%.*s", indentation, "", line_length, line_start);
15600 g.LogLineFirstItem = false;
15601 if (*line_end == '\n')
15602 {
15603 LogText(IM_NEWLINE);
15604 g.LogLineFirstItem = true;
15605 }
15606 }
15607 if (is_last_line)
15608 break;
15609 text_remaining = line_end + 1;
15610 }
15611
15612 if (suffix)
15613 LogRenderedText(ref_pos, text: suffix, text_end: suffix + ImStrlen(s: suffix));
15614}
15615
15616// Start logging/capturing text output
15617void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
15618{
15619 ImGuiContext& g = *GImGui;
15620 ImGuiWindow* window = g.CurrentWindow;
15621 IM_ASSERT(g.LogEnabled == false);
15622 IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
15623 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
15624
15625 g.LogEnabled = g.ItemUnclipByLog = true;
15626 g.LogFlags = flags;
15627 g.LogWindow = window;
15628 g.LogNextPrefix = g.LogNextSuffix = NULL;
15629 g.LogDepthRef = window->DC.TreeDepth;
15630 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
15631 g.LogLinePosY = FLT_MAX;
15632 g.LogLineFirstItem = true;
15633}
15634
15635// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
15636void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
15637{
15638 ImGuiContext& g = *GImGui;
15639 g.LogNextPrefix = prefix;
15640 g.LogNextSuffix = suffix;
15641}
15642
15643void ImGui::LogToTTY(int auto_open_depth)
15644{
15645 ImGuiContext& g = *GImGui;
15646 if (g.LogEnabled)
15647 return;
15648 IM_UNUSED(auto_open_depth);
15649#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15650 LogBegin(flags: ImGuiLogFlags_OutputTTY, auto_open_depth);
15651 g.LogFile = stdout;
15652#endif
15653}
15654
15655// Start logging/capturing text output to given file
15656void ImGui::LogToFile(int auto_open_depth, const char* filename)
15657{
15658 ImGuiContext& g = *GImGui;
15659 if (g.LogEnabled)
15660 return;
15661
15662 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
15663 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
15664 // By opening the file in binary mode "ab" we have consistent output everywhere.
15665 if (!filename)
15666 filename = g.IO.LogFilename;
15667 if (!filename || !filename[0])
15668 return;
15669 ImFileHandle f = ImFileOpen(filename, mode: "ab");
15670 if (!f)
15671 {
15672 IM_ASSERT(0);
15673 return;
15674 }
15675
15676 LogBegin(flags: ImGuiLogFlags_OutputFile, auto_open_depth);
15677 g.LogFile = f;
15678}
15679
15680// Start logging/capturing text output to clipboard
15681void ImGui::LogToClipboard(int auto_open_depth)
15682{
15683 ImGuiContext& g = *GImGui;
15684 if (g.LogEnabled)
15685 return;
15686 LogBegin(flags: ImGuiLogFlags_OutputClipboard, auto_open_depth);
15687}
15688
15689void ImGui::LogToBuffer(int auto_open_depth)
15690{
15691 ImGuiContext& g = *GImGui;
15692 if (g.LogEnabled)
15693 return;
15694 LogBegin(flags: ImGuiLogFlags_OutputBuffer, auto_open_depth);
15695}
15696
15697void ImGui::LogFinish()
15698{
15699 ImGuiContext& g = *GImGui;
15700 if (!g.LogEnabled)
15701 return;
15702
15703 LogText(IM_NEWLINE);
15704 switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
15705 {
15706 case ImGuiLogFlags_OutputTTY:
15707#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15708 fflush(stream: g.LogFile);
15709#endif
15710 break;
15711 case ImGuiLogFlags_OutputFile:
15712 ImFileClose(f: g.LogFile);
15713 break;
15714 case ImGuiLogFlags_OutputBuffer:
15715 break;
15716 case ImGuiLogFlags_OutputClipboard:
15717 if (!g.LogBuffer.empty())
15718 SetClipboardText(g.LogBuffer.begin());
15719 break;
15720 default:
15721 IM_ASSERT(0);
15722 break;
15723 }
15724
15725 g.LogEnabled = g.ItemUnclipByLog = false;
15726 g.LogFlags = ImGuiLogFlags_None;
15727 g.LogFile = NULL;
15728 g.LogBuffer.clear();
15729}
15730
15731// Helper to display logging buttons
15732// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
15733void ImGui::LogButtons()
15734{
15735 ImGuiContext& g = *GImGui;
15736
15737 PushID(str_id: "LogButtons");
15738#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15739 const bool log_to_tty = Button(label: "Log To TTY"); SameLine();
15740#else
15741 const bool log_to_tty = false;
15742#endif
15743 const bool log_to_file = Button(label: "Log To File"); SameLine();
15744 const bool log_to_clipboard = Button(label: "Log To Clipboard"); SameLine();
15745 PushItemFlag(option: ImGuiItemFlags_NoTabStop, enabled: true);
15746 SetNextItemWidth(80.0f);
15747 SliderInt(label: "Default Depth", v: &g.LogDepthToExpandDefault, v_min: 0, v_max: 9, NULL);
15748 PopItemFlag();
15749 PopID();
15750
15751 // Start logging at the end of the function so that the buttons don't appear in the log
15752 if (log_to_tty)
15753 LogToTTY();
15754 if (log_to_file)
15755 LogToFile();
15756 if (log_to_clipboard)
15757 LogToClipboard();
15758}
15759
15760//-----------------------------------------------------------------------------
15761// [SECTION] SETTINGS
15762//-----------------------------------------------------------------------------
15763// - UpdateSettings() [Internal]
15764// - MarkIniSettingsDirty() [Internal]
15765// - FindSettingsHandler() [Internal]
15766// - ClearIniSettings() [Internal]
15767// - LoadIniSettingsFromDisk()
15768// - LoadIniSettingsFromMemory()
15769// - SaveIniSettingsToDisk()
15770// - SaveIniSettingsToMemory()
15771//-----------------------------------------------------------------------------
15772// - CreateNewWindowSettings() [Internal]
15773// - FindWindowSettingsByID() [Internal]
15774// - FindWindowSettingsByWindow() [Internal]
15775// - ClearWindowSettings() [Internal]
15776// - WindowSettingsHandler_***() [Internal]
15777//-----------------------------------------------------------------------------
15778
15779// Called by NewFrame()
15780void ImGui::UpdateSettings()
15781{
15782 // Load settings on first frame (if not explicitly loaded manually before)
15783 ImGuiContext& g = *GImGui;
15784 if (!g.SettingsLoaded)
15785 {
15786 IM_ASSERT(g.SettingsWindows.empty());
15787 if (g.IO.IniFilename)
15788 LoadIniSettingsFromDisk(ini_filename: g.IO.IniFilename);
15789 g.SettingsLoaded = true;
15790 }
15791
15792 // Save settings (with a delay after the last modification, so we don't spam disk too much)
15793 if (g.SettingsDirtyTimer > 0.0f)
15794 {
15795 g.SettingsDirtyTimer -= g.IO.DeltaTime;
15796 if (g.SettingsDirtyTimer <= 0.0f)
15797 {
15798 if (g.IO.IniFilename != NULL)
15799 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
15800 else
15801 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
15802 g.SettingsDirtyTimer = 0.0f;
15803 }
15804 }
15805}
15806
15807void ImGui::MarkIniSettingsDirty()
15808{
15809 ImGuiContext& g = *GImGui;
15810 if (g.SettingsDirtyTimer <= 0.0f)
15811 g.SettingsDirtyTimer = g.IO.IniSavingRate;
15812}
15813
15814void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
15815{
15816 ImGuiContext& g = *GImGui;
15817 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
15818 if (g.SettingsDirtyTimer <= 0.0f)
15819 g.SettingsDirtyTimer = g.IO.IniSavingRate;
15820}
15821
15822void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
15823{
15824 ImGuiContext& g = *GImGui;
15825 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
15826 g.SettingsHandlers.push_back(v: *handler);
15827}
15828
15829void ImGui::RemoveSettingsHandler(const char* type_name)
15830{
15831 ImGuiContext& g = *GImGui;
15832 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
15833 g.SettingsHandlers.erase(it: handler);
15834}
15835
15836ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
15837{
15838 ImGuiContext& g = *GImGui;
15839 const ImGuiID type_hash = ImHashStr(data_p: type_name);
15840 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15841 if (handler.TypeHash == type_hash)
15842 return &handler;
15843 return NULL;
15844}
15845
15846// Clear all settings (windows, tables, docking etc.)
15847void ImGui::ClearIniSettings()
15848{
15849 ImGuiContext& g = *GImGui;
15850 g.SettingsIniData.clear();
15851 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15852 if (handler.ClearAllFn != NULL)
15853 handler.ClearAllFn(&g, &handler);
15854}
15855
15856void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
15857{
15858 size_t file_data_size = 0;
15859 char* file_data = (char*)ImFileLoadToMemory(filename: ini_filename, mode: "rb", out_file_size: &file_data_size);
15860 if (!file_data)
15861 return;
15862 if (file_data_size > 0)
15863 LoadIniSettingsFromMemory(ini_data: file_data, ini_size: (size_t)file_data_size);
15864 IM_FREE(file_data);
15865}
15866
15867// Zero-tolerance, no error reporting, cheap .ini parsing
15868// 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!
15869void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
15870{
15871 ImGuiContext& g = *GImGui;
15872 IM_ASSERT(g.Initialized);
15873 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
15874 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
15875
15876 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
15877 // 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..
15878 if (ini_size == 0)
15879 ini_size = ImStrlen(s: ini_data);
15880 g.SettingsIniData.Buf.resize(new_size: (int)ini_size + 1);
15881 char* const buf = g.SettingsIniData.Buf.Data;
15882 char* const buf_end = buf + ini_size;
15883 memcpy(dest: buf, src: ini_data, n: ini_size);
15884 buf_end[0] = 0;
15885
15886 // Call pre-read handlers
15887 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
15888 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15889 if (handler.ReadInitFn != NULL)
15890 handler.ReadInitFn(&g, &handler);
15891
15892 void* entry_data = NULL;
15893 ImGuiSettingsHandler* entry_handler = NULL;
15894
15895 char* line_end = NULL;
15896 for (char* line = buf; line < buf_end; line = line_end + 1)
15897 {
15898 // Skip new lines markers, then find end of the line
15899 while (*line == '\n' || *line == '\r')
15900 line++;
15901 line_end = line;
15902 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
15903 line_end++;
15904 line_end[0] = 0;
15905 if (line[0] == ';')
15906 continue;
15907 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
15908 {
15909 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
15910 line_end[-1] = 0;
15911 const char* name_end = line_end - 1;
15912 const char* type_start = line + 1;
15913 char* type_end = (char*)(void*)ImStrchrRange(str: type_start, str_end: name_end, c: ']');
15914 const char* name_start = type_end ? ImStrchrRange(str: type_end + 1, str_end: name_end, c: '[') : NULL;
15915 if (!type_end || !name_start)
15916 continue;
15917 *type_end = 0; // Overwrite first ']'
15918 name_start++; // Skip second '['
15919 entry_handler = FindSettingsHandler(type_name: type_start);
15920 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
15921 }
15922 else if (entry_handler != NULL && entry_data != NULL)
15923 {
15924 // Let type handler parse the line
15925 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
15926 }
15927 }
15928 g.SettingsLoaded = true;
15929
15930 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
15931 memcpy(dest: buf, src: ini_data, n: ini_size);
15932
15933 // Call post-read handlers
15934 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15935 if (handler.ApplyAllFn != NULL)
15936 handler.ApplyAllFn(&g, &handler);
15937}
15938
15939void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
15940{
15941 ImGuiContext& g = *GImGui;
15942 g.SettingsDirtyTimer = 0.0f;
15943 if (!ini_filename)
15944 return;
15945
15946 size_t ini_data_size = 0;
15947 const char* ini_data = SaveIniSettingsToMemory(out_ini_size: &ini_data_size);
15948 ImFileHandle f = ImFileOpen(filename: ini_filename, mode: "wt");
15949 if (!f)
15950 return;
15951 ImFileWrite(data: ini_data, sz: sizeof(char), count: ini_data_size, f);
15952 ImFileClose(f);
15953}
15954
15955// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
15956const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
15957{
15958 ImGuiContext& g = *GImGui;
15959 g.SettingsDirtyTimer = 0.0f;
15960 g.SettingsIniData.Buf.resize(new_size: 0);
15961 g.SettingsIniData.Buf.push_back(v: 0);
15962 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15963 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
15964 if (out_size)
15965 *out_size = (size_t)g.SettingsIniData.size();
15966 return g.SettingsIniData.c_str();
15967}
15968
15969ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
15970{
15971 ImGuiContext& g = *GImGui;
15972
15973 if (g.IO.ConfigDebugIniSettings == false)
15974 {
15975 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
15976 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
15977 if (const char* p = strstr(haystack: name, needle: "###"))
15978 name = p;
15979 }
15980 const size_t name_len = ImStrlen(s: name);
15981
15982 // Allocate chunk
15983 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
15984 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(sz: chunk_size);
15985 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
15986 settings->ID = ImHashStr(data_p: name, data_size: name_len);
15987 memcpy(dest: settings->GetName(), src: name, n: name_len + 1); // Store with zero terminator
15988
15989 return settings;
15990}
15991
15992// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
15993// This is called once per window .ini entry + once per newly instantiated window.
15994ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
15995{
15996 ImGuiContext& g = *GImGui;
15997 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
15998 if (settings->ID == id && !settings->WantDelete)
15999 return settings;
16000 return NULL;
16001}
16002
16003// This is faster if you are holding on a Window already as we don't need to perform a search.
16004ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
16005{
16006 ImGuiContext& g = *GImGui;
16007 if (window->SettingsOffset != -1)
16008 return g.SettingsWindows.ptr_from_offset(off: window->SettingsOffset);
16009 return FindWindowSettingsByID(id: window->ID);
16010}
16011
16012// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
16013void ImGui::ClearWindowSettings(const char* name)
16014{
16015 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
16016 ImGuiContext& g = *GImGui;
16017 ImGuiWindow* window = FindWindowByName(name);
16018 if (window != NULL)
16019 {
16020 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
16021 InitOrLoadWindowSettings(window, NULL);
16022 if (window->DockId != 0)
16023 DockContextProcessUndockWindow(ctx: &g, window, clear_persistent_docking_ref: true);
16024 }
16025 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(id: ImHashStr(data_p: name)))
16026 settings->WantDelete = true;
16027}
16028
16029static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
16030{
16031 ImGuiContext& g = *ctx;
16032 for (ImGuiWindow* window : g.Windows)
16033 window->SettingsOffset = -1;
16034 g.SettingsWindows.clear();
16035}
16036
16037static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
16038{
16039 ImGuiID id = ImHashStr(data_p: name);
16040 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
16041 if (settings)
16042 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
16043 else
16044 settings = ImGui::CreateNewWindowSettings(name);
16045 settings->ID = id;
16046 settings->WantApply = true;
16047 return (void*)settings;
16048}
16049
16050static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
16051{
16052 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
16053 int x, y;
16054 int i;
16055 ImU32 u1;
16056 if (sscanf(s: line, format: "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
16057 else if (sscanf(s: line, format: "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
16058 else if (sscanf(s: line, format: "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
16059 else if (sscanf(s: line, format: "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
16060 else if (sscanf(s: line, format: "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
16061 else if (sscanf(s: line, format: "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
16062 else if (sscanf(s: line, format: "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
16063 else if (sscanf(s: line, format: "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
16064 else if (sscanf(s: line, format: "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
16065}
16066
16067// Apply to existing windows (if any)
16068static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
16069{
16070 ImGuiContext& g = *ctx;
16071 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
16072 if (settings->WantApply)
16073 {
16074 if (ImGuiWindow* window = ImGui::FindWindowByID(id: settings->ID))
16075 ApplyWindowSettings(window, settings);
16076 settings->WantApply = false;
16077 }
16078}
16079
16080static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
16081{
16082 // Gather data from windows that were active during this session
16083 // (if a window wasn't opened in this session we preserve its settings)
16084 ImGuiContext& g = *ctx;
16085 for (ImGuiWindow* window : g.Windows)
16086 {
16087 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
16088 continue;
16089
16090 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
16091 if (!settings)
16092 {
16093 settings = ImGui::CreateNewWindowSettings(name: window->Name);
16094 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
16095 }
16096 IM_ASSERT(settings->ID == window->ID);
16097 settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
16098 settings->Size = ImVec2ih(window->SizeFull);
16099 settings->ViewportId = window->ViewportId;
16100 settings->ViewportPos = ImVec2ih(window->ViewportPos);
16101 IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
16102 settings->DockId = window->DockId;
16103 settings->ClassId = window->WindowClass.ClassId;
16104 settings->DockOrder = window->DockOrder;
16105 settings->Collapsed = window->Collapsed;
16106 settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
16107 settings->WantDelete = false;
16108 }
16109
16110 // Write to text buffer
16111 buf->reserve(capacity: buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
16112 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
16113 {
16114 if (settings->WantDelete)
16115 continue;
16116 const char* settings_name = settings->GetName();
16117 buf->appendf(fmt: "[%s][%s]\n", handler->TypeName, settings_name);
16118 if (settings->IsChild)
16119 {
16120 buf->appendf(fmt: "IsChild=1\n");
16121 buf->appendf(fmt: "Size=%d,%d\n", settings->Size.x, settings->Size.y);
16122 }
16123 else
16124 {
16125 if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
16126 {
16127 buf->appendf(fmt: "ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
16128 buf->appendf(fmt: "ViewportId=0x%08X\n", settings->ViewportId);
16129 }
16130 if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
16131 buf->appendf(fmt: "Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
16132 if (settings->Size.x != 0 || settings->Size.y != 0)
16133 buf->appendf(fmt: "Size=%d,%d\n", settings->Size.x, settings->Size.y);
16134 buf->appendf(fmt: "Collapsed=%d\n", settings->Collapsed);
16135 if (settings->DockId != 0)
16136 {
16137 //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
16138 if (settings->DockOrder == -1)
16139 buf->appendf(fmt: "DockId=0x%08X\n", settings->DockId);
16140 else
16141 buf->appendf(fmt: "DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
16142 if (settings->ClassId != 0)
16143 buf->appendf(fmt: "ClassId=0x%08X\n", settings->ClassId);
16144 }
16145 }
16146 buf->append(str: "\n");
16147 }
16148}
16149
16150//-----------------------------------------------------------------------------
16151// [SECTION] LOCALIZATION
16152//-----------------------------------------------------------------------------
16153
16154void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
16155{
16156 ImGuiContext& g = *GImGui;
16157 for (int n = 0; n < count; n++)
16158 g.LocalizationTable[entries[n].Key] = entries[n].Text;
16159}
16160
16161//-----------------------------------------------------------------------------
16162// [SECTION] VIEWPORTS, PLATFORM WINDOWS
16163//-----------------------------------------------------------------------------
16164// - GetMainViewport()
16165// - FindViewportByID()
16166// - FindViewportByPlatformHandle()
16167// - SetCurrentViewport() [Internal]
16168// - SetWindowViewport() [Internal]
16169// - GetWindowAlwaysWantOwnViewport() [Internal]
16170// - UpdateTryMergeWindowIntoHostViewport() [Internal]
16171// - UpdateTryMergeWindowIntoHostViewports() [Internal]
16172// - TranslateWindowsInViewport() [Internal]
16173// - ScaleWindowsInViewport() [Internal]
16174// - FindHoveredViewportFromPlatformWindowStack() [Internal]
16175// - UpdateViewportsNewFrame() [Internal]
16176// - UpdateViewportsEndFrame() [Internal]
16177// - AddUpdateViewport() [Internal]
16178// - WindowSelectViewport() [Internal]
16179// - WindowSyncOwnedViewport() [Internal]
16180// - UpdatePlatformWindows()
16181// - RenderPlatformWindowsDefault()
16182// - FindPlatformMonitorForPos() [Internal]
16183// - FindPlatformMonitorForRect() [Internal]
16184// - UpdateViewportPlatformMonitor() [Internal]
16185// - DestroyPlatformWindow() [Internal]
16186// - DestroyPlatformWindows()
16187//-----------------------------------------------------------------------------
16188
16189ImGuiViewport* ImGui::GetMainViewport()
16190{
16191 ImGuiContext& g = *GImGui;
16192 return g.Viewports[0];
16193}
16194
16195// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
16196ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
16197{
16198 ImGuiContext& g = *GImGui;
16199 for (ImGuiViewportP* viewport : g.Viewports)
16200 if (viewport->ID == id)
16201 return viewport;
16202 return NULL;
16203}
16204
16205ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
16206{
16207 ImGuiContext& g = *GImGui;
16208 for (ImGuiViewportP* viewport : g.Viewports)
16209 if (viewport->PlatformHandle == platform_handle)
16210 return viewport;
16211 return NULL;
16212}
16213
16214void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
16215{
16216 ImGuiContext& g = *GImGui;
16217 (void)current_window;
16218
16219 if (viewport)
16220 viewport->LastFrameActive = g.FrameCount;
16221 if (g.CurrentViewport == viewport)
16222 return;
16223 g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
16224 g.CurrentViewport = viewport;
16225 IM_ASSERT(g.CurrentDpiScale > 0.0f && g.CurrentDpiScale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
16226 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
16227
16228 // Notify platform layer of viewport changes
16229 // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
16230 if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
16231 g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
16232}
16233
16234void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16235{
16236 // Abandon viewport
16237 if (window->ViewportOwned && window->Viewport->Window == window)
16238 window->Viewport->Size = ImVec2(0.0f, 0.0f);
16239
16240 window->Viewport = viewport;
16241 window->ViewportId = viewport->ID;
16242 window->ViewportOwned = (viewport->Window == window);
16243}
16244
16245static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
16246{
16247 // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
16248 ImGuiContext& g = *GImGui;
16249 if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
16250 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16251 if (!window->DockIsActive)
16252 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
16253 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
16254 return true;
16255 return false;
16256}
16257
16258static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16259{
16260 ImGuiContext& g = *GImGui;
16261 if (window->Viewport == viewport)
16262 return false;
16263 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
16264 return false;
16265 if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
16266 return false;
16267 if (!viewport->GetMainRect().Contains(r: window->Rect()))
16268 return false;
16269 if (GetWindowAlwaysWantOwnViewport(window))
16270 return false;
16271
16272 // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
16273 for (ImGuiWindow* window_behind : g.Windows)
16274 {
16275 if (window_behind == window)
16276 break;
16277 if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
16278 if (window_behind->Viewport->GetMainRect().Overlaps(r: window->Rect()))
16279 return false;
16280 }
16281
16282 // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
16283 ImGuiViewportP* old_viewport = window->Viewport;
16284 if (window->ViewportOwned)
16285 for (int n = 0; n < g.Windows.Size; n++)
16286 if (g.Windows[n]->Viewport == old_viewport)
16287 SetWindowViewport(window: g.Windows[n], viewport);
16288 SetWindowViewport(window, viewport);
16289 BringWindowToDisplayFront(window);
16290
16291 return true;
16292}
16293
16294// FIXME: handle 0 to N host viewports
16295static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
16296{
16297 ImGuiContext& g = *GImGui;
16298 return UpdateTryMergeWindowIntoHostViewport(window, viewport: g.Viewports[0]);
16299}
16300
16301// Translate Dear ImGui windows when a Host Viewport has been moved
16302// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
16303void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size)
16304{
16305 ImGuiContext& g = *GImGui;
16306 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X\n", viewport->ID);
16307 IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
16308
16309 // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
16310 // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
16311 // 2) If it's not going to fit into the new size, keep it at same absolute position.
16312 // One problem with this is that most Win32 applications doesn't update their render while dragging,
16313 // and so the window will appear to teleport when releasing the mouse.
16314 const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
16315 ImRect test_still_fit_rect(old_pos, old_pos + old_size);
16316 ImVec2 delta_pos = new_pos - old_pos;
16317 for (ImGuiWindow* window : g.Windows) // FIXME-OPT
16318 if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(r: window->Rect()))))
16319 TranslateWindow(window, delta: delta_pos);
16320}
16321
16322// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
16323void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
16324{
16325 ImGuiContext& g = *GImGui;
16326 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport->ID);
16327 if (viewport->Window)
16328 {
16329 ScaleWindow(window: viewport->Window, scale);
16330 }
16331 else
16332 {
16333 for (ImGuiWindow* window : g.Windows)
16334 if (window->Viewport == viewport)
16335 ScaleWindow(window, scale);
16336 }
16337}
16338
16339// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
16340// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
16341// B) It requires Platform_GetWindowFocus to be implemented by backend.
16342ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
16343{
16344 ImGuiContext& g = *GImGui;
16345 ImGuiViewportP* best_candidate = NULL;
16346 for (ImGuiViewportP* viewport : g.Viewports)
16347 if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(p: mouse_platform_pos))
16348 if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
16349 best_candidate = viewport;
16350 return best_candidate;
16351}
16352
16353// Update viewports and monitor infos
16354// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
16355static void ImGui::UpdateViewportsNewFrame()
16356{
16357 ImGuiContext& g = *GImGui;
16358 IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
16359
16360 // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
16361 // Update Focused status
16362 const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
16363 if (viewports_enabled)
16364 {
16365 ImGuiViewportP* focused_viewport = NULL;
16366 for (ImGuiViewportP* viewport : g.Viewports)
16367 {
16368 const bool platform_funcs_available = viewport->PlatformWindowCreated;
16369 if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
16370 {
16371 bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
16372 if (is_minimized)
16373 viewport->Flags |= ImGuiViewportFlags_IsMinimized;
16374 else
16375 viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
16376 }
16377
16378 // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
16379 // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
16380 if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
16381 {
16382 bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
16383 if (is_focused)
16384 viewport->Flags |= ImGuiViewportFlags_IsFocused;
16385 else
16386 viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
16387 if (is_focused)
16388 focused_viewport = viewport;
16389 }
16390 }
16391
16392 // Focused viewport has changed?
16393 if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
16394 {
16395 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X '%s', attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID, focused_viewport->Window ? focused_viewport->Window->Name : "n/a");
16396 const ImGuiViewport* prev_focused_viewport = FindViewportByID(id: g.PlatformLastFocusedViewportId);
16397 const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
16398
16399 // Store a tag so we can infer z-order easily from all our windows
16400 // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
16401 // will keep the front most stamp instead of losing it back to their parent viewport.
16402 if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
16403 focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
16404 g.PlatformLastFocusedViewportId = focused_viewport->ID;
16405
16406 // Focus associated dear imgui window
16407 // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
16408 // - if focus didn't happen because we destroyed another window (#6462)
16409 // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
16410 const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
16411 if (apply_imgui_focus_on_focused_viewport && g.IO.ConfigViewportPlatformFocusSetsImGuiFocus)
16412 {
16413 focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
16414 ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
16415 if (focused_viewport->Window != NULL)
16416 FocusWindow(window: focused_viewport->Window, flags: focus_request_flags);
16417 else if (focused_viewport->LastFocusedHadNavWindow)
16418 FocusTopMostWindowUnderOne(NULL, NULL, filter_viewport: focused_viewport, flags: focus_request_flags); // Focus top most in viewport
16419 else
16420 FocusWindow(NULL, flags: focus_request_flags); // No window had focus last time viewport was focused
16421 }
16422 }
16423 if (focused_viewport)
16424 focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
16425 }
16426
16427 // Create/update main viewport with current platform position.
16428 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
16429 ImGuiViewportP* main_viewport = g.Viewports[0];
16430 IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
16431 IM_ASSERT(main_viewport->Window == NULL);
16432 ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
16433 ImVec2 main_viewport_size = g.IO.DisplaySize;
16434 ImVec2 main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale;
16435 if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
16436 {
16437 main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
16438 main_viewport_size = main_viewport->Size;
16439 main_viewport_framebuffer_scale = main_viewport->FramebufferScale;
16440 }
16441 AddUpdateViewport(NULL, id: IMGUI_VIEWPORT_DEFAULT_ID, platform_pos: main_viewport_pos, size: main_viewport_size, flags: ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
16442
16443 g.CurrentDpiScale = 0.0f;
16444 g.CurrentViewport = NULL;
16445 g.MouseViewport = NULL;
16446 for (int n = 0; n < g.Viewports.Size; n++)
16447 {
16448 ImGuiViewportP* viewport = g.Viewports[n];
16449 viewport->Idx = n;
16450
16451 // Erase unused viewports
16452 if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
16453 {
16454 DestroyViewport(viewport);
16455 n--;
16456 continue;
16457 }
16458
16459 const bool platform_funcs_available = viewport->PlatformWindowCreated;
16460 if (viewports_enabled)
16461 {
16462 // Update Position and Size (from Platform Window to ImGui) if requested.
16463 // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
16464 if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
16465 {
16466 // Viewport->WorkPos and WorkSize will be updated below
16467 if (viewport->PlatformRequestMove)
16468 viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
16469 if (viewport->PlatformRequestResize)
16470 viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
16471 if (g.PlatformIO.Platform_GetWindowFramebufferScale != NULL)
16472 viewport->FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport);
16473 }
16474 }
16475
16476 // Update/copy monitor info
16477 UpdateViewportPlatformMonitor(viewport);
16478
16479 // Lock down space taken by menu bars and status bars + query initial insets from backend
16480 // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
16481 viewport->WorkInsetMin = viewport->BuildWorkInsetMin;
16482 viewport->WorkInsetMax = viewport->BuildWorkInsetMax;
16483 viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f);
16484 if (g.PlatformIO.Platform_GetWindowWorkAreaInsets != NULL && platform_funcs_available)
16485 {
16486 ImVec4 insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport);
16487 IM_ASSERT(insets.x >= 0.0f && insets.y >= 0.0f && insets.z >= 0.0f && insets.w >= 0.0f);
16488 viewport->BuildWorkInsetMin = ImVec2(insets.x, insets.y);
16489 viewport->BuildWorkInsetMax = ImVec2(insets.z, insets.w);
16490 }
16491 viewport->UpdateWorkRect();
16492
16493 // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
16494 viewport->Alpha = 1.0f;
16495
16496 // Translate Dear ImGui windows when a Host Viewport has been moved
16497 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
16498 const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
16499 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
16500 TranslateWindowsInViewport(viewport, old_pos: viewport->LastPos, new_pos: viewport->Pos, old_size: viewport->LastSize, new_size: viewport->Size);
16501
16502 // Update DPI scale
16503 float new_dpi_scale;
16504 if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
16505 new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
16506 else if (viewport->PlatformMonitor != -1)
16507 new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
16508 else
16509 new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
16510 IM_ASSERT(new_dpi_scale > 0.0f && new_dpi_scale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
16511 if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
16512 {
16513 float scale_factor = new_dpi_scale / viewport->DpiScale;
16514 if (g.IO.ConfigDpiScaleViewports)
16515 ScaleWindowsInViewport(viewport, scale: scale_factor);
16516 //if (viewport == GetMainViewport())
16517 // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
16518
16519 // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
16520 // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
16521 // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
16522 //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
16523 // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
16524 }
16525 viewport->DpiScale = new_dpi_scale;
16526 }
16527
16528 // Update fallback monitor
16529 g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
16530 if (g.PlatformIO.Monitors.Size == 0)
16531 {
16532 ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
16533 monitor->MainPos = main_viewport->Pos;
16534 monitor->MainSize = main_viewport->Size;
16535 monitor->WorkPos = main_viewport->WorkPos;
16536 monitor->WorkSize = main_viewport->WorkSize;
16537 monitor->DpiScale = main_viewport->DpiScale;
16538 g.PlatformMonitorsFullWorkRect.Add(p: monitor->WorkPos);
16539 g.PlatformMonitorsFullWorkRect.Add(p: monitor->WorkPos + monitor->WorkSize);
16540 }
16541 else
16542 {
16543 g.FallbackMonitor = g.PlatformIO.Monitors[0];
16544 }
16545 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
16546 {
16547 g.PlatformMonitorsFullWorkRect.Add(p: monitor.WorkPos);
16548 g.PlatformMonitorsFullWorkRect.Add(p: monitor.WorkPos + monitor.WorkSize);
16549 }
16550
16551 if (!viewports_enabled)
16552 {
16553 g.MouseViewport = main_viewport;
16554 return;
16555 }
16556
16557 // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
16558 // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
16559 ImGuiViewportP* viewport_hovered = NULL;
16560 if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
16561 {
16562 viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(id: g.IO.MouseHoveredViewport) : NULL;
16563 if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
16564 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos: g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
16565 }
16566 else
16567 {
16568 // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
16569 // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
16570 // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
16571 // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
16572 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos: g.IO.MousePos);
16573 }
16574 if (viewport_hovered != NULL)
16575 g.MouseLastHoveredViewport = viewport_hovered;
16576 else if (g.MouseLastHoveredViewport == NULL)
16577 g.MouseLastHoveredViewport = g.Viewports[0];
16578
16579 // Update mouse reference viewport
16580 // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
16581 // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
16582 if (g.MovingWindow && g.MovingWindow->Viewport)
16583 g.MouseViewport = g.MovingWindow->Viewport;
16584 else
16585 g.MouseViewport = g.MouseLastHoveredViewport;
16586
16587 // When dragging something, always refer to the last hovered viewport.
16588 // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
16589 // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
16590 // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
16591 // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
16592 const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
16593 if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
16594 viewport_hovered = g.MouseLastHoveredViewport;
16595 if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
16596 if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
16597 g.MouseViewport = viewport_hovered;
16598
16599 IM_ASSERT(g.MouseViewport != NULL);
16600}
16601
16602// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
16603static void ImGui::UpdateViewportsEndFrame()
16604{
16605 ImGuiContext& g = *GImGui;
16606 g.PlatformIO.Viewports.resize(new_size: 0);
16607 for (int i = 0; i < g.Viewports.Size; i++)
16608 {
16609 ImGuiViewportP* viewport = g.Viewports[i];
16610 viewport->LastPos = viewport->Pos;
16611 viewport->LastSize = viewport->Size;
16612 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
16613 if (i > 0) // Always include main viewport in the list
16614 continue;
16615 if (viewport->Window && !IsWindowActiveAndVisible(window: viewport->Window))
16616 continue;
16617 if (i > 0)
16618 IM_ASSERT(viewport->Window != NULL);
16619 g.PlatformIO.Viewports.push_back(v: viewport);
16620 }
16621 g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
16622}
16623
16624// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
16625ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
16626{
16627 ImGuiContext& g = *GImGui;
16628 IM_ASSERT(id != 0);
16629
16630 flags |= ImGuiViewportFlags_IsPlatformWindow;
16631 if (window != NULL)
16632 {
16633 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
16634 if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
16635 flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
16636 if (!window_can_use_inputs)
16637 flags |= ImGuiViewportFlags_NoInputs;
16638 if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
16639 flags |= ImGuiViewportFlags_NoFocusOnAppearing;
16640 }
16641
16642 ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
16643 if (viewport)
16644 {
16645 // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
16646 ImVec2 prev_pos = viewport->Pos;
16647 ImVec2 prev_size = viewport->Size;
16648 if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
16649 viewport->Pos = pos;
16650 if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
16651 viewport->Size = size;
16652 viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
16653 if (prev_pos != viewport->Pos || prev_size != viewport->Size)
16654 UpdateViewportPlatformMonitor(viewport);
16655 }
16656 else
16657 {
16658 // New viewport
16659 viewport = IM_NEW(ImGuiViewportP)();
16660 viewport->ID = id;
16661 viewport->Idx = g.Viewports.Size;
16662 viewport->Pos = viewport->LastPos = pos;
16663 viewport->Size = viewport->LastSize = size;
16664 viewport->Flags = flags;
16665 UpdateViewportPlatformMonitor(viewport);
16666 g.Viewports.push_back(v: viewport);
16667 g.ViewportCreatedCount++;
16668 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
16669
16670 // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
16671 // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
16672 g.DrawListSharedData.ClipRectFullscreen.x = ImMin(lhs: g.DrawListSharedData.ClipRectFullscreen.x, rhs: viewport->Pos.x);
16673 g.DrawListSharedData.ClipRectFullscreen.y = ImMin(lhs: g.DrawListSharedData.ClipRectFullscreen.y, rhs: viewport->Pos.y);
16674 g.DrawListSharedData.ClipRectFullscreen.z = ImMax(lhs: g.DrawListSharedData.ClipRectFullscreen.z, rhs: viewport->Pos.x + viewport->Size.x);
16675 g.DrawListSharedData.ClipRectFullscreen.w = ImMax(lhs: g.DrawListSharedData.ClipRectFullscreen.w, rhs: viewport->Pos.y + viewport->Size.y);
16676
16677 // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
16678 // This is so we can select an appropriate font size on the first frame of our window lifetime
16679 viewport->DpiScale = GetViewportPlatformMonitor(viewport)->DpiScale;
16680 }
16681
16682 viewport->Window = window;
16683 viewport->LastFrameActive = g.FrameCount;
16684 viewport->UpdateWorkRect();
16685 IM_ASSERT(window == NULL || viewport->ID == window->ID);
16686
16687 if (window != NULL)
16688 window->ViewportOwned = true;
16689
16690 return viewport;
16691}
16692
16693static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
16694{
16695 // Clear references to this viewport in windows (window->ViewportId becomes the master data)
16696 ImGuiContext& g = *GImGui;
16697 for (ImGuiWindow* window : g.Windows)
16698 {
16699 if (window->Viewport != viewport)
16700 continue;
16701 window->Viewport = NULL;
16702 window->ViewportOwned = false;
16703 }
16704 if (viewport == g.MouseLastHoveredViewport)
16705 g.MouseLastHoveredViewport = NULL;
16706
16707 // Destroy
16708 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
16709 DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
16710 IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
16711 IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
16712 g.Viewports.erase(it: g.Viewports.Data + viewport->Idx);
16713 IM_DELETE(p: viewport);
16714}
16715
16716// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
16717static void ImGui::WindowSelectViewport(ImGuiWindow* window)
16718{
16719 ImGuiContext& g = *GImGui;
16720 ImGuiWindowFlags flags = window->Flags;
16721 window->ViewportAllowPlatformMonitorExtend = -1;
16722
16723 // Restore main viewport if multi-viewport is not supported by the backend
16724 ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
16725 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
16726 {
16727 SetWindowViewport(window, viewport: main_viewport);
16728 return;
16729 }
16730 window->ViewportOwned = false;
16731
16732 // Appearing popups reset their viewport so they can inherit again
16733 if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
16734 {
16735 window->Viewport = NULL;
16736 window->ViewportId = 0;
16737 }
16738
16739 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport) == 0)
16740 {
16741 // By default inherit from parent window
16742 if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
16743 window->Viewport = window->ParentWindow->Viewport;
16744
16745 // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
16746 if (window->Viewport == NULL && window->ViewportId != 0)
16747 {
16748 window->Viewport = (ImGuiViewportP*)FindViewportByID(id: window->ViewportId);
16749 if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
16750 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->ViewportPos, size: window->Size, flags: ImGuiViewportFlags_None);
16751 }
16752 }
16753
16754 bool lock_viewport = false;
16755 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport)
16756 {
16757 // Code explicitly request a viewport
16758 window->Viewport = (ImGuiViewportP*)FindViewportByID(id: g.NextWindowData.ViewportId);
16759 window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
16760 if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
16761 {
16762 window->Viewport->Window = window;
16763 window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
16764 }
16765 lock_viewport = true;
16766 }
16767 else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
16768 {
16769 // Always inherit viewport from parent window
16770 if (window->DockNode && window->DockNode->HostWindow)
16771 IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
16772 window->Viewport = window->ParentWindow->Viewport;
16773 }
16774 else if (window->DockNode && window->DockNode->HostWindow)
16775 {
16776 // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
16777 window->Viewport = window->DockNode->HostWindow->Viewport;
16778 }
16779 else if (flags & ImGuiWindowFlags_Tooltip)
16780 {
16781 window->Viewport = g.MouseViewport;
16782 }
16783 else if (GetWindowAlwaysWantOwnViewport(window))
16784 {
16785 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_None);
16786 }
16787 else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
16788 {
16789 if (window->Viewport != NULL && window->Viewport->Window == window)
16790 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_None);
16791 }
16792 else
16793 {
16794 // Merge into host viewport?
16795 // We cannot test window->ViewportOwned as it set lower in the function.
16796 // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
16797 bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
16798 if (try_to_merge_into_host_viewport)
16799 UpdateTryMergeWindowIntoHostViewports(window);
16800 }
16801
16802 // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
16803 if (window->Viewport == NULL)
16804 if (!UpdateTryMergeWindowIntoHostViewport(window, viewport: main_viewport))
16805 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_None);
16806
16807 // Mark window as allowed to protrude outside of its viewport and into the current monitor
16808 if (!lock_viewport)
16809 {
16810 if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
16811 {
16812 // We need to take account of the possibility that mouse may become invalid.
16813 // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
16814 ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
16815 bool use_mouse_ref = (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !g.NavWindow);
16816 bool mouse_valid = IsMousePosValid(mouse_pos: &mouse_ref);
16817 if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
16818 window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos(pos: (use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
16819 else
16820 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
16821 }
16822 else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
16823 {
16824 // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
16825 const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
16826 if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
16827 {
16828 // Steal/transfer ownership
16829 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
16830 window->Viewport->Window = window;
16831 window->Viewport->ID = window->ID;
16832 window->Viewport->LastNameHash = 0;
16833 }
16834 else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
16835 {
16836 // New viewport
16837 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_NoFocusOnAppearing);
16838 }
16839 }
16840 else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
16841 {
16842 // Regular (non-child, non-popup) windows by default are also allowed to protrude
16843 // Child windows are kept contained within their parent.
16844 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
16845 }
16846 }
16847
16848 // Update flags
16849 window->ViewportOwned = (window == window->Viewport->Window);
16850 window->ViewportId = window->Viewport->ID;
16851
16852 // If the OS window has a title bar, hide our imgui title bar
16853 //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
16854 // window->Flags |= ImGuiWindowFlags_NoTitleBar;
16855}
16856
16857void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
16858{
16859 ImGuiContext& g = *GImGui;
16860
16861 bool viewport_rect_changed = false;
16862
16863 // Synchronize window --> viewport in most situations
16864 // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
16865 if (window->Viewport->PlatformRequestMove)
16866 {
16867 window->Pos = window->Viewport->Pos;
16868 MarkIniSettingsDirty(window);
16869 }
16870 else if (memcmp(s1: &window->Viewport->Pos, s2: &window->Pos, n: sizeof(window->Pos)) != 0)
16871 {
16872 viewport_rect_changed = true;
16873 window->Viewport->Pos = window->Pos;
16874 }
16875
16876 if (window->Viewport->PlatformRequestResize)
16877 {
16878 window->Size = window->SizeFull = window->Viewport->Size;
16879 MarkIniSettingsDirty(window);
16880 }
16881 else if (memcmp(s1: &window->Viewport->Size, s2: &window->Size, n: sizeof(window->Size)) != 0)
16882 {
16883 viewport_rect_changed = true;
16884 window->Viewport->Size = window->Size;
16885 }
16886 window->Viewport->UpdateWorkRect();
16887
16888 // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
16889 // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
16890 if (viewport_rect_changed)
16891 UpdateViewportPlatformMonitor(viewport: window->Viewport);
16892
16893 // Update common viewport flags
16894 const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
16895 ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
16896 ImGuiWindowFlags window_flags = window->Flags;
16897 const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
16898 const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
16899 if (window_flags & ImGuiWindowFlags_Tooltip)
16900 viewport_flags |= ImGuiViewportFlags_TopMost;
16901 if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
16902 viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
16903 if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
16904 viewport_flags |= ImGuiViewportFlags_NoDecoration;
16905
16906 // Not correct to set modal as topmost because:
16907 // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
16908 // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
16909 //if (flags & ImGuiWindowFlags_Modal)
16910 // viewport_flags |= ImGuiViewportFlags_TopMost;
16911
16912 // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
16913 // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
16914 // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
16915 // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
16916 if (is_short_lived_floating_window && !is_modal)
16917 viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
16918
16919 // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
16920 if (window->WindowClass.ViewportFlagsOverrideSet)
16921 viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
16922 if (window->WindowClass.ViewportFlagsOverrideClear)
16923 viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
16924
16925 // We can also tell the backend that clearing the platform window won't be necessary,
16926 // as our window background is filling the viewport and we have disabled BgAlpha.
16927 // FIXME: Work on support for per-viewport transparency (#2766)
16928 if (!(window_flags & ImGuiWindowFlags_NoBackground))
16929 viewport_flags |= ImGuiViewportFlags_NoRendererClear;
16930
16931 window->Viewport->Flags = viewport_flags;
16932
16933 // Update parent viewport ID
16934 // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
16935 if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
16936 window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
16937 else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
16938 window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
16939 else
16940 window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
16941}
16942
16943// Called by user at the end of the main loop, after EndFrame()
16944// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
16945void ImGui::UpdatePlatformWindows()
16946{
16947 ImGuiContext& g = *GImGui;
16948 IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
16949 IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
16950 g.FrameCountPlatformEnded = g.FrameCount;
16951 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
16952 return;
16953
16954 // Create/resize/destroy platform windows to match each active viewport.
16955 // Skip the main viewport (index 0), which is always fully handled by the application!
16956 for (int i = 1; i < g.Viewports.Size; i++)
16957 {
16958 ImGuiViewportP* viewport = g.Viewports[i];
16959
16960 // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
16961 // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
16962 bool destroy_platform_window = false;
16963 destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
16964 destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(window: viewport->Window));
16965 if (destroy_platform_window)
16966 {
16967 DestroyPlatformWindow(viewport);
16968 continue;
16969 }
16970
16971 // New windows that appears directly in a new viewport won't always have a size on their first frame
16972 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
16973 continue;
16974
16975 // Create window
16976 const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
16977 if (is_new_platform_window)
16978 {
16979 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
16980 g.PlatformIO.Platform_CreateWindow(viewport);
16981 if (g.PlatformIO.Renderer_CreateWindow != NULL)
16982 g.PlatformIO.Renderer_CreateWindow(viewport);
16983 g.PlatformWindowsCreatedCount++;
16984 viewport->LastNameHash = 0;
16985 viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
16986 viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
16987 viewport->PlatformWindowCreated = true;
16988 }
16989
16990 // Apply Position and Size (from ImGui to Platform/Renderer backends)
16991 if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
16992 g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
16993 if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
16994 g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
16995 if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
16996 g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
16997 viewport->LastPlatformPos = viewport->Pos;
16998 viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
16999
17000 // Update title bar (if it changed)
17001 if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(window: viewport->Window))
17002 {
17003 const char* title_begin = window_for_title->Name;
17004 char* title_end = (char*)(intptr_t)FindRenderedTextEnd(text: title_begin);
17005 const ImGuiID title_hash = ImHashStr(data_p: title_begin, data_size: title_end - title_begin);
17006 if (viewport->LastNameHash != title_hash)
17007 {
17008 char title_end_backup_c = *title_end;
17009 *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
17010 g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
17011 *title_end = title_end_backup_c;
17012 viewport->LastNameHash = title_hash;
17013 }
17014 }
17015
17016 // Update alpha (if it changed)
17017 if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
17018 g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
17019 viewport->LastAlpha = viewport->Alpha;
17020
17021 // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
17022 if (g.PlatformIO.Platform_UpdateWindow)
17023 g.PlatformIO.Platform_UpdateWindow(viewport);
17024
17025 if (is_new_platform_window)
17026 {
17027 // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
17028 if (g.FrameCount < 3)
17029 viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
17030
17031 // Show window
17032 g.PlatformIO.Platform_ShowWindow(viewport);
17033
17034 // Even without focus, we assume the window becomes front-most.
17035 // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
17036 if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
17037 viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
17038 }
17039
17040 // Clear request flags
17041 viewport->ClearRequestFlags();
17042 }
17043}
17044
17045// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
17046// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
17047// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
17048//
17049// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
17050// for (int i = 1; i < platform_io.Viewports.Size; i++)
17051// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
17052// MyRenderFunction(platform_io.Viewports[i], my_args);
17053// for (int i = 1; i < platform_io.Viewports.Size; i++)
17054// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
17055// MySwapBufferFunction(platform_io.Viewports[i], my_args);
17056//
17057void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
17058{
17059 // Skip the main viewport (index 0), which is always fully handled by the application!
17060 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
17061 for (int i = 1; i < platform_io.Viewports.Size; i++)
17062 {
17063 ImGuiViewport* viewport = platform_io.Viewports[i];
17064 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
17065 continue;
17066 if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
17067 if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
17068 }
17069 for (int i = 1; i < platform_io.Viewports.Size; i++)
17070 {
17071 ImGuiViewport* viewport = platform_io.Viewports[i];
17072 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
17073 continue;
17074 if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
17075 if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
17076 }
17077}
17078
17079static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
17080{
17081 ImGuiContext& g = *GImGui;
17082 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
17083 {
17084 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
17085 if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(p: pos))
17086 return monitor_n;
17087 }
17088 return -1;
17089}
17090
17091// Search for the monitor with the largest intersection area with the given rectangle
17092// We generally try to avoid searching loops but the monitor count should be very small here
17093// FIXME-OPT: We could test the last monitor used for that viewport first, and early
17094static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
17095{
17096 ImGuiContext& g = *GImGui;
17097
17098 const int monitor_count = g.PlatformIO.Monitors.Size;
17099 if (monitor_count <= 1)
17100 return monitor_count - 1;
17101
17102 // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
17103 // This is necessary for tooltips which always resize down to zero at first.
17104 const float surface_threshold = ImMax(lhs: rect.GetWidth() * rect.GetHeight() * 0.5f, rhs: 1.0f);
17105 int best_monitor_n = 0; // Default to the first monitor as fallback
17106 float best_monitor_surface = 0.001f;
17107
17108 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
17109 {
17110 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
17111 const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
17112 if (monitor_rect.Contains(r: rect))
17113 return monitor_n;
17114 ImRect overlapping_rect = rect;
17115 overlapping_rect.ClipWithFull(r: monitor_rect);
17116 float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
17117 if (overlapping_surface < best_monitor_surface)
17118 continue;
17119 best_monitor_surface = overlapping_surface;
17120 best_monitor_n = monitor_n;
17121 }
17122 return best_monitor_n;
17123}
17124
17125// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
17126static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
17127{
17128 viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(rect: viewport->GetMainRect());
17129}
17130
17131// Return value is always != NULL, but don't hold on it across frames.
17132const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
17133{
17134 ImGuiContext& g = *GImGui;
17135 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
17136 int monitor_idx = viewport->PlatformMonitor;
17137 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
17138 return &g.PlatformIO.Monitors[monitor_idx];
17139 return &g.FallbackMonitor;
17140}
17141
17142void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
17143{
17144 ImGuiContext& g = *GImGui;
17145 if (viewport->PlatformWindowCreated)
17146 {
17147 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
17148 if (g.PlatformIO.Renderer_DestroyWindow)
17149 g.PlatformIO.Renderer_DestroyWindow(viewport);
17150 if (g.PlatformIO.Platform_DestroyWindow)
17151 g.PlatformIO.Platform_DestroyWindow(viewport);
17152 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
17153
17154 // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
17155 // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
17156 if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
17157 viewport->PlatformWindowCreated = false;
17158 }
17159 else
17160 {
17161 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
17162 }
17163 viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
17164 viewport->ClearRequestFlags();
17165}
17166
17167void ImGui::DestroyPlatformWindows()
17168{
17169 // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
17170 // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
17171 // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
17172 // code to operator a consistent manner.
17173 // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
17174 // crashing if it doesn't have data stored.
17175 ImGuiContext& g = *GImGui;
17176 for (ImGuiViewportP* viewport : g.Viewports)
17177 DestroyPlatformWindow(viewport);
17178}
17179
17180
17181//-----------------------------------------------------------------------------
17182// [SECTION] DOCKING
17183//-----------------------------------------------------------------------------
17184// Docking: Internal Types
17185// Docking: Forward Declarations
17186// Docking: ImGuiDockContext
17187// Docking: ImGuiDockContext Docking/Undocking functions
17188// Docking: ImGuiDockNode
17189// Docking: ImGuiDockNode Tree manipulation functions
17190// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17191// Docking: Builder Functions
17192// Docking: Begin/End Support Functions (called from Begin/End)
17193// Docking: Settings
17194//-----------------------------------------------------------------------------
17195
17196//-----------------------------------------------------------------------------
17197// Typical Docking call flow: (root level is generally public API):
17198//-----------------------------------------------------------------------------
17199// - NewFrame() new dear imgui frame
17200// | DockContextNewFrameUpdateUndocking() - process queued undocking requests
17201// | - DockContextProcessUndockWindow() - process one window undocking request
17202// | - DockContextProcessUndockNode() - process one whole node undocking request
17203// | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes
17204// | - update g.HoveredDockNode - [debug] update node hovered by mouse
17205// | - DockContextProcessDock() - process one docking request
17206// | - DockNodeUpdate()
17207// | - DockNodeUpdateForRootNode()
17208// | - DockNodeUpdateFlagsAndCollapse()
17209// | - DockNodeFindInfo()
17210// | - destroy unused node or tab bar
17211// | - create dock node host window
17212// | - Begin() etc.
17213// | - DockNodeStartMouseMovingWindow()
17214// | - DockNodeTreeUpdatePosSize()
17215// | - DockNodeTreeUpdateSplitter()
17216// | - draw node background
17217// | - DockNodeUpdateTabBar() - create/update tab bar for a docking node
17218// | - DockNodeAddTabBar()
17219// | - DockNodeWindowMenuUpdate()
17220// | - DockNodeCalcTabBarLayout()
17221// | - BeginTabBarEx()
17222// | - TabItemEx() calls
17223// | - EndTabBar()
17224// | - BeginDockableDragDropTarget()
17225// | - DockNodeUpdate() - recurse into child nodes...
17226//-----------------------------------------------------------------------------
17227// - DockSpace() user submit a dockspace into a window
17228// | Begin(Child) - create a child window
17229// | DockNodeUpdate() - call main dock node update function
17230// | End(Child)
17231// | ItemSize()
17232//-----------------------------------------------------------------------------
17233// - Begin()
17234// | BeginDocked()
17235// | BeginDockableDragDropSource()
17236// | BeginDockableDragDropTarget()
17237// | - DockNodePreviewDockRender()
17238//-----------------------------------------------------------------------------
17239// - EndFrame()
17240// | DockContextEndFrame()
17241//-----------------------------------------------------------------------------
17242
17243//-----------------------------------------------------------------------------
17244// Docking: Internal Types
17245//-----------------------------------------------------------------------------
17246// - ImGuiDockRequestType
17247// - ImGuiDockRequest
17248// - ImGuiDockPreviewData
17249// - ImGuiDockNodeSettings
17250// - ImGuiDockContext
17251//-----------------------------------------------------------------------------
17252
17253enum ImGuiDockRequestType
17254{
17255 ImGuiDockRequestType_None = 0,
17256 ImGuiDockRequestType_Dock,
17257 ImGuiDockRequestType_Undock,
17258 ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
17259};
17260
17261struct ImGuiDockRequest
17262{
17263 ImGuiDockRequestType Type;
17264 ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
17265 ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
17266 ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
17267 ImGuiDir DockSplitDir;
17268 float DockSplitRatio;
17269 bool DockSplitOuter;
17270 ImGuiWindow* UndockTargetWindow;
17271 ImGuiDockNode* UndockTargetNode;
17272
17273 ImGuiDockRequest()
17274 {
17275 Type = ImGuiDockRequestType_None;
17276 DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
17277 DockTargetNode = UndockTargetNode = NULL;
17278 DockSplitDir = ImGuiDir_None;
17279 DockSplitRatio = 0.5f;
17280 DockSplitOuter = false;
17281 }
17282};
17283
17284struct ImGuiDockPreviewData
17285{
17286 ImGuiDockNode FutureNode;
17287 bool IsDropAllowed;
17288 bool IsCenterAvailable;
17289 bool IsSidesAvailable; // Hold your breath, grammar freaks..
17290 bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
17291 ImGuiDockNode* SplitNode;
17292 ImGuiDir SplitDir;
17293 float SplitRatio;
17294 ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
17295
17296 ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
17297};
17298
17299// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
17300struct ImGuiDockNodeSettings
17301{
17302 ImGuiID ID;
17303 ImGuiID ParentNodeId;
17304 ImGuiID ParentWindowId;
17305 ImGuiID SelectedTabId;
17306 signed char SplitAxis;
17307 char Depth;
17308 ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
17309 ImVec2ih Pos;
17310 ImVec2ih Size;
17311 ImVec2ih SizeRef;
17312 ImGuiDockNodeSettings() { memset(s: this, c: 0, n: sizeof(*this)); SplitAxis = ImGuiAxis_None; }
17313};
17314
17315//-----------------------------------------------------------------------------
17316// Docking: Forward Declarations
17317//-----------------------------------------------------------------------------
17318
17319namespace ImGui
17320{
17321 // ImGuiDockContext
17322 static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
17323 static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
17324 static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
17325 static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
17326 static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
17327 static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
17328 static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
17329 static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
17330
17331 // ImGuiDockNode
17332 static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
17333 static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
17334 static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
17335 static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
17336 static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
17337 static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
17338 static void DockNodeHideHostWindow(ImGuiDockNode* node);
17339 static void DockNodeUpdate(ImGuiDockNode* node);
17340 static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
17341 static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
17342 static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
17343 static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
17344 static void DockNodeAddTabBar(ImGuiDockNode* node);
17345 static void DockNodeRemoveTabBar(ImGuiDockNode* node);
17346 static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
17347 static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
17348 static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
17349 static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
17350 static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
17351 static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
17352 static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
17353 static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
17354 static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
17355 static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, fmt: "##DockNode_%02X", node->ID); return buf; }
17356 static int DockNodeGetTabOrder(ImGuiWindow* window);
17357
17358 // ImGuiDockNode tree manipulations
17359 static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
17360 static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
17361 static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
17362 static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
17363 static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
17364 static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
17365
17366 // Settings
17367 static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
17368 static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
17369 static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
17370 static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
17371 static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
17372 static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
17373 static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
17374 static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
17375}
17376
17377//-----------------------------------------------------------------------------
17378// Docking: ImGuiDockContext
17379//-----------------------------------------------------------------------------
17380// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
17381// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
17382// At boot time only, we run a simple GC to remove nodes that have no references.
17383// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
17384// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
17385// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
17386//-----------------------------------------------------------------------------
17387// - DockContextInitialize()
17388// - DockContextShutdown()
17389// - DockContextClearNodes()
17390// - DockContextRebuildNodes()
17391// - DockContextNewFrameUpdateUndocking()
17392// - DockContextNewFrameUpdateDocking()
17393// - DockContextEndFrame()
17394// - DockContextFindNodeByID()
17395// - DockContextBindNodeToWindow()
17396// - DockContextGenNodeID()
17397// - DockContextAddNode()
17398// - DockContextRemoveNode()
17399// - ImGuiDockContextPruneNodeData
17400// - DockContextPruneUnusedSettingsNodes()
17401// - DockContextBuildNodesFromSettings()
17402// - DockContextBuildAddWindowsToNodes()
17403//-----------------------------------------------------------------------------
17404
17405void ImGui::DockContextInitialize(ImGuiContext* ctx)
17406{
17407 ImGuiContext& g = *ctx;
17408
17409 // Add .ini handle for persistent docking data
17410 ImGuiSettingsHandler ini_handler;
17411 ini_handler.TypeName = "Docking";
17412 ini_handler.TypeHash = ImHashStr(data_p: "Docking");
17413 ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
17414 ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
17415 ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
17416 ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
17417 ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
17418 ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
17419 g.SettingsHandlers.push_back(v: ini_handler);
17420
17421 g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
17422}
17423
17424void ImGui::DockContextShutdown(ImGuiContext* ctx)
17425{
17426 ImGuiDockContext* dc = &ctx->DockContext;
17427 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17428 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17429 IM_DELETE(p: node);
17430}
17431
17432void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
17433{
17434 IM_UNUSED(ctx);
17435 IM_ASSERT(ctx == GImGui);
17436 DockBuilderRemoveNodeDockedWindows(node_id: root_id, clear_settings_refs);
17437 DockBuilderRemoveNodeChildNodes(node_id: root_id);
17438}
17439
17440// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
17441// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
17442void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
17443{
17444 ImGuiContext& g = *ctx;
17445 ImGuiDockContext* dc = &ctx->DockContext;
17446 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
17447 SaveIniSettingsToMemory();
17448 ImGuiID root_id = 0; // Rebuild all
17449 DockContextClearNodes(ctx, root_id, clear_settings_refs: false);
17450 DockContextBuildNodesFromSettings(ctx, node_settings_array: dc->NodesSettings.Data, node_settings_count: dc->NodesSettings.Size);
17451 DockContextBuildAddWindowsToNodes(ctx, root_id);
17452}
17453
17454// Docking context update function, called by NewFrame()
17455void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
17456{
17457 ImGuiContext& g = *ctx;
17458 ImGuiDockContext* dc = &ctx->DockContext;
17459 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17460 {
17461 if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
17462 DockContextClearNodes(ctx, root_id: 0, clear_settings_refs: true);
17463 return;
17464 }
17465
17466 // Setting NoSplit at runtime merges all nodes
17467 if (g.IO.ConfigDockingNoSplit)
17468 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17469 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17470 if (node->IsRootNode() && node->IsSplitNode())
17471 {
17472 DockBuilderRemoveNodeChildNodes(node_id: node->ID);
17473 //dc->WantFullRebuild = true;
17474 }
17475
17476 // Process full rebuild
17477#if 0
17478 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
17479 dc->WantFullRebuild = true;
17480#endif
17481 if (dc->WantFullRebuild)
17482 {
17483 DockContextRebuildNodes(ctx);
17484 dc->WantFullRebuild = false;
17485 }
17486
17487 // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
17488 for (ImGuiDockRequest& req : dc->Requests)
17489 {
17490 if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
17491 DockContextProcessUndockWindow(ctx, window: req.UndockTargetWindow);
17492 else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
17493 DockContextProcessUndockNode(ctx, node: req.UndockTargetNode);
17494 }
17495}
17496
17497// Docking context update function, called by NewFrame()
17498void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
17499{
17500 ImGuiContext& g = *ctx;
17501 ImGuiDockContext* dc = &ctx->DockContext;
17502 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17503 return;
17504
17505 // [DEBUG] Store hovered dock node.
17506 // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
17507 // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
17508 g.DebugHoveredDockNode = NULL;
17509 if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
17510 {
17511 if (hovered_window->DockNodeAsHost)
17512 g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(node: hovered_window->DockNodeAsHost, pos: g.IO.MousePos);
17513 else if (hovered_window->RootWindow->DockNode)
17514 g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
17515 }
17516
17517 // Process Docking requests
17518 for (ImGuiDockRequest& req : dc->Requests)
17519 if (req.Type == ImGuiDockRequestType_Dock)
17520 DockContextProcessDock(ctx, req: &req);
17521 dc->Requests.resize(new_size: 0);
17522
17523 // Create windows for each automatic docking nodes
17524 // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
17525 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17526 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17527 if (node->IsFloatingNode())
17528 DockNodeUpdate(node);
17529}
17530
17531void ImGui::DockContextEndFrame(ImGuiContext* ctx)
17532{
17533 // Draw backgrounds of node missing their window
17534 ImGuiContext& g = *ctx;
17535 ImGuiDockContext* dc = &g.DockContext;
17536 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17537 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17538 if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
17539 {
17540 ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
17541 ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(r_in: bg_rect, r_outer: node->HostWindow->Rect(), threshold: g.Style.DockingSeparatorSize);
17542 node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17543 node->HostWindow->DrawList->AddRectFilled(p_min: bg_rect.Min, p_max: bg_rect.Max, col: node->LastBgColor, rounding: node->HostWindow->WindowRounding, flags: bg_rounding_flags);
17544 }
17545}
17546
17547ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
17548{
17549 return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(key: id);
17550}
17551
17552ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
17553{
17554 // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
17555 // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
17556 // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
17557 ImGuiID id = 0x0001;
17558 while (DockContextFindNodeByID(ctx, id) != NULL)
17559 id++;
17560 return id;
17561}
17562
17563static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
17564{
17565 // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
17566 ImGuiContext& g = *ctx;
17567 if (id == 0)
17568 id = DockContextGenNodeID(ctx);
17569 else
17570 IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
17571
17572 // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
17573 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
17574 ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
17575 ctx->DockContext.Nodes.SetVoidPtr(key: node->ID, val: node);
17576 return node;
17577}
17578
17579static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
17580{
17581 ImGuiContext& g = *ctx;
17582 ImGuiDockContext* dc = &ctx->DockContext;
17583
17584 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
17585 IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
17586 IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
17587 IM_ASSERT(node->Windows.Size == 0);
17588
17589 if (node->HostWindow)
17590 node->HostWindow->DockNodeAsHost = NULL;
17591
17592 ImGuiDockNode* parent_node = node->ParentNode;
17593 const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
17594 if (merge)
17595 {
17596 IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
17597 ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
17598 DockNodeTreeMerge(ctx: &g, parent_node, merge_lead_child: sibling_node);
17599 }
17600 else
17601 {
17602 for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
17603 if (parent_node->ChildNodes[n] == node)
17604 node->ParentNode->ChildNodes[n] = NULL;
17605 dc->Nodes.SetVoidPtr(key: node->ID, NULL);
17606 IM_DELETE(p: node);
17607 }
17608}
17609
17610static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
17611{
17612 const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
17613 const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
17614 return ImGui::DockNodeGetDepth(node: b) - ImGui::DockNodeGetDepth(node: a);
17615}
17616
17617// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
17618struct ImGuiDockContextPruneNodeData
17619{
17620 int CountWindows, CountChildWindows, CountChildNodes;
17621 ImGuiID RootId;
17622 ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
17623};
17624
17625// Garbage collect unused nodes (run once at init time)
17626static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
17627{
17628 ImGuiContext& g = *ctx;
17629 ImGuiDockContext* dc = &ctx->DockContext;
17630 IM_ASSERT(g.Windows.Size == 0);
17631
17632 ImPool<ImGuiDockContextPruneNodeData> pool;
17633 pool.Reserve(capacity: dc->NodesSettings.Size);
17634
17635 // Count child nodes and compute RootID
17636 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17637 {
17638 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17639 ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(key: settings->ParentNodeId) : 0;
17640 pool.GetOrAddByKey(key: settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
17641 if (settings->ParentNodeId)
17642 pool.GetOrAddByKey(key: settings->ParentNodeId)->CountChildNodes++;
17643 }
17644
17645 // Count reference to dock ids from dockspaces
17646 // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
17647 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17648 {
17649 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17650 if (settings->ParentWindowId != 0)
17651 if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(id: settings->ParentWindowId))
17652 if (window_settings->DockId)
17653 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(key: window_settings->DockId))
17654 data->CountChildNodes++;
17655 }
17656
17657 // Count reference to dock ids from window settings
17658 // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
17659 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
17660 if (ImGuiID dock_id = settings->DockId)
17661 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(key: dock_id))
17662 {
17663 data->CountWindows++;
17664 if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(key: data->RootId))
17665 data_root->CountChildWindows++;
17666 }
17667
17668 // Prune
17669 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17670 {
17671 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17672 ImGuiDockContextPruneNodeData* data = pool.GetByKey(key: settings->ID);
17673 if (data == NULL || data->CountWindows > 1)
17674 continue;
17675 ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(key: data->RootId);
17676
17677 bool remove = false;
17678 remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
17679 remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
17680 remove |= (data_root->CountChildWindows == 0);
17681 if (remove)
17682 {
17683 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
17684 DockSettingsRemoveNodeReferences(node_ids: &settings->ID, node_ids_count: 1);
17685 settings->ID = 0;
17686 }
17687 }
17688}
17689
17690static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
17691{
17692 // Build nodes
17693 for (int node_n = 0; node_n < node_settings_count; node_n++)
17694 {
17695 ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
17696 if (settings->ID == 0)
17697 continue;
17698 ImGuiDockNode* node = DockContextAddNode(ctx, id: settings->ID);
17699 node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, id: settings->ParentNodeId) : NULL;
17700 node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
17701 node->Size = ImVec2(settings->Size.x, settings->Size.y);
17702 node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
17703 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
17704 if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
17705 node->ParentNode->ChildNodes[0] = node;
17706 else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
17707 node->ParentNode->ChildNodes[1] = node;
17708 node->SelectedTabId = settings->SelectedTabId;
17709 node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
17710 node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
17711
17712 // Bind host window immediately if it already exist (in case of a rebuild)
17713 // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
17714 char host_window_title[20];
17715 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17716 node->HostWindow = FindWindowByName(name: DockNodeGetHostWindowTitle(node: root_node, buf: host_window_title, IM_ARRAYSIZE(host_window_title)));
17717 }
17718}
17719
17720void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
17721{
17722 // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
17723 ImGuiContext& g = *ctx;
17724 for (ImGuiWindow* window : g.Windows)
17725 {
17726 if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
17727 continue;
17728 if (window->DockNode != NULL)
17729 continue;
17730
17731 ImGuiDockNode* node = DockContextFindNodeByID(ctx, id: window->DockId);
17732 IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
17733 if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
17734 DockNodeAddWindow(node, window, add_to_tab_bar: true);
17735 }
17736}
17737
17738//-----------------------------------------------------------------------------
17739// Docking: ImGuiDockContext Docking/Undocking functions
17740//-----------------------------------------------------------------------------
17741// - DockContextQueueDock()
17742// - DockContextQueueUndockWindow()
17743// - DockContextQueueUndockNode()
17744// - DockContextQueueNotifyRemovedNode()
17745// - DockContextProcessDock()
17746// - DockContextProcessUndockWindow()
17747// - DockContextProcessUndockNode()
17748// - DockContextCalcDropPosForDocking()
17749//-----------------------------------------------------------------------------
17750
17751void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
17752{
17753 IM_ASSERT(target != payload);
17754 ImGuiDockRequest req;
17755 req.Type = ImGuiDockRequestType_Dock;
17756 req.DockTargetWindow = target;
17757 req.DockTargetNode = target_node;
17758 req.DockPayload = payload;
17759 req.DockSplitDir = split_dir;
17760 req.DockSplitRatio = split_ratio;
17761 req.DockSplitOuter = split_outer;
17762 ctx->DockContext.Requests.push_back(v: req);
17763}
17764
17765void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
17766{
17767 ImGuiDockRequest req;
17768 req.Type = ImGuiDockRequestType_Undock;
17769 req.UndockTargetWindow = window;
17770 ctx->DockContext.Requests.push_back(v: req);
17771}
17772
17773void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
17774{
17775 ImGuiDockRequest req;
17776 req.Type = ImGuiDockRequestType_Undock;
17777 req.UndockTargetNode = node;
17778 ctx->DockContext.Requests.push_back(v: req);
17779}
17780
17781void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
17782{
17783 ImGuiDockContext* dc = &ctx->DockContext;
17784 for (ImGuiDockRequest& req : dc->Requests)
17785 if (req.DockTargetNode == node)
17786 req.Type = ImGuiDockRequestType_None;
17787}
17788
17789void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
17790{
17791 IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
17792 IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
17793
17794 ImGuiContext& g = *ctx;
17795 IM_UNUSED(g);
17796
17797 ImGuiWindow* payload_window = req->DockPayload; // Optional
17798 ImGuiWindow* target_window = req->DockTargetWindow;
17799 ImGuiDockNode* node = req->DockTargetNode;
17800 if (payload_window)
17801 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
17802 else
17803 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
17804
17805 // Decide which Tab will be selected at the end of the operation
17806 ImGuiID next_selected_id = 0;
17807 ImGuiDockNode* payload_node = NULL;
17808 if (payload_window)
17809 {
17810 payload_node = payload_window->DockNodeAsHost;
17811 payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
17812 if (payload_node && payload_node->IsLeafNode())
17813 next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
17814 if (payload_node == NULL)
17815 next_selected_id = payload_window->TabId;
17816 }
17817
17818 // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
17819 // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
17820 if (node)
17821 IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
17822 if (node && target_window && node == target_window->DockNodeAsHost)
17823 IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
17824
17825 // Create new node and add existing window to it
17826 if (node == NULL)
17827 {
17828 node = DockContextAddNode(ctx, id: 0);
17829 node->Pos = target_window->Pos;
17830 node->Size = target_window->Size;
17831 if (target_window->DockNodeAsHost == NULL)
17832 {
17833 DockNodeAddWindow(node, window: target_window, add_to_tab_bar: true);
17834 node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
17835 target_window->DockIsActive = true;
17836 }
17837 }
17838
17839 ImGuiDir split_dir = req->DockSplitDir;
17840 if (split_dir != ImGuiDir_None)
17841 {
17842 // Split into two, one side will be our payload node unless we are dropping a loose window
17843 const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17844 const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
17845 const float split_ratio = req->DockSplitRatio;
17846 DockNodeTreeSplit(ctx, parent_node: node, split_axis, split_first_child: split_inheritor_child_idx, split_ratio, new_node: payload_node); // payload_node may be NULL here!
17847 ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
17848 new_node->HostWindow = node->HostWindow;
17849 node = new_node;
17850 }
17851 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17852
17853 if (node != payload_node)
17854 {
17855 // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
17856 if (node->Windows.Size > 0 && node->TabBar == NULL)
17857 {
17858 DockNodeAddTabBar(node);
17859 for (int n = 0; n < node->Windows.Size; n++)
17860 TabBarAddTab(tab_bar: node->TabBar, tab_flags: ImGuiTabItemFlags_None, window: node->Windows[n]);
17861 }
17862
17863 if (payload_node != NULL)
17864 {
17865 // Transfer full payload node (with 1+ child windows or child nodes)
17866 if (payload_node->IsSplitNode())
17867 {
17868 if (node->Windows.Size > 0)
17869 {
17870 // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
17871 // In this situation, we move the windows of the target node into the currently visible node of the payload.
17872 // This allows us to preserve some of the underlying dock tree settings nicely.
17873 IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
17874 ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
17875 if (visible_node->TabBar)
17876 IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
17877 DockNodeMoveWindows(dst_node: node, src_node: visible_node);
17878 DockNodeMoveWindows(dst_node: visible_node, src_node: node);
17879 DockSettingsRenameNodeReferences(old_node_id: node->ID, new_node_id: visible_node->ID);
17880 }
17881 if (node->IsCentralNode())
17882 {
17883 // Central node property needs to be moved to a leaf node, pick the last focused one.
17884 // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
17885 ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, id: payload_node->LastFocusedNodeId);
17886 IM_ASSERT(last_focused_node != NULL);
17887 ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(node: last_focused_node);
17888 IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
17889 last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17890 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
17891 last_focused_root_node->CentralNode = last_focused_node;
17892 }
17893
17894 IM_ASSERT(node->Windows.Size == 0);
17895 DockNodeMoveChildNodes(dst_node: node, src_node: payload_node);
17896 }
17897 else
17898 {
17899 const ImGuiID payload_dock_id = payload_node->ID;
17900 DockNodeMoveWindows(dst_node: node, src_node: payload_node);
17901 DockSettingsRenameNodeReferences(old_node_id: payload_dock_id, new_node_id: node->ID);
17902 }
17903 DockContextRemoveNode(ctx, node: payload_node, merge_sibling_into_parent_node: true);
17904 }
17905 else if (payload_window)
17906 {
17907 // Transfer single window
17908 const ImGuiID payload_dock_id = payload_window->DockId;
17909 node->VisibleWindow = payload_window;
17910 DockNodeAddWindow(node, window: payload_window, add_to_tab_bar: true);
17911 if (payload_dock_id != 0)
17912 DockSettingsRenameNodeReferences(old_node_id: payload_dock_id, new_node_id: node->ID);
17913 }
17914 }
17915 else
17916 {
17917 // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
17918 node->WantHiddenTabBarUpdate = true;
17919 }
17920
17921 // Update selection immediately
17922 if (ImGuiTabBar* tab_bar = node->TabBar)
17923 tab_bar->NextSelectedTabId = next_selected_id;
17924 MarkIniSettingsDirty();
17925}
17926
17927// Problem:
17928// Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
17929// than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
17930// with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
17931// due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
17932// Solution:
17933// When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
17934// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
17935static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
17936{
17937 if (ref_viewport == NULL)
17938 return size;
17939
17940 ImGuiContext& g = *GImGui;
17941 ImVec2 max_size = ImTrunc(v: ref_viewport->WorkSize * 0.90f);
17942 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
17943 {
17944 const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(viewport_p: ref_viewport);
17945 max_size = ImTrunc(v: monitor->WorkSize * 0.90f);
17946 }
17947 return ImMin(lhs: size, rhs: max_size);
17948}
17949
17950void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
17951{
17952 ImGuiContext& g = *ctx;
17953 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
17954 if (window->DockNode)
17955 DockNodeRemoveWindow(node: window->DockNode, window, save_dock_id: clear_persistent_docking_ref ? 0 : window->DockId);
17956 else
17957 window->DockId = 0;
17958 window->Collapsed = false;
17959 window->DockIsActive = false;
17960 window->DockNodeIsVisible = window->DockTabIsVisible = false;
17961 window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(size: window->SizeFull, ref_viewport: window->Viewport);
17962
17963 MarkIniSettingsDirty();
17964}
17965
17966void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
17967{
17968 ImGuiContext& g = *ctx;
17969 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
17970 IM_ASSERT(node->IsLeafNode());
17971 IM_ASSERT(node->Windows.Size >= 1);
17972
17973 if (node->IsRootNode() || node->IsCentralNode())
17974 {
17975 // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
17976 ImGuiDockNode* new_node = DockContextAddNode(ctx, id: 0);
17977 new_node->Pos = node->Pos;
17978 new_node->Size = node->Size;
17979 new_node->SizeRef = node->SizeRef;
17980 DockNodeMoveWindows(dst_node: new_node, src_node: node);
17981 DockSettingsRenameNodeReferences(old_node_id: node->ID, new_node_id: new_node->ID);
17982 node = new_node;
17983 }
17984 else
17985 {
17986 // Otherwise extract our node and merge our sibling back into the parent node.
17987 IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
17988 int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
17989 node->ParentNode->ChildNodes[index_in_parent] = NULL;
17990 DockNodeTreeMerge(ctx, parent_node: node->ParentNode, merge_lead_child: node->ParentNode->ChildNodes[index_in_parent ^ 1]);
17991 node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
17992 node->ParentNode = NULL;
17993 }
17994 for (ImGuiWindow* window : node->Windows)
17995 {
17996 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
17997 if (window->ParentWindow)
17998 window->ParentWindow->DC.ChildWindows.find_erase(v: window);
17999 UpdateWindowParentAndRootLinks(window, flags: window->Flags, NULL);
18000 }
18001 node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18002 node->Size = FixLargeWindowsWhenUndocking(size: node->Size, ref_viewport: node->Windows[0]->Viewport);
18003 node->WantMouseMove = true;
18004 MarkIniSettingsDirty();
18005}
18006
18007// This is mostly used for automation.
18008bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
18009{
18010 if (target != NULL && target_node == NULL)
18011 target_node = target->DockNode;
18012
18013 // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
18014 // (which would be functionally identical) we only show the outer one. Reflect this here.
18015 if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
18016 split_outer = true;
18017 ImGuiDockPreviewData split_data;
18018 DockNodePreviewDockSetup(host_window: target, host_node: target_node, payload_window, payload_node, preview_data: &split_data, is_explicit_target: false, is_outer_docking: split_outer);
18019 if (split_data.DropRectsDraw[split_dir+1].IsInverted())
18020 return false;
18021 *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
18022 return true;
18023}
18024
18025//-----------------------------------------------------------------------------
18026// Docking: ImGuiDockNode
18027//-----------------------------------------------------------------------------
18028// - DockNodeGetTabOrder()
18029// - DockNodeAddWindow()
18030// - DockNodeRemoveWindow()
18031// - DockNodeMoveChildNodes()
18032// - DockNodeMoveWindows()
18033// - DockNodeApplyPosSizeToWindows()
18034// - DockNodeHideHostWindow()
18035// - ImGuiDockNodeFindInfoResults
18036// - DockNodeFindInfo()
18037// - DockNodeFindWindowByID()
18038// - DockNodeUpdateFlagsAndCollapse()
18039// - DockNodeUpdateHasCentralNodeFlag()
18040// - DockNodeUpdateVisibleFlag()
18041// - DockNodeStartMouseMovingWindow()
18042// - DockNodeUpdate()
18043// - DockNodeUpdateWindowMenu()
18044// - DockNodeBeginAmendTabBar()
18045// - DockNodeEndAmendTabBar()
18046// - DockNodeUpdateTabBar()
18047// - DockNodeAddTabBar()
18048// - DockNodeRemoveTabBar()
18049// - DockNodeIsDropAllowedOne()
18050// - DockNodeIsDropAllowed()
18051// - DockNodeCalcTabBarLayout()
18052// - DockNodeCalcSplitRects()
18053// - DockNodeCalcDropRectsAndTestMousePos()
18054// - DockNodePreviewDockSetup()
18055// - DockNodePreviewDockRender()
18056//-----------------------------------------------------------------------------
18057
18058ImGuiDockNode::ImGuiDockNode(ImGuiID id)
18059{
18060 ID = id;
18061 SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
18062 ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
18063 TabBar = NULL;
18064 SplitAxis = ImGuiAxis_None;
18065
18066 State = ImGuiDockNodeState_Unknown;
18067 LastBgColor = IM_COL32_WHITE;
18068 HostWindow = VisibleWindow = NULL;
18069 CentralNode = OnlyNodeWithWindows = NULL;
18070 CountNodeWithWindows = 0;
18071 LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
18072 LastFocusedNodeId = 0;
18073 SelectedTabId = 0;
18074 WantCloseTabId = 0;
18075 RefViewportId = 0;
18076 AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
18077 AuthorityForViewport = ImGuiDataAuthority_Auto;
18078 IsVisible = true;
18079 IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
18080 IsBgDrawnThisFrame = false;
18081 WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
18082}
18083
18084ImGuiDockNode::~ImGuiDockNode()
18085{
18086 IM_DELETE(p: TabBar);
18087 TabBar = NULL;
18088 ChildNodes[0] = ChildNodes[1] = NULL;
18089}
18090
18091int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
18092{
18093 ImGuiTabBar* tab_bar = window->DockNode->TabBar;
18094 if (tab_bar == NULL)
18095 return -1;
18096 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id: window->TabId);
18097 return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
18098}
18099
18100static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
18101{
18102 window->Hidden = true;
18103 window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
18104}
18105
18106static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
18107{
18108 ImGuiContext& g = *GImGui; (void)g;
18109 if (window->DockNode)
18110 {
18111 // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
18112 IM_ASSERT(window->DockNode->ID != node->ID);
18113 DockNodeRemoveWindow(node: window->DockNode, window, save_dock_id: 0);
18114 }
18115 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
18116 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
18117
18118 // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
18119 // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
18120 // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
18121 if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
18122 DockNodeHideWindowDuringHostWindowCreation(window: node->Windows[0]);
18123
18124 node->Windows.push_back(v: window);
18125 node->WantHiddenTabBarUpdate = true;
18126 window->DockNode = node;
18127 window->DockId = node->ID;
18128 window->DockIsActive = (node->Windows.Size > 1);
18129 window->DockTabWantClose = false;
18130
18131 // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
18132 // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
18133 if (node->HostWindow == NULL && node->IsFloatingNode())
18134 {
18135 if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
18136 node->AuthorityForPos = ImGuiDataAuthority_Window;
18137 if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
18138 node->AuthorityForSize = ImGuiDataAuthority_Window;
18139 if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
18140 node->AuthorityForViewport = ImGuiDataAuthority_Window;
18141 }
18142
18143 // Add to tab bar if requested
18144 if (add_to_tab_bar)
18145 {
18146 if (node->TabBar == NULL)
18147 {
18148 DockNodeAddTabBar(node);
18149 node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
18150
18151 // Add existing windows
18152 for (int n = 0; n < node->Windows.Size - 1; n++)
18153 TabBarAddTab(tab_bar: node->TabBar, tab_flags: ImGuiTabItemFlags_None, window: node->Windows[n]);
18154 }
18155 TabBarAddTab(tab_bar: node->TabBar, tab_flags: ImGuiTabItemFlags_Unsorted, window);
18156 }
18157
18158 DockNodeUpdateVisibleFlag(node);
18159
18160 // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
18161 if (node->HostWindow)
18162 UpdateWindowParentAndRootLinks(window, flags: window->Flags | ImGuiWindowFlags_ChildWindow, parent_window: node->HostWindow);
18163}
18164
18165static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
18166{
18167 ImGuiContext& g = *GImGui;
18168 IM_ASSERT(window->DockNode == node);
18169 //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
18170 //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
18171 IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
18172 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
18173
18174 window->DockNode = NULL;
18175 window->DockIsActive = window->DockTabWantClose = false;
18176 window->DockId = save_dock_id;
18177 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
18178 if (window->ParentWindow)
18179 window->ParentWindow->DC.ChildWindows.find_erase(v: window);
18180 UpdateWindowParentAndRootLinks(window, flags: window->Flags, NULL); // Update immediately
18181
18182 if (node->HostWindow && node->HostWindow->ViewportOwned)
18183 {
18184 // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
18185 // But mid-frame, if we clear viewport we need to mark window as hidden as well.
18186 window->Viewport = NULL;
18187 window->ViewportId = 0;
18188 window->ViewportOwned = false;
18189 window->Hidden = true;
18190 }
18191
18192 // Remove window
18193 bool erased = false;
18194 for (int n = 0; n < node->Windows.Size; n++)
18195 if (node->Windows[n] == window)
18196 {
18197 node->Windows.erase(it: node->Windows.Data + n);
18198 erased = true;
18199 break;
18200 }
18201 if (!erased)
18202 IM_ASSERT(erased);
18203 if (node->VisibleWindow == window)
18204 node->VisibleWindow = NULL;
18205
18206 // Remove tab and possibly tab bar
18207 node->WantHiddenTabBarUpdate = true;
18208 if (node->TabBar)
18209 {
18210 TabBarRemoveTab(tab_bar: node->TabBar, tab_id: window->TabId);
18211 const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
18212 if (node->Windows.Size < tab_count_threshold_for_tab_bar)
18213 DockNodeRemoveTabBar(node);
18214 }
18215
18216 if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
18217 {
18218 // Automatic dock node delete themselves if they are not holding at least one tab
18219 DockContextRemoveNode(ctx: &g, node, merge_sibling_into_parent_node: true);
18220 return;
18221 }
18222
18223 if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
18224 {
18225 ImGuiWindow* remaining_window = node->Windows[0];
18226 // Note: we used to transport viewport ownership here.
18227 remaining_window->Collapsed = node->HostWindow->Collapsed;
18228 }
18229
18230 // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
18231 DockNodeUpdateVisibleFlag(node);
18232}
18233
18234static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
18235{
18236 IM_ASSERT(dst_node->Windows.Size == 0);
18237 dst_node->ChildNodes[0] = src_node->ChildNodes[0];
18238 dst_node->ChildNodes[1] = src_node->ChildNodes[1];
18239 if (dst_node->ChildNodes[0])
18240 dst_node->ChildNodes[0]->ParentNode = dst_node;
18241 if (dst_node->ChildNodes[1])
18242 dst_node->ChildNodes[1]->ParentNode = dst_node;
18243 dst_node->SplitAxis = src_node->SplitAxis;
18244 dst_node->SizeRef = src_node->SizeRef;
18245 src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
18246}
18247
18248static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
18249{
18250 // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
18251 IM_ASSERT(src_node && dst_node && dst_node != src_node);
18252 ImGuiTabBar* src_tab_bar = src_node->TabBar;
18253 if (src_tab_bar != NULL)
18254 IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
18255
18256 // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
18257 bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
18258 if (move_tab_bar)
18259 {
18260 dst_node->TabBar = src_node->TabBar;
18261 src_node->TabBar = NULL;
18262 }
18263
18264 // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
18265 for (ImGuiWindow* window : src_node->Windows)
18266 {
18267 window->DockNode = NULL;
18268 window->DockIsActive = false;
18269 DockNodeAddWindow(node: dst_node, window, add_to_tab_bar: !move_tab_bar);
18270 }
18271 src_node->Windows.clear();
18272
18273 if (!move_tab_bar && src_node->TabBar)
18274 {
18275 if (dst_node->TabBar)
18276 dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
18277 DockNodeRemoveTabBar(node: src_node);
18278 }
18279}
18280
18281static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
18282{
18283 for (ImGuiWindow* window : node->Windows)
18284 {
18285 SetWindowPos(window, pos: node->Pos, cond: ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
18286 SetWindowSize(window, size: node->Size, cond: ImGuiCond_Always);
18287 }
18288}
18289
18290static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
18291{
18292 if (node->HostWindow)
18293 {
18294 if (node->HostWindow->DockNodeAsHost == node)
18295 node->HostWindow->DockNodeAsHost = NULL;
18296 node->HostWindow = NULL;
18297 }
18298
18299 if (node->Windows.Size == 1)
18300 {
18301 node->VisibleWindow = node->Windows[0];
18302 node->Windows[0]->DockIsActive = false;
18303 }
18304
18305 if (node->TabBar)
18306 DockNodeRemoveTabBar(node);
18307}
18308
18309// Search function called once by root node in DockNodeUpdate()
18310struct ImGuiDockNodeTreeInfo
18311{
18312 ImGuiDockNode* CentralNode;
18313 ImGuiDockNode* FirstNodeWithWindows;
18314 int CountNodesWithWindows;
18315 //ImGuiWindowClass WindowClassForMerges;
18316
18317 ImGuiDockNodeTreeInfo() { memset(s: this, c: 0, n: sizeof(*this)); }
18318};
18319
18320static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
18321{
18322 if (node->Windows.Size > 0)
18323 {
18324 if (info->FirstNodeWithWindows == NULL)
18325 info->FirstNodeWithWindows = node;
18326 info->CountNodesWithWindows++;
18327 }
18328 if (node->IsCentralNode())
18329 {
18330 IM_ASSERT(info->CentralNode == NULL); // Should be only one
18331 IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
18332 info->CentralNode = node;
18333 }
18334 if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
18335 return;
18336 if (node->ChildNodes[0])
18337 DockNodeFindInfo(node: node->ChildNodes[0], info);
18338 if (node->ChildNodes[1])
18339 DockNodeFindInfo(node: node->ChildNodes[1], info);
18340}
18341
18342static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
18343{
18344 IM_ASSERT(id != 0);
18345 for (ImGuiWindow* window : node->Windows)
18346 if (window->ID == id)
18347 return window;
18348 return NULL;
18349}
18350
18351// - Remove inactive windows/nodes.
18352// - Update visibility flag.
18353static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
18354{
18355 ImGuiContext& g = *GImGui;
18356 IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
18357
18358 // Inherit most flags
18359 if (node->ParentNode)
18360 node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18361
18362 // Recurse into children
18363 // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
18364 // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
18365 // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
18366 node->HasCentralNodeChild = false;
18367 if (node->ChildNodes[0])
18368 DockNodeUpdateFlagsAndCollapse(node: node->ChildNodes[0]);
18369 if (node->ChildNodes[1])
18370 DockNodeUpdateFlagsAndCollapse(node: node->ChildNodes[1]);
18371
18372 // Remove inactive windows, collapse nodes
18373 // Merge node flags overrides stored in windows
18374 node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18375 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18376 {
18377 ImGuiWindow* window = node->Windows[window_n];
18378 IM_ASSERT(window->DockNode == node);
18379
18380 bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
18381 bool remove = false;
18382 remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
18383 remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
18384 remove |= (window->DockTabWantClose);
18385 if (remove)
18386 {
18387 window->DockTabWantClose = false;
18388 if (node->Windows.Size == 1 && !node->IsCentralNode())
18389 {
18390 DockNodeHideHostWindow(node);
18391 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
18392 DockNodeRemoveWindow(node, window, save_dock_id: node->ID); // Will delete the node so it'll be invalid on return
18393 return;
18394 }
18395 DockNodeRemoveWindow(node, window, save_dock_id: node->ID);
18396 window_n--;
18397 continue;
18398 }
18399
18400 // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
18401 //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
18402 node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
18403 }
18404 node->UpdateMergedFlags();
18405
18406 // Auto-hide tab bar option
18407 ImGuiDockNodeFlags node_flags = node->MergedFlags;
18408 if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
18409 node->WantHiddenTabBarToggle = true;
18410 node->WantHiddenTabBarUpdate = false;
18411
18412 // Cancel toggling if we know our tab bar is enforced to be hidden at all times
18413 if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
18414 node->WantHiddenTabBarToggle = false;
18415
18416 // Apply toggles at a single point of the frame (here!)
18417 if (node->Windows.Size > 1)
18418 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
18419 else if (node->WantHiddenTabBarToggle)
18420 node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
18421 node->WantHiddenTabBarToggle = false;
18422
18423 DockNodeUpdateVisibleFlag(node);
18424}
18425
18426// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
18427static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
18428{
18429 node->HasCentralNodeChild = false;
18430 if (node->ChildNodes[0])
18431 DockNodeUpdateHasCentralNodeChild(node: node->ChildNodes[0]);
18432 if (node->ChildNodes[1])
18433 DockNodeUpdateHasCentralNodeChild(node: node->ChildNodes[1]);
18434 if (node->IsRootNode())
18435 {
18436 ImGuiDockNode* mark_node = node->CentralNode;
18437 while (mark_node)
18438 {
18439 mark_node->HasCentralNodeChild = true;
18440 mark_node = mark_node->ParentNode;
18441 }
18442 }
18443}
18444
18445static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
18446{
18447 // Update visibility flag
18448 bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
18449 is_visible |= (node->Windows.Size > 0);
18450 is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
18451 is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
18452 node->IsVisible = is_visible;
18453}
18454
18455static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
18456{
18457 ImGuiContext& g = *GImGui;
18458 IM_ASSERT(node->WantMouseMove == true);
18459 StartMouseMovingWindow(window);
18460 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
18461 g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
18462 node->WantMouseMove = false;
18463}
18464
18465// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
18466static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
18467{
18468 DockNodeUpdateFlagsAndCollapse(node);
18469
18470 // - Setup central node pointers
18471 // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
18472 // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
18473 ImGuiDockNodeTreeInfo info;
18474 DockNodeFindInfo(node, info: &info);
18475 node->CentralNode = info.CentralNode;
18476 node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
18477 node->CountNodeWithWindows = info.CountNodesWithWindows;
18478 if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
18479 node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
18480
18481 // Copy the window class from of our first window so it can be used for proper dock filtering.
18482 // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
18483 // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
18484 if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
18485 {
18486 node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
18487 for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
18488 if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
18489 {
18490 node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
18491 break;
18492 }
18493 }
18494
18495 ImGuiDockNode* mark_node = node->CentralNode;
18496 while (mark_node)
18497 {
18498 mark_node->HasCentralNodeChild = true;
18499 mark_node = mark_node->ParentNode;
18500 }
18501}
18502
18503static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
18504{
18505 // Remove ourselves from any previous different host window
18506 // This can happen if a user mistakenly does (see #4295 for details):
18507 // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace
18508 // - N+1: NewFrame() // will create floating host window for that node
18509 // - N+1: DockSpace(id) // requalify node as dockspace, moving host window
18510 if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
18511 node->HostWindow->DockNodeAsHost = NULL;
18512
18513 host_window->DockNodeAsHost = node;
18514 node->HostWindow = host_window;
18515}
18516
18517static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
18518{
18519 ImGuiContext& g = *GImGui;
18520 IM_ASSERT(node->LastFrameActive != g.FrameCount);
18521 node->LastFrameAlive = g.FrameCount;
18522 node->IsBgDrawnThisFrame = false;
18523
18524 node->CentralNode = node->OnlyNodeWithWindows = NULL;
18525 if (node->IsRootNode())
18526 DockNodeUpdateForRootNode(node);
18527
18528 // Remove tab bar if not needed
18529 if (node->TabBar && node->IsNoTabBar())
18530 DockNodeRemoveTabBar(node);
18531
18532 // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
18533 bool want_to_hide_host_window = false;
18534 if (node->IsFloatingNode())
18535 {
18536 if (node->Windows.Size <= 1 && node->IsLeafNode())
18537 if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
18538 want_to_hide_host_window = true;
18539 if (node->CountNodeWithWindows == 0)
18540 want_to_hide_host_window = true;
18541 }
18542 if (want_to_hide_host_window)
18543 {
18544 if (node->Windows.Size == 1)
18545 {
18546 // Floating window pos/size is authoritative
18547 ImGuiWindow* single_window = node->Windows[0];
18548 node->Pos = single_window->Pos;
18549 node->Size = single_window->SizeFull;
18550 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18551
18552 // Transfer focus immediately so when we revert to a regular window it is immediately selected
18553 if (node->HostWindow && g.NavWindow == node->HostWindow)
18554 FocusWindow(window: single_window);
18555 if (node->HostWindow)
18556 {
18557 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
18558 single_window->Viewport = node->HostWindow->Viewport;
18559 single_window->ViewportId = node->HostWindow->ViewportId;
18560 if (node->HostWindow->ViewportOwned)
18561 {
18562 single_window->Viewport->ID = single_window->ID;
18563 single_window->Viewport->Window = single_window;
18564 single_window->ViewportOwned = true;
18565 }
18566 }
18567 node->RefViewportId = single_window->ViewportId;
18568 }
18569
18570 DockNodeHideHostWindow(node);
18571 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
18572 node->WantCloseAll = false;
18573 node->WantCloseTabId = 0;
18574 node->HasCloseButton = node->HasWindowMenuButton = false;
18575 node->LastFrameActive = g.FrameCount;
18576
18577 if (node->WantMouseMove && node->Windows.Size == 1)
18578 DockNodeStartMouseMovingWindow(node, window: node->Windows[0]);
18579 return;
18580 }
18581
18582 // In some circumstance we will defer creating the host window (so everything will be kept hidden),
18583 // while the expected visible window is resizing itself.
18584 // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
18585 // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
18586 // N+0: Begin(): window created (with no known size), node is created
18587 // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
18588 // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
18589 // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
18590 // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
18591 // In reality it isn't very important as user quickly ends up with size data in .ini file.
18592 if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
18593 {
18594 IM_ASSERT(node->Windows.Size > 0);
18595 ImGuiWindow* ref_window = NULL;
18596 if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
18597 ref_window = DockNodeFindWindowByID(node, id: node->SelectedTabId);
18598 if (ref_window == NULL)
18599 ref_window = node->Windows[0];
18600 if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
18601 {
18602 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
18603 return;
18604 }
18605 }
18606
18607 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
18608
18609 // Decide if the node will have a close button and a window menu button
18610 node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
18611 node->HasCloseButton = false;
18612 for (ImGuiWindow* window : node->Windows)
18613 {
18614 // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
18615 node->HasCloseButton |= window->HasCloseButton;
18616 window->DockIsActive = (node->Windows.Size > 1);
18617 }
18618 if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
18619 node->HasCloseButton = false;
18620
18621 // Bind or create host window
18622 ImGuiWindow* host_window = NULL;
18623 bool beginned_into_host_window = false;
18624 if (node->IsDockSpace())
18625 {
18626 // [Explicit root dockspace node]
18627 IM_ASSERT(node->HostWindow);
18628 host_window = node->HostWindow;
18629 }
18630 else
18631 {
18632 // [Automatic root or child nodes]
18633 if (node->IsRootNode() && node->IsVisible)
18634 {
18635 ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
18636
18637 // Sync Pos
18638 if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
18639 SetNextWindowPos(pos: ref_window->Pos);
18640 else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
18641 SetNextWindowPos(pos: node->Pos);
18642
18643 // Sync Size
18644 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
18645 SetNextWindowSize(size: ref_window->SizeFull);
18646 else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
18647 SetNextWindowSize(size: node->Size);
18648
18649 // Sync Collapsed
18650 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
18651 SetNextWindowCollapsed(collapsed: ref_window->Collapsed);
18652
18653 // Sync Viewport
18654 if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
18655 SetNextWindowViewport(ref_window->ViewportId);
18656 else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
18657 SetNextWindowViewport(node->RefViewportId);
18658
18659 SetNextWindowClass(&node->WindowClass);
18660
18661 // Begin into the host window
18662 char window_label[20];
18663 DockNodeGetHostWindowTitle(node, buf: window_label, IM_ARRAYSIZE(window_label));
18664 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
18665 window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
18666 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
18667 window_flags |= ImGuiWindowFlags_NoTitleBar;
18668
18669 SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
18670 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: ImVec2(0, 0));
18671 Begin(name: window_label, NULL, flags: window_flags);
18672 PopStyleVar();
18673 beginned_into_host_window = true;
18674
18675 host_window = g.CurrentWindow;
18676 DockNodeSetupHostWindow(node, host_window);
18677 host_window->DC.CursorPos = host_window->Pos;
18678 node->Pos = host_window->Pos;
18679 node->Size = host_window->Size;
18680
18681 // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
18682 // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
18683 // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
18684 // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
18685 // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
18686 // after the dock host window, losing their top-most status.
18687 if (node->HostWindow->Appearing)
18688 BringWindowToDisplayFront(window: node->HostWindow);
18689
18690 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18691 }
18692 else if (node->ParentNode)
18693 {
18694 node->HostWindow = host_window = node->ParentNode->HostWindow;
18695 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18696 }
18697 if (node->WantMouseMove && node->HostWindow)
18698 DockNodeStartMouseMovingWindow(node, window: node->HostWindow);
18699 }
18700 node->RefViewportId = 0; // Clear when we have a host window
18701
18702 // Update focused node (the one whose title bar is highlight) within a node tree
18703 if (node->IsSplitNode())
18704 IM_ASSERT(node->TabBar == NULL);
18705 if (node->IsRootNode())
18706 if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
18707 while (p_window != NULL && p_window->DockNode != NULL)
18708 {
18709 ImGuiDockNode* p_node = DockNodeGetRootNode(node: p_window->DockNode);
18710 if (p_node == node)
18711 {
18712 node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
18713 break;
18714 }
18715 p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
18716 }
18717
18718 // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
18719 ImGuiDockNode* central_node = node->CentralNode;
18720 const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
18721 bool central_node_hole_register_hit_test_hole = central_node_hole;
18722 if (central_node_hole)
18723 if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
18724 if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, payload_window: *(ImGuiWindow**)payload->Data))
18725 central_node_hole_register_hit_test_hole = false;
18726 if (central_node_hole_register_hit_test_hole)
18727 {
18728 // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
18729 // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
18730 // covering passthru node we'd have a gap on the edge not covered by the hole)
18731 IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
18732 ImGuiDockNode* root_node = DockNodeGetRootNode(node: central_node);
18733 ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
18734 ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
18735 if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += g.WindowsBorderHoverPadding; }
18736 if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= g.WindowsBorderHoverPadding; }
18737 if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += g.WindowsBorderHoverPadding; }
18738 if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= g.WindowsBorderHoverPadding; }
18739 //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
18740 if (central_node_hole && !hole_rect.IsInverted())
18741 {
18742 SetWindowHitTestHole(window: host_window, pos: hole_rect.Min, size: hole_rect.Max - hole_rect.Min);
18743 if (host_window->ParentWindow)
18744 SetWindowHitTestHole(window: host_window->ParentWindow, pos: hole_rect.Min, size: hole_rect.Max - hole_rect.Min);
18745 }
18746 }
18747
18748 // Update position/size, process and draw resizing splitters
18749 if (node->IsRootNode() && host_window)
18750 {
18751 DockNodeTreeUpdatePosSize(node, pos: host_window->Pos, size: host_window->Size);
18752 PushStyleColor(idx: ImGuiCol_Separator, col: g.Style.Colors[ImGuiCol_Border]);
18753 PushStyleColor(idx: ImGuiCol_SeparatorActive, col: g.Style.Colors[ImGuiCol_ResizeGripActive]);
18754 PushStyleColor(idx: ImGuiCol_SeparatorHovered, col: g.Style.Colors[ImGuiCol_ResizeGripHovered]);
18755 DockNodeTreeUpdateSplitter(node);
18756 PopStyleColor(count: 3);
18757 }
18758
18759 // Draw empty node background (currently can only be the Central Node)
18760 if (host_window && node->IsEmpty() && node->IsVisible)
18761 {
18762 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
18763 node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(idx: ImGuiCol_DockingEmptyBg);
18764 if (node->LastBgColor != 0)
18765 host_window->DrawList->AddRectFilled(p_min: node->Pos, p_max: node->Pos + node->Size, col: node->LastBgColor);
18766 node->IsBgDrawnThisFrame = true;
18767 }
18768
18769 // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
18770 // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
18771 // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
18772 const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
18773 if (render_dockspace_bg && node->IsVisible)
18774 {
18775 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
18776 if (central_node_hole)
18777 RenderRectFilledWithHole(draw_list: host_window->DrawList, outer: node->Rect(), inner: central_node->Rect(), col: GetColorU32(idx: ImGuiCol_WindowBg), rounding: 0.0f);
18778 else
18779 host_window->DrawList->AddRectFilled(p_min: node->Pos, p_max: node->Pos + node->Size, col: GetColorU32(idx: ImGuiCol_WindowBg), rounding: 0.0f);
18780 }
18781
18782 // Draw and populate Tab Bar
18783 if (host_window)
18784 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
18785 if (host_window && node->Windows.Size > 0)
18786 {
18787 DockNodeUpdateTabBar(node, host_window);
18788 }
18789 else
18790 {
18791 node->WantCloseAll = false;
18792 node->WantCloseTabId = 0;
18793 node->IsFocused = false;
18794 }
18795 if (node->TabBar && node->TabBar->SelectedTabId)
18796 node->SelectedTabId = node->TabBar->SelectedTabId;
18797 else if (node->Windows.Size > 0)
18798 node->SelectedTabId = node->Windows[0]->TabId;
18799
18800 // Draw payload drop target
18801 if (host_window && node->IsVisible)
18802 if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
18803 BeginDockableDragDropTarget(window: host_window);
18804
18805 // We update this after DockNodeUpdateTabBar()
18806 node->LastFrameActive = g.FrameCount;
18807
18808 // Recurse into children
18809 // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
18810 if (host_window)
18811 {
18812 if (node->ChildNodes[0])
18813 DockNodeUpdate(node: node->ChildNodes[0]);
18814 if (node->ChildNodes[1])
18815 DockNodeUpdate(node: node->ChildNodes[1]);
18816
18817 // Render outer borders last (after the tab bar)
18818 if (node->IsRootNode())
18819 RenderWindowOuterBorders(window: host_window);
18820 }
18821
18822 // End host window
18823 if (beginned_into_host_window) //-V1020
18824 End();
18825}
18826
18827// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
18828static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
18829{
18830 ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
18831 ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
18832 if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
18833 return d;
18834 return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
18835}
18836
18837// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
18838// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
18839// Custom overrides may want to decorate, group, sort entries.
18840// Please note those are internal structures: if you copy this expect occasional breakage.
18841// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
18842void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
18843{
18844 IM_UNUSED(ctx);
18845 if (tab_bar->Tabs.Size == 1)
18846 {
18847 // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
18848 if (MenuItem(label: LocalizeGetMsg(key: ImGuiLocKey_DockingHideTabBar), NULL, selected: node->IsHiddenTabBar()))
18849 node->WantHiddenTabBarToggle = true;
18850 }
18851 else
18852 {
18853 // Display a selectable list of windows in this docking node
18854 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
18855 {
18856 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
18857 if (tab->Flags & ImGuiTabItemFlags_Button)
18858 continue;
18859 if (Selectable(label: TabBarGetTabName(tab_bar, tab), selected: tab->ID == tab_bar->SelectedTabId))
18860 TabBarQueueFocus(tab_bar, tab);
18861 SameLine();
18862 Text(fmt: " ");
18863 }
18864 }
18865}
18866
18867static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
18868{
18869 // Try to position the menu so it is more likely to stays within the same viewport
18870 ImGuiContext& g = *GImGui;
18871 if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
18872 SetNextWindowPos(pos: ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), cond: ImGuiCond_Always, pivot: ImVec2(0.0f, 0.0f));
18873 else
18874 SetNextWindowPos(pos: ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), cond: ImGuiCond_Always, pivot: ImVec2(1.0f, 0.0f));
18875 if (BeginPopup(str_id: "#WindowMenu"))
18876 {
18877 node->IsFocused = true;
18878 g.DockNodeWindowMenuHandler(&g, node, tab_bar);
18879 EndPopup();
18880 }
18881}
18882
18883// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
18884bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
18885{
18886 if (node->TabBar == NULL || node->HostWindow == NULL)
18887 return false;
18888 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18889 return false;
18890 if (node->TabBar->ID == 0)
18891 return false;
18892 Begin(name: node->HostWindow->Name);
18893 PushOverrideID(id: node->ID);
18894 bool ret = BeginTabBarEx(tab_bar: node->TabBar, bb: node->TabBar->BarRect, flags: node->TabBar->Flags);
18895 IM_UNUSED(ret);
18896 IM_ASSERT(ret);
18897 return true;
18898}
18899
18900void ImGui::DockNodeEndAmendTabBar()
18901{
18902 EndTabBar();
18903 PopID();
18904 End();
18905}
18906
18907static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
18908{
18909 // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
18910 ImGuiContext& g = *GImGui;
18911 if (g.NavWindowingTarget)
18912 return (g.NavWindowingTarget->DockNode == node);
18913
18914 // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
18915 if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
18916 {
18917 // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
18918 ImGuiWindow* parent_window = g.NavWindow->RootWindow;
18919 while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
18920 parent_window = parent_window->ParentWindow->RootWindow;
18921 ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
18922 for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
18923 if ((parent_node = ImGui::DockNodeGetRootNode(node: parent_node)) == root_node)
18924 return true;
18925 }
18926 return false;
18927}
18928
18929// Submit the tab bar corresponding to a dock node and various housekeeping details.
18930static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
18931{
18932 ImGuiContext& g = *GImGui;
18933 ImGuiStyle& style = g.Style;
18934
18935 const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
18936 node->WantCloseAll = false;
18937 node->WantCloseTabId = 0;
18938
18939 // Decide if we should use a focused title bar color
18940 bool is_focused = false;
18941 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18942 if (IsDockNodeTitleBarHighlighted(node, root_node))
18943 is_focused = true;
18944
18945 // Hidden tab bar will show a triangle on the upper-left (in Begin)
18946 if (node->IsHiddenTabBar() || node->IsNoTabBar())
18947 {
18948 node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
18949 node->IsFocused = is_focused;
18950 if (is_focused)
18951 node->LastFrameFocused = g.FrameCount;
18952 if (node->VisibleWindow)
18953 {
18954 // Notify root of visible window (used to display title in OS task bar)
18955 if (is_focused || root_node->VisibleWindow == NULL)
18956 root_node->VisibleWindow = node->VisibleWindow;
18957 if (node->TabBar)
18958 node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
18959 }
18960 return;
18961 }
18962
18963 // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
18964 bool backup_skip_item = host_window->SkipItems;
18965 if (!node->IsDockSpace())
18966 {
18967 host_window->SkipItems = false;
18968 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
18969 }
18970
18971 // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
18972 // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
18973 // as docked windows themselves will override the stack with their own root ID.
18974 PushOverrideID(id: node->ID);
18975 ImGuiTabBar* tab_bar = node->TabBar;
18976 bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
18977 if (tab_bar == NULL)
18978 {
18979 DockNodeAddTabBar(node);
18980 tab_bar = node->TabBar;
18981 }
18982
18983 ImGuiID focus_tab_id = 0;
18984 node->IsFocused = is_focused;
18985
18986 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
18987 const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
18988
18989 // In a dock node, the Collapse Button turns into the Window Menu button.
18990 // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
18991 if (has_window_menu_button && IsPopupOpen(str_id: "#WindowMenu"))
18992 {
18993 ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
18994 DockNodeWindowMenuUpdate(node, tab_bar);
18995 if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
18996 focus_tab_id = tab_bar->NextSelectedTabId;
18997 is_focused |= node->IsFocused;
18998 }
18999
19000 // Layout
19001 ImRect title_bar_rect, tab_bar_rect;
19002 ImVec2 window_menu_button_pos;
19003 ImVec2 close_button_pos;
19004 DockNodeCalcTabBarLayout(node, out_title_rect: &title_bar_rect, out_tab_bar_rect: &tab_bar_rect, out_window_menu_button_pos: &window_menu_button_pos, out_close_button_pos: &close_button_pos);
19005
19006 // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
19007 const int tabs_count_old = tab_bar->Tabs.Size;
19008 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19009 {
19010 ImGuiWindow* window = node->Windows[window_n];
19011 if (TabBarFindTabByID(tab_bar, tab_id: window->TabId) == NULL)
19012 TabBarAddTab(tab_bar, tab_flags: ImGuiTabItemFlags_Unsorted, window);
19013 }
19014
19015 // Title bar
19016 if (is_focused)
19017 node->LastFrameFocused = g.FrameCount;
19018 ImU32 title_bar_col = GetColorU32(idx: host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
19019 ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(r_in: title_bar_rect, r_outer: host_window->Rect(), threshold: g.Style.DockingSeparatorSize);
19020 host_window->DrawList->AddRectFilled(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, col: title_bar_col, rounding: host_window->WindowRounding, flags: rounding_flags);
19021
19022 // Docking/Collapse button
19023 if (has_window_menu_button)
19024 {
19025 if (CollapseButton(id: host_window->GetID(str: "#COLLAPSE"), pos: window_menu_button_pos, dock_node: node)) // == DockNodeGetWindowMenuButtonId(node)
19026 OpenPopup(str_id: "#WindowMenu");
19027 if (IsItemActive())
19028 focus_tab_id = tab_bar->SelectedTabId;
19029 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
19030 SetTooltip("%s", LocalizeGetMsg(key: ImGuiLocKey_DockingDragToUndockOrMoveNode));
19031 }
19032
19033 // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
19034 int tabs_unsorted_start = tab_bar->Tabs.Size;
19035 for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
19036 {
19037 // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
19038 tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
19039 tabs_unsorted_start = tab_n;
19040 }
19041 if (tab_bar->Tabs.Size > tabs_unsorted_start)
19042 {
19043 IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
19044 for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
19045 {
19046 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19047 IM_UNUSED(tab);
19048 IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
19049 }
19050 IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
19051 if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
19052 ImQsort(base: tab_bar->Tabs.Data + tabs_unsorted_start, count: tab_bar->Tabs.Size - tabs_unsorted_start, size_of_element: sizeof(ImGuiTabItem), compare_func: TabItemComparerByDockOrder);
19053 }
19054
19055 // Apply NavWindow focus back to the tab bar
19056 if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
19057 tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
19058
19059 // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
19060 if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, tab_id: node->SelectedTabId) != NULL)
19061 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
19062 else if (tab_bar->Tabs.Size > tabs_count_old)
19063 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
19064
19065 // Begin tab bar
19066 ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
19067 tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
19068 tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyMixed; // Enforce default policy. Since 1.92.2 this is now reasonable. May expose later if needed. (#8800, #3421)
19069 tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
19070 if (!host_window->Collapsed && is_focused)
19071 tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
19072 tab_bar->ID = GetID(str_id: "#TabBar");
19073 tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
19074 tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
19075 BeginTabBarEx(tab_bar, bb: tab_bar_rect, flags: tab_bar_flags);
19076 //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
19077
19078 // Backup style colors
19079 ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
19080 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19081 backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
19082
19083 // Submit actual tabs
19084 node->VisibleWindow = NULL;
19085 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19086 {
19087 ImGuiWindow* window = node->Windows[window_n];
19088 if (window->LastFrameActive + 1 < g.FrameCount && node_was_active)
19089 continue; // FIXME: Not sure if that's still taken/useful.
19090
19091 ImGuiTabItemFlags tab_item_flags = 0;
19092 tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
19093 if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
19094 tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
19095 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
19096 tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
19097
19098 // Apply stored style overrides for the window
19099 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19100 g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(in: window->DockStyle.Colors[color_n]);
19101
19102 // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
19103 bool tab_open = true;
19104 TabItemEx(tab_bar, label: window->Name, p_open: window->HasCloseButton ? &tab_open : NULL, flags: tab_item_flags, docked_window: window);
19105 if (!tab_open)
19106 node->WantCloseTabId = window->TabId;
19107 if (tab_bar->VisibleTabId == window->TabId)
19108 node->VisibleWindow = window;
19109
19110 // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
19111 window->DC.DockTabItemStatusFlags = g.LastItemData.StatusFlags;
19112 window->DC.DockTabItemRect = g.LastItemData.Rect;
19113
19114 // Update navigation ID on menu layer
19115 if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
19116 host_window->NavLastIds[1] = window->TabId;
19117 }
19118
19119 // Restore style colors
19120 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19121 g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
19122
19123 // Notify root of visible window (used to display title in OS task bar)
19124 if (node->VisibleWindow)
19125 if (is_focused || root_node->VisibleWindow == NULL)
19126 root_node->VisibleWindow = node->VisibleWindow;
19127
19128 // Close button (after VisibleWindow was updated)
19129 // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
19130 const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
19131 const bool close_button_is_visible = node->HasCloseButton;
19132 //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
19133 if (close_button_is_visible)
19134 {
19135 if (!close_button_is_enabled)
19136 {
19137 PushItemFlag(option: ImGuiItemFlags_Disabled, enabled: true);
19138 PushStyleColor(idx: ImGuiCol_Text, col: style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
19139 }
19140 if (CloseButton(id: host_window->GetID(str: "#CLOSE"), pos: close_button_pos))
19141 {
19142 node->WantCloseAll = true;
19143 for (int n = 0; n < tab_bar->Tabs.Size; n++)
19144 TabBarCloseTab(tab_bar, tab: &tab_bar->Tabs[n]);
19145 }
19146 //if (IsItemActive())
19147 // focus_tab_id = tab_bar->SelectedTabId;
19148 if (!close_button_is_enabled)
19149 {
19150 PopStyleColor();
19151 PopItemFlag();
19152 }
19153 }
19154
19155 // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
19156 // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
19157 ImGuiID title_bar_id = host_window->GetID(str: "#TITLEBAR");
19158 if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
19159 {
19160 // AllowOverlap mode required for appending into dock node tab bar,
19161 // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
19162 bool held;
19163 KeepAliveID(id: title_bar_id);
19164 ButtonBehavior(bb: title_bar_rect, id: title_bar_id, NULL, out_held: &held, flags: ImGuiButtonFlags_AllowOverlap);
19165 if (g.HoveredId == title_bar_id)
19166 {
19167 g.LastItemData.ID = title_bar_id;
19168 }
19169 if (held)
19170 {
19171 if (IsMouseClicked(button: 0))
19172 focus_tab_id = tab_bar->SelectedTabId;
19173
19174 // Forward moving request to selected window
19175 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id: tab_bar->SelectedTabId))
19176 StartMouseMovingWindowOrNode(window: tab->Window ? tab->Window : node->HostWindow, node, undock: false); // Undock from tab bar empty space
19177 }
19178 }
19179
19180 // Forward focus from host node to selected window
19181 //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
19182 // focus_tab_id = tab_bar->SelectedTabId;
19183
19184 // When clicked on a tab we requested focus to the docked child
19185 // This overrides the value set by "forward focus from host node to selected window".
19186 if (tab_bar->NextSelectedTabId)
19187 focus_tab_id = tab_bar->NextSelectedTabId;
19188
19189 // Apply navigation focus
19190 if (focus_tab_id != 0)
19191 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id: focus_tab_id))
19192 if (tab->Window)
19193 {
19194 FocusWindow(window: tab->Window);
19195 NavInitWindow(window: tab->Window, force_reinit: false);
19196 }
19197
19198 EndTabBar();
19199 PopID();
19200
19201 // Restore SkipItems flag
19202 if (!node->IsDockSpace())
19203 {
19204 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
19205 host_window->SkipItems = backup_skip_item;
19206 }
19207}
19208
19209static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
19210{
19211 IM_ASSERT(node->TabBar == NULL);
19212 node->TabBar = IM_NEW(ImGuiTabBar);
19213}
19214
19215static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
19216{
19217 if (node->TabBar == NULL)
19218 return;
19219 IM_DELETE(p: node->TabBar);
19220 node->TabBar = NULL;
19221}
19222
19223static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
19224{
19225 if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
19226 return false;
19227
19228 ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
19229 ImGuiWindowClass* payload_class = &payload->WindowClass;
19230 if (host_class->ClassId != payload_class->ClassId)
19231 {
19232 bool pass = false;
19233 if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
19234 pass = true;
19235 if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
19236 pass = true;
19237 if (!pass)
19238 return false;
19239 }
19240
19241 // Prevent docking any window created above a popup
19242 // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
19243 // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
19244 // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
19245 // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
19246 ImGuiContext& g = *GImGui;
19247 for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
19248 if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
19249 if (ImGui::IsWindowWithinBeginStackOf(window: payload, potential_parent: popup_window)) // Payload is created from within a popup begin stack.
19250 return false;
19251
19252 return true;
19253}
19254
19255static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
19256{
19257 if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
19258 return true;
19259
19260 const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
19261 for (int payload_n = 0; payload_n < payload_count; payload_n++)
19262 {
19263 ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
19264 if (DockNodeIsDropAllowedOne(payload, host_window))
19265 return true;
19266 }
19267 return false;
19268}
19269
19270// window menu button == collapse button when not in a dock node.
19271// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
19272static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
19273{
19274 ImGuiContext& g = *GImGui;
19275 ImGuiStyle& style = g.Style;
19276
19277 ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
19278 if (out_title_rect) { *out_title_rect = r; }
19279
19280 r.Min.x += style.WindowBorderSize;
19281 r.Max.x -= style.WindowBorderSize;
19282
19283 float button_sz = g.FontSize;
19284 r.Min.x += style.FramePadding.x;
19285 r.Max.x -= style.FramePadding.x;
19286 ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
19287 if (node->HasCloseButton)
19288 {
19289 if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
19290 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
19291 }
19292 if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
19293 {
19294 r.Min.x += button_sz + style.ItemInnerSpacing.x;
19295 }
19296 else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
19297 {
19298 window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
19299 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
19300 }
19301 if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
19302 if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
19303}
19304
19305void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
19306{
19307 ImGuiContext& g = *GImGui;
19308 const float dock_spacing = g.Style.ItemInnerSpacing.x;
19309 const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
19310 pos_new[axis ^ 1] = pos_old[axis ^ 1];
19311 size_new[axis ^ 1] = size_old[axis ^ 1];
19312
19313 // Distribute size on given axis (with a desired size or equally)
19314 const float w_avail = size_old[axis] - dock_spacing;
19315 if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
19316 {
19317 size_new[axis] = size_new_desired[axis];
19318 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
19319 }
19320 else
19321 {
19322 size_new[axis] = IM_TRUNC(w_avail * 0.5f);
19323 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
19324 }
19325
19326 // Position each node
19327 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
19328 {
19329 pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
19330 }
19331 else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
19332 {
19333 pos_new[axis] = pos_old[axis];
19334 pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
19335 }
19336}
19337
19338// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
19339bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
19340{
19341 ImGuiContext& g = *GImGui;
19342
19343 const float parent_smaller_axis = ImMin(lhs: parent.GetWidth(), rhs: parent.GetHeight());
19344 const float hs_for_central_nodes = ImMin(lhs: g.FontSize * 1.5f, rhs: ImMax(lhs: g.FontSize * 0.5f, rhs: parent_smaller_axis / 8.0f));
19345 float hs_w; // Half-size, longer axis
19346 float hs_h; // Half-size, smaller axis
19347 ImVec2 off; // Distance from edge or center
19348 if (outer_docking)
19349 {
19350 //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
19351 //hs_h = ImTrunc(hs_w * 0.15f);
19352 //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
19353 hs_w = ImTrunc(f: hs_for_central_nodes * 1.50f);
19354 hs_h = ImTrunc(f: hs_for_central_nodes * 0.80f);
19355 off = ImTrunc(v: ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
19356 }
19357 else
19358 {
19359 hs_w = ImTrunc(f: hs_for_central_nodes);
19360 hs_h = ImTrunc(f: hs_for_central_nodes * 0.90f);
19361 off = ImTrunc(v: ImVec2(hs_w * 2.40f, hs_w * 2.40f));
19362 }
19363
19364 ImVec2 c = ImTrunc(v: parent.GetCenter());
19365 if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
19366 else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
19367 else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
19368 else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
19369 else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
19370
19371 if (test_mouse_pos == NULL)
19372 return false;
19373
19374 ImRect hit_r = out_r;
19375 if (!outer_docking)
19376 {
19377 // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
19378 hit_r.Expand(amount: ImTrunc(f: hs_w * 0.30f));
19379 ImVec2 mouse_delta = (*test_mouse_pos - c);
19380 float mouse_delta_len2 = ImLengthSqr(lhs: mouse_delta);
19381 float r_threshold_center = hs_w * 1.4f;
19382 float r_threshold_sides = hs_w * (1.4f + 1.2f);
19383 if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
19384 return (dir == ImGuiDir_None);
19385 if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
19386 return (dir == ImGetDirQuadrantFromDelta(dx: mouse_delta.x, dy: mouse_delta.y));
19387 }
19388 return hit_r.Contains(p: *test_mouse_pos);
19389}
19390
19391// host_node may be NULL if the window doesn't have a DockNode already.
19392// FIXME-DOCK: This is misnamed since it's also doing the filtering.
19393static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
19394{
19395 ImGuiContext& g = *GImGui;
19396
19397 // There is an edge case when docking into a dockspace which only has inactive nodes.
19398 // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
19399 // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
19400 if (payload_node == NULL)
19401 payload_node = payload_window->DockNodeAsHost;
19402 ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(node: host_node) : host_node;
19403 if (ref_node_for_rect)
19404 IM_ASSERT(ref_node_for_rect->IsVisible == true);
19405
19406 // Filter, figure out where we are allowed to dock
19407 ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
19408 ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
19409 data->IsCenterAvailable = true;
19410 if (is_outer_docking)
19411 data->IsCenterAvailable = false;
19412 else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
19413 data->IsCenterAvailable = false;
19414 else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
19415 data->IsCenterAvailable = false;
19416 else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
19417 data->IsCenterAvailable = false;
19418 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
19419 data->IsCenterAvailable = false;
19420 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
19421 data->IsCenterAvailable = false;
19422
19423 data->IsSidesAvailable = true;
19424 if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
19425 data->IsSidesAvailable = false;
19426 else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
19427 data->IsSidesAvailable = false;
19428 else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
19429 data->IsSidesAvailable = false;
19430
19431 // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
19432 data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
19433 data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
19434 data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
19435 data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
19436
19437 // Calculate drop shapes geometry for allowed splitting directions
19438 IM_ASSERT(ImGuiDir_None == -1);
19439 data->SplitNode = host_node;
19440 data->SplitDir = ImGuiDir_None;
19441 data->IsSplitDirExplicit = false;
19442 if (!host_window->Collapsed)
19443 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
19444 {
19445 if (dir == ImGuiDir_None && !data->IsCenterAvailable)
19446 continue;
19447 if (dir != ImGuiDir_None && !data->IsSidesAvailable)
19448 continue;
19449 if (DockNodeCalcDropRectsAndTestMousePos(parent: data->FutureNode.Rect(), dir: (ImGuiDir)dir, out_r&: data->DropRectsDraw[dir+1], outer_docking: is_outer_docking, test_mouse_pos: &g.IO.MousePos))
19450 {
19451 data->SplitDir = (ImGuiDir)dir;
19452 data->IsSplitDirExplicit = true;
19453 }
19454 }
19455
19456 // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
19457 data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
19458 if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
19459 data->IsDropAllowed = false;
19460
19461 // Calculate split area
19462 data->SplitRatio = 0.0f;
19463 if (data->SplitDir != ImGuiDir_None)
19464 {
19465 ImGuiDir split_dir = data->SplitDir;
19466 ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
19467 ImVec2 pos_new, pos_old = data->FutureNode.Pos;
19468 ImVec2 size_new, size_old = data->FutureNode.Size;
19469 DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir: split_dir, size_new_desired: payload_window->Size);
19470
19471 // Calculate split ratio so we can pass it down the docking request
19472 float split_ratio = ImSaturate(f: size_new[split_axis] / data->FutureNode.Size[split_axis]);
19473 data->FutureNode.Pos = pos_new;
19474 data->FutureNode.Size = size_new;
19475 data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
19476 }
19477}
19478
19479static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
19480{
19481 ImGuiContext& g = *GImGui;
19482 IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
19483
19484 // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
19485 // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
19486 const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
19487
19488 // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
19489 int overlay_draw_lists_count = 0;
19490 ImDrawList* overlay_draw_lists[2];
19491 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(viewport: host_window->Viewport);
19492 if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
19493 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(viewport: root_payload->Viewport);
19494
19495 // Draw main preview rectangle
19496 const ImU32 overlay_col_main = GetColorU32(idx: ImGuiCol_DockingPreview, alpha_mul: is_transparent_payload ? 0.60f : 0.40f);
19497 const ImU32 overlay_col_drop = GetColorU32(idx: ImGuiCol_DockingPreview, alpha_mul: is_transparent_payload ? 0.90f : 0.70f);
19498 const ImU32 overlay_col_drop_hovered = GetColorU32(idx: ImGuiCol_DockingPreview, alpha_mul: is_transparent_payload ? 1.20f : 1.00f);
19499 const ImU32 overlay_col_lines = GetColorU32(idx: ImGuiCol_NavWindowingHighlight, alpha_mul: is_transparent_payload ? 0.80f : 0.60f);
19500
19501 // Display area preview
19502 const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
19503 if (data->IsDropAllowed)
19504 {
19505 ImRect overlay_rect = data->FutureNode.Rect();
19506 if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
19507 overlay_rect.Min.y += GetFrameHeight();
19508 if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
19509 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19510 overlay_draw_lists[overlay_n]->AddRectFilled(p_min: overlay_rect.Min, p_max: overlay_rect.Max, col: overlay_col_main, rounding: host_window->WindowRounding, flags: CalcRoundingFlagsForRectInRect(r_in: overlay_rect, r_outer: host_window->Rect(), threshold: g.Style.DockingSeparatorSize));
19511 }
19512
19513 // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
19514 if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
19515 {
19516 // Compute target tab bar geometry so we can locate our preview tabs
19517 ImRect tab_bar_rect;
19518 DockNodeCalcTabBarLayout(node: &data->FutureNode, NULL, out_tab_bar_rect: &tab_bar_rect, NULL, NULL);
19519 ImVec2 tab_pos = tab_bar_rect.Min;
19520 if (host_node && host_node->TabBar)
19521 {
19522 if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
19523 tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
19524 else
19525 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(window: host_node->Windows[0]).x;
19526 }
19527 else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
19528 {
19529 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(window: host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
19530 }
19531
19532 // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
19533 if (root_payload->DockNodeAsHost)
19534 IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
19535 ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
19536 const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
19537 for (int payload_n = 0; payload_n < payload_count; payload_n++)
19538 {
19539 // DockNode's TabBar may have non-window Tabs manually appended by user
19540 ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
19541 if (tab_bar_with_payload && payload_window == NULL)
19542 continue;
19543 if (!DockNodeIsDropAllowedOne(payload: payload_window, host_window))
19544 continue;
19545
19546 // Calculate the tab bounding box for each payload window
19547 ImVec2 tab_size = TabItemCalcSize(window: payload_window);
19548 ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
19549 tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
19550 const ImU32 overlay_col_text = GetColorU32(col: payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
19551 const ImU32 overlay_col_tabs = GetColorU32(col: payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
19552 PushStyleColor(idx: ImGuiCol_Text, col: overlay_col_text);
19553 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19554 {
19555 ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
19556 if (!tab_bar_rect.Contains(r: tab_bb))
19557 overlay_draw_lists[overlay_n]->PushClipRect(clip_rect_min: tab_bar_rect.Min, clip_rect_max: tab_bar_rect.Max);
19558 TabItemBackground(draw_list: overlay_draw_lists[overlay_n], bb: tab_bb, flags: tab_flags, col: overlay_col_tabs);
19559 TabItemLabelAndCloseButton(draw_list: overlay_draw_lists[overlay_n], bb: tab_bb, flags: tab_flags, frame_padding: g.Style.FramePadding, label: payload_window->Name, tab_id: 0, close_button_id: 0, is_contents_visible: false, NULL, NULL);
19560 if (!tab_bar_rect.Contains(r: tab_bb))
19561 overlay_draw_lists[overlay_n]->PopClipRect();
19562 }
19563 PopStyleColor();
19564 }
19565 }
19566
19567 // Display drop boxes
19568 const float overlay_rounding = ImMax(lhs: 3.0f, rhs: g.Style.FrameRounding);
19569 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
19570 {
19571 if (!data->DropRectsDraw[dir + 1].IsInverted())
19572 {
19573 ImRect draw_r = data->DropRectsDraw[dir + 1];
19574 ImRect draw_r_in = draw_r;
19575 draw_r_in.Expand(amount: -2.0f);
19576 ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
19577 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19578 {
19579 ImVec2 center = ImFloor(v: draw_r_in.GetCenter());
19580 overlay_draw_lists[overlay_n]->AddRectFilled(p_min: draw_r.Min, p_max: draw_r.Max, col: overlay_col, rounding: overlay_rounding);
19581 overlay_draw_lists[overlay_n]->AddRect(p_min: draw_r_in.Min, p_max: draw_r_in.Max, col: overlay_col_lines, rounding: overlay_rounding);
19582 if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
19583 overlay_draw_lists[overlay_n]->AddLine(p1: ImVec2(center.x, draw_r_in.Min.y), p2: ImVec2(center.x, draw_r_in.Max.y), col: overlay_col_lines);
19584 if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
19585 overlay_draw_lists[overlay_n]->AddLine(p1: ImVec2(draw_r_in.Min.x, center.y), p2: ImVec2(draw_r_in.Max.x, center.y), col: overlay_col_lines);
19586 }
19587 }
19588
19589 // Stop after ImGuiDir_None
19590 if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
19591 return;
19592 }
19593}
19594
19595//-----------------------------------------------------------------------------
19596// Docking: ImGuiDockNode Tree manipulation functions
19597//-----------------------------------------------------------------------------
19598// - DockNodeTreeSplit()
19599// - DockNodeTreeMerge()
19600// - DockNodeTreeUpdatePosSize()
19601// - DockNodeTreeUpdateSplitterFindTouchingNode()
19602// - DockNodeTreeUpdateSplitter()
19603// - DockNodeTreeFindFallbackLeafNode()
19604// - DockNodeTreeFindNodeByPos()
19605//-----------------------------------------------------------------------------
19606
19607void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
19608{
19609 ImGuiContext& g = *GImGui;
19610 IM_ASSERT(split_axis != ImGuiAxis_None);
19611
19612 ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, id: 0);
19613 child_0->ParentNode = parent_node;
19614
19615 ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, id: 0);
19616 child_1->ParentNode = parent_node;
19617
19618 ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
19619 DockNodeMoveChildNodes(dst_node: child_inheritor, src_node: parent_node);
19620 parent_node->ChildNodes[0] = child_0;
19621 parent_node->ChildNodes[1] = child_1;
19622 parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
19623 parent_node->SplitAxis = split_axis;
19624 parent_node->VisibleWindow = NULL;
19625 parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
19626
19627 float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
19628 size_avail = ImMax(lhs: size_avail, rhs: g.Style.WindowMinSize[split_axis] * 2.0f);
19629 IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
19630 child_0->SizeRef = child_1->SizeRef = parent_node->Size;
19631 child_0->SizeRef[split_axis] = ImTrunc(f: size_avail * split_ratio);
19632 child_1->SizeRef[split_axis] = ImTrunc(f: size_avail - child_0->SizeRef[split_axis]);
19633
19634 DockNodeMoveWindows(dst_node: parent_node->ChildNodes[split_inheritor_child_idx], src_node: parent_node);
19635 DockSettingsRenameNodeReferences(old_node_id: parent_node->ID, new_node_id: parent_node->ChildNodes[split_inheritor_child_idx]->ID);
19636 DockNodeUpdateHasCentralNodeChild(node: DockNodeGetRootNode(node: parent_node));
19637 DockNodeTreeUpdatePosSize(node: parent_node, pos: parent_node->Pos, size: parent_node->Size);
19638
19639 // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
19640 child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
19641 child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
19642 child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19643 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19644 child_0->UpdateMergedFlags();
19645 child_1->UpdateMergedFlags();
19646 parent_node->UpdateMergedFlags();
19647 if (child_inheritor->IsCentralNode())
19648 DockNodeGetRootNode(node: parent_node)->CentralNode = child_inheritor;
19649}
19650
19651void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
19652{
19653 // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
19654 ImGuiContext& g = *GImGui;
19655 ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
19656 ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
19657 IM_ASSERT(child_0 || child_1);
19658 IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
19659 if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
19660 {
19661 IM_ASSERT(parent_node->TabBar == NULL);
19662 IM_ASSERT(parent_node->Windows.Size == 0);
19663 }
19664 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
19665
19666 ImVec2 backup_last_explicit_size = parent_node->SizeRef;
19667 DockNodeMoveChildNodes(dst_node: parent_node, src_node: merge_lead_child);
19668 if (child_0)
19669 {
19670 DockNodeMoveWindows(dst_node: parent_node, src_node: child_0); // Generally only 1 of the 2 child node will have windows
19671 DockSettingsRenameNodeReferences(old_node_id: child_0->ID, new_node_id: parent_node->ID);
19672 }
19673 if (child_1)
19674 {
19675 DockNodeMoveWindows(dst_node: parent_node, src_node: child_1);
19676 DockSettingsRenameNodeReferences(old_node_id: child_1->ID, new_node_id: parent_node->ID);
19677 }
19678 DockNodeApplyPosSizeToWindows(node: parent_node);
19679 parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
19680 parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
19681 parent_node->SizeRef = backup_last_explicit_size;
19682
19683 // Flags transfer
19684 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
19685 parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19686 parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19687 parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
19688 parent_node->UpdateMergedFlags();
19689
19690 if (child_0)
19691 {
19692 ctx->DockContext.Nodes.SetVoidPtr(key: child_0->ID, NULL);
19693 IM_DELETE(p: child_0);
19694 }
19695 if (child_1)
19696 {
19697 ctx->DockContext.Nodes.SetVoidPtr(key: child_1->ID, NULL);
19698 IM_DELETE(p: child_1);
19699 }
19700}
19701
19702// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
19703// (Depth-first, Pre-Order)
19704void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
19705{
19706 // During the regular dock node update we write to all nodes.
19707 // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
19708 ImGuiContext& g = *GImGui;
19709 const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
19710 if (write_to_node)
19711 {
19712 node->Pos = pos;
19713 node->Size = size;
19714 }
19715
19716 if (node->IsLeafNode())
19717 return;
19718
19719 ImGuiDockNode* child_0 = node->ChildNodes[0];
19720 ImGuiDockNode* child_1 = node->ChildNodes[1];
19721 ImVec2 child_0_pos = pos, child_1_pos = pos;
19722 ImVec2 child_0_size = size, child_1_size = size;
19723
19724 const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(node: only_write_to_single_node, parent: child_0));
19725 const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(node: only_write_to_single_node, parent: child_1));
19726 const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
19727 const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
19728
19729 if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
19730 {
19731 const float spacing = g.Style.DockingSeparatorSize;
19732 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
19733 const float size_avail = ImMax(lhs: size[axis] - spacing, rhs: 0.0f);
19734
19735 // Size allocation policy
19736 // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
19737 const float size_min_each = ImTrunc(f: ImMin(lhs: size_avail, rhs: g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
19738
19739 // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
19740 // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
19741 // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
19742
19743 // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
19744 if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
19745 {
19746 child_0_size[axis] = child_0->SizeRef[axis] = ImMin(lhs: size_avail - 1.0f, rhs: child_0->Size[axis]);
19747 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
19748 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
19749 }
19750 else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
19751 {
19752 child_1_size[axis] = child_1->SizeRef[axis] = ImMin(lhs: size_avail - 1.0f, rhs: child_1->Size[axis]);
19753 child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
19754 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
19755 }
19756 else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
19757 {
19758 // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
19759 // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
19760 float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
19761 child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(f: size_avail * split_ratio);
19762 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
19763 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
19764 }
19765
19766 // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
19767 else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
19768 {
19769 child_0_size[axis] = ImMin(lhs: size_avail - size_min_each, rhs: child_0->SizeRef[axis]);
19770 child_1_size[axis] = (size_avail - child_0_size[axis]);
19771 }
19772 else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
19773 {
19774 child_1_size[axis] = ImMin(lhs: size_avail - size_min_each, rhs: child_1->SizeRef[axis]);
19775 child_0_size[axis] = (size_avail - child_1_size[axis]);
19776 }
19777 else
19778 {
19779 // 4) Otherwise distribute according to the relative ratio of each SizeRef value
19780 float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
19781 child_0_size[axis] = ImMax(lhs: size_min_each, rhs: ImTrunc(f: size_avail * split_ratio + 0.5f));
19782 child_1_size[axis] = (size_avail - child_0_size[axis]);
19783 }
19784
19785 child_1_pos[axis] += spacing + child_0_size[axis];
19786 }
19787
19788 if (only_write_to_single_node == NULL)
19789 child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
19790
19791 const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
19792 const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
19793 if (child_0_recurse)
19794 DockNodeTreeUpdatePosSize(node: child_0, pos: child_0_pos, size: child_0_size);
19795 if (child_1_recurse)
19796 DockNodeTreeUpdatePosSize(node: child_1, pos: child_1_pos, size: child_1_size);
19797}
19798
19799static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
19800{
19801 if (node->IsLeafNode())
19802 {
19803 touching_nodes->push_back(v: node);
19804 return;
19805 }
19806 if (node->ChildNodes[0]->IsVisible)
19807 if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
19808 DockNodeTreeUpdateSplitterFindTouchingNode(node: node->ChildNodes[0], axis, side, touching_nodes);
19809 if (node->ChildNodes[1]->IsVisible)
19810 if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
19811 DockNodeTreeUpdateSplitterFindTouchingNode(node: node->ChildNodes[1], axis, side, touching_nodes);
19812}
19813
19814// (Depth-First, Pre-Order)
19815void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
19816{
19817 if (node->IsLeafNode())
19818 return;
19819
19820 ImGuiContext& g = *GImGui;
19821
19822 ImGuiDockNode* child_0 = node->ChildNodes[0];
19823 ImGuiDockNode* child_1 = node->ChildNodes[1];
19824 if (child_0->IsVisible && child_1->IsVisible)
19825 {
19826 // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
19827 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
19828 IM_ASSERT(axis != ImGuiAxis_None);
19829 ImRect bb;
19830 bb.Min = child_0->Pos;
19831 bb.Max = child_1->Pos;
19832 bb.Min[axis] += child_0->Size[axis];
19833 bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
19834 //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
19835
19836 const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
19837 const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
19838 if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
19839 {
19840 ImGuiWindow* window = g.CurrentWindow;
19841 window->DrawList->AddRectFilled(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Separator), rounding: g.Style.FrameRounding);
19842 }
19843 else
19844 {
19845 //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
19846 //bb.Max[axis] -= 1;
19847 PushID(int_id: node->ID);
19848
19849 // Find resizing limits by gathering list of nodes that are touching the splitter line.
19850 ImVector<ImGuiDockNode*> touching_nodes[2];
19851 float min_size = g.Style.WindowMinSize[axis];
19852 float resize_limits[2];
19853 resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
19854 resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
19855
19856 ImGuiID splitter_id = GetID(str_id: "##Splitter");
19857 if (g.ActiveId == splitter_id) // Only process when splitter is active
19858 {
19859 DockNodeTreeUpdateSplitterFindTouchingNode(node: child_0, axis, side: 1, touching_nodes: &touching_nodes[0]);
19860 DockNodeTreeUpdateSplitterFindTouchingNode(node: child_1, axis, side: 0, touching_nodes: &touching_nodes[1]);
19861 for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
19862 resize_limits[0] = ImMax(lhs: resize_limits[0], rhs: touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
19863 for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
19864 resize_limits[1] = ImMin(lhs: resize_limits[1], rhs: touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
19865
19866 // [DEBUG] Render touching nodes & limits
19867 /*
19868 ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19869 for (int n = 0; n < 2; n++)
19870 {
19871 for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
19872 draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
19873 if (axis == ImGuiAxis_X)
19874 draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
19875 else
19876 draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
19877 }
19878 */
19879 }
19880
19881 // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
19882 float cur_size_0 = child_0->Size[axis];
19883 float cur_size_1 = child_1->Size[axis];
19884 float min_size_0 = resize_limits[0] - child_0->Pos[axis];
19885 float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
19886 ImU32 bg_col = GetColorU32(idx: ImGuiCol_WindowBg);
19887 if (SplitterBehavior(bb, id: GetID(str_id: "##Splitter"), axis, size1: &cur_size_0, size2: &cur_size_1, min_size1: min_size_0, min_size2: min_size_1, hover_extend: g.WindowsBorderHoverPadding, hover_visibility_delay: WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
19888 {
19889 if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
19890 {
19891 child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
19892 child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
19893 child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
19894
19895 // Lock the size of every node that is a sibling of the node we are touching
19896 // This might be less desirable if we can merge sibling of a same axis into the same parental level.
19897 for (int side_n = 0; side_n < 2; side_n++)
19898 for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
19899 {
19900 ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
19901 //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19902 //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
19903 while (touching_node->ParentNode != node)
19904 {
19905 if (touching_node->ParentNode->SplitAxis == axis)
19906 {
19907 // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
19908 ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
19909 node_to_preserve->WantLockSizeOnce = true;
19910 //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
19911 //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
19912 }
19913 touching_node = touching_node->ParentNode;
19914 }
19915 }
19916
19917 DockNodeTreeUpdatePosSize(node: child_0, pos: child_0->Pos, size: child_0->Size);
19918 DockNodeTreeUpdatePosSize(node: child_1, pos: child_1->Pos, size: child_1->Size);
19919 MarkIniSettingsDirty();
19920 }
19921 }
19922 PopID();
19923 }
19924 }
19925
19926 if (child_0->IsVisible)
19927 DockNodeTreeUpdateSplitter(node: child_0);
19928 if (child_1->IsVisible)
19929 DockNodeTreeUpdateSplitter(node: child_1);
19930}
19931
19932ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
19933{
19934 if (node->IsLeafNode())
19935 return node;
19936 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node: node->ChildNodes[0]))
19937 return leaf_node;
19938 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node: node->ChildNodes[1]))
19939 return leaf_node;
19940 return NULL;
19941}
19942
19943ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
19944{
19945 if (!node->IsVisible)
19946 return NULL;
19947
19948 const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
19949 ImRect r(node->Pos, node->Pos + node->Size);
19950 r.Expand(amount: dock_spacing * 0.5f);
19951 bool inside = r.Contains(p: pos);
19952 if (!inside)
19953 return NULL;
19954
19955 if (node->IsLeafNode())
19956 return node;
19957 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node: node->ChildNodes[0], pos))
19958 return hovered_node;
19959 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node: node->ChildNodes[1], pos))
19960 return hovered_node;
19961
19962 // This means we are hovering over the splitter/spacing of a parent node
19963 return node;
19964}
19965
19966//-----------------------------------------------------------------------------
19967// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
19968//-----------------------------------------------------------------------------
19969// - SetWindowDock() [Internal]
19970// - DockSpace()
19971// - DockSpaceOverViewport()
19972//-----------------------------------------------------------------------------
19973
19974// [Internal] Called via SetNextWindowDockID()
19975void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
19976{
19977 // Test condition (NB: bit 0 is always true) and clear flags for next time
19978 if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
19979 return;
19980 window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
19981
19982 if (window->DockId == dock_id)
19983 return;
19984
19985 // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
19986 ImGuiContext& g = *GImGui;
19987 if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx: &g, id: dock_id))
19988 if (new_node->IsSplitNode())
19989 {
19990 // Policy: Find central node or latest focused node. We first move back to our root node.
19991 new_node = DockNodeGetRootNode(node: new_node);
19992 if (new_node->CentralNode)
19993 {
19994 IM_ASSERT(new_node->CentralNode->IsCentralNode());
19995 dock_id = new_node->CentralNode->ID;
19996 }
19997 else
19998 {
19999 dock_id = new_node->LastFocusedNodeId;
20000 }
20001 }
20002
20003 if (window->DockId == dock_id)
20004 return;
20005
20006 if (window->DockNode)
20007 DockNodeRemoveWindow(node: window->DockNode, window, save_dock_id: 0);
20008 window->DockId = dock_id;
20009}
20010
20011// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
20012// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
20013// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
20014// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
20015ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
20016{
20017 ImGuiContext& g = *GImGui;
20018 ImGuiWindow* window = GetCurrentWindowRead();
20019 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
20020 return 0;
20021
20022 // Early out if parent window is hidden/collapsed
20023 // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
20024 // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
20025 if (window->SkipItems)
20026 flags |= ImGuiDockNodeFlags_KeepAliveOnly;
20027 if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
20028 window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
20029
20030 IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags!
20031 IM_ASSERT((flags & ImGuiDockNodeFlags_CentralNode) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145)
20032
20033 IM_ASSERT(dockspace_id != 0);
20034 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: dockspace_id);
20035 if (node == NULL)
20036 {
20037 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
20038 node = DockContextAddNode(ctx: &g, id: dockspace_id);
20039 node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
20040 }
20041 if (window_class && window_class->ClassId != node->WindowClass.ClassId)
20042 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId);
20043 node->SharedFlags = flags;
20044 node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
20045
20046 // When a DockSpace transitioned form implicit to explicit this may be called a second time
20047 // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
20048 if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
20049 {
20050 IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
20051 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
20052 return dockspace_id;
20053 }
20054 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
20055
20056 // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
20057 if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
20058 {
20059 node->LastFrameAlive = g.FrameCount;
20060 return dockspace_id;
20061 }
20062
20063 const ImVec2 content_avail = GetContentRegionAvail();
20064 ImVec2 size = ImTrunc(v: size_arg);
20065 if (size.x <= 0.0f)
20066 size.x = ImMax(lhs: content_avail.x + size.x, rhs: 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
20067 if (size.y <= 0.0f)
20068 size.y = ImMax(lhs: content_avail.y + size.y, rhs: 4.0f);
20069 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
20070
20071 node->Pos = window->DC.CursorPos;
20072 node->Size = node->SizeRef = size;
20073 SetNextWindowPos(pos: node->Pos);
20074 SetNextWindowSize(size: node->Size);
20075 g.NextWindowData.PosUndock = false;
20076
20077 // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
20078 // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
20079 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
20080 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
20081 window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
20082 window_flags |= ImGuiWindowFlags_NoBackground;
20083
20084 char title[256];
20085 ImFormatString(buf: title, IM_ARRAYSIZE(title), fmt: "%s/DockSpace_%08X", window->Name, dockspace_id);
20086
20087 PushStyleVar(idx: ImGuiStyleVar_ChildBorderSize, val: 0.0f);
20088 Begin(name: title, NULL, flags: window_flags);
20089 PopStyleVar();
20090
20091 ImGuiWindow* host_window = g.CurrentWindow;
20092 DockNodeSetupHostWindow(node, host_window);
20093 host_window->ChildId = window->GetID(str: title);
20094 node->OnlyNodeWithWindows = NULL;
20095
20096 IM_ASSERT(node->IsRootNode());
20097
20098 // We need to handle the rare case were a central node is missing.
20099 // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
20100 // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
20101 // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
20102 // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
20103 // as it doesn't make sense for an empty dockspace to not have this property.
20104 if (node->IsLeafNode() && !node->IsCentralNode())
20105 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20106
20107 // Update the node
20108 DockNodeUpdate(node);
20109
20110 End();
20111
20112 ImRect bb(node->Pos, node->Pos + size);
20113 ItemSize(size);
20114 ItemAdd(bb, id: dockspace_id, NULL, extra_flags: ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
20115 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(window: g.HoveredWindow, potential_parent: host_window, popup_hierarchy: false, dock_hierarchy: true)) // To fullfill IsItemHovered(), similar to EndChild()
20116 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
20117
20118 return dockspace_id;
20119}
20120
20121// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
20122// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
20123// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
20124// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
20125ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
20126{
20127 if (viewport == NULL)
20128 viewport = GetMainViewport();
20129
20130 // Submit a window filling the entire viewport
20131 SetNextWindowPos(pos: viewport->WorkPos);
20132 SetNextWindowSize(size: viewport->WorkSize);
20133 SetNextWindowViewport(viewport->ID);
20134
20135 ImGuiWindowFlags host_window_flags = 0;
20136 host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
20137 host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
20138 if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
20139 host_window_flags |= ImGuiWindowFlags_NoBackground;
20140
20141 // FIXME-OPT: When using ImGuiDockNodeFlags_KeepAliveOnly with DockSpaceOverViewport() we might be able to spare submitting the window,
20142 // since DockSpace() with that flag doesn't need a window. We'd only need to compute the default ID accordingly.
20143 if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly)
20144 host_window_flags |= ImGuiWindowFlags_NoMouseInputs;
20145
20146 char label[32];
20147 ImFormatString(buf: label, IM_ARRAYSIZE(label), fmt: "WindowOverViewport_%08X", viewport->ID);
20148
20149 PushStyleVar(idx: ImGuiStyleVar_WindowRounding, val: 0.0f);
20150 PushStyleVar(idx: ImGuiStyleVar_WindowBorderSize, val: 0.0f);
20151 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: ImVec2(0.0f, 0.0f));
20152 Begin(name: label, NULL, flags: host_window_flags);
20153 PopStyleVar(count: 3);
20154
20155 // Submit the dockspace
20156 if (dockspace_id == 0)
20157 dockspace_id = GetID(str_id: "DockSpace");
20158 DockSpace(dockspace_id, size_arg: ImVec2(0.0f, 0.0f), flags: dockspace_flags, window_class);
20159
20160 End();
20161
20162 return dockspace_id;
20163}
20164
20165//-----------------------------------------------------------------------------
20166// Docking: Builder Functions
20167//-----------------------------------------------------------------------------
20168// Very early end-user API to manipulate dock nodes.
20169// Only available in imgui_internal.h. Expect this API to change/break!
20170// It is expected that those functions are all called _before_ the dockspace node submission.
20171//-----------------------------------------------------------------------------
20172// - DockBuilderDockWindow()
20173// - DockBuilderGetNode()
20174// - DockBuilderSetNodePos()
20175// - DockBuilderSetNodeSize()
20176// - DockBuilderAddNode()
20177// - DockBuilderRemoveNode()
20178// - DockBuilderRemoveNodeChildNodes()
20179// - DockBuilderRemoveNodeDockedWindows()
20180// - DockBuilderSplitNode()
20181// - DockBuilderCopyNodeRec()
20182// - DockBuilderCopyNode()
20183// - DockBuilderCopyWindowSettings()
20184// - DockBuilderCopyDockSpace()
20185// - DockBuilderFinish()
20186//-----------------------------------------------------------------------------
20187
20188void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
20189{
20190 // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
20191 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20192 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
20193 ImGuiID window_id = ImHashStr(data_p: window_name);
20194 if (ImGuiWindow* window = FindWindowByID(id: window_id))
20195 {
20196 // Apply to created window
20197 ImGuiID prev_node_id = window->DockId;
20198 SetWindowDock(window, dock_id: node_id, cond: ImGuiCond_Always);
20199 if (window->DockId != prev_node_id)
20200 window->DockOrder = -1;
20201 }
20202 else
20203 {
20204 // Apply to settings
20205 ImGuiWindowSettings* settings = FindWindowSettingsByID(id: window_id);
20206 if (settings == NULL)
20207 settings = CreateNewWindowSettings(name: window_name);
20208 if (settings->DockId != node_id)
20209 settings->DockOrder = -1;
20210 settings->DockId = node_id;
20211 }
20212}
20213
20214ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
20215{
20216 ImGuiContext& g = *GImGui;
20217 return DockContextFindNodeByID(ctx: &g, id: node_id);
20218}
20219
20220void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
20221{
20222 ImGuiContext& g = *GImGui;
20223 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: node_id);
20224 if (node == NULL)
20225 return;
20226 node->Pos = pos;
20227 node->AuthorityForPos = ImGuiDataAuthority_DockNode;
20228}
20229
20230void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
20231{
20232 ImGuiContext& g = *GImGui;
20233 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: node_id);
20234 if (node == NULL)
20235 return;
20236 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
20237 node->Size = node->SizeRef = size;
20238 node->AuthorityForSize = ImGuiDataAuthority_DockNode;
20239}
20240
20241// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
20242// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
20243// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
20244// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
20245// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
20246// - Use (id == 0) to let the system allocate a node identifier.
20247// - Existing node with a same id will be removed.
20248ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
20249{
20250 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20251 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
20252
20253 if (node_id != 0)
20254 DockBuilderRemoveNode(node_id);
20255
20256 ImGuiDockNode* node = NULL;
20257 if (flags & ImGuiDockNodeFlags_DockSpace)
20258 {
20259 DockSpace(dockspace_id: node_id, size_arg: ImVec2(0, 0), flags: (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
20260 node = DockContextFindNodeByID(ctx: &g, id: node_id);
20261 }
20262 else
20263 {
20264 node = DockContextAddNode(ctx: &g, id: node_id);
20265 node->SetLocalFlags(flags);
20266 }
20267 node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
20268 return node->ID;
20269}
20270
20271void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
20272{
20273 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20274 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
20275
20276 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: node_id);
20277 if (node == NULL)
20278 return;
20279 DockBuilderRemoveNodeDockedWindows(node_id, clear_settings_refs: true);
20280 DockBuilderRemoveNodeChildNodes(node_id);
20281 // Node may have moved or deleted if e.g. any merge happened
20282 node = DockContextFindNodeByID(ctx: &g, id: node_id);
20283 if (node == NULL)
20284 return;
20285 if (node->IsCentralNode() && node->ParentNode)
20286 node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20287 DockContextRemoveNode(ctx: &g, node, merge_sibling_into_parent_node: true);
20288}
20289
20290// root_id = 0 to remove all, root_id != 0 to remove child of given node.
20291void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
20292{
20293 ImGuiContext& g = *GImGui;
20294 ImGuiDockContext* dc = &g.DockContext;
20295
20296 ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx: &g, id: root_id) : NULL;
20297 if (root_id && root_node == NULL)
20298 return;
20299 bool has_central_node = false;
20300
20301 ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
20302 ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
20303
20304 // Process active windows
20305 ImVector<ImGuiDockNode*> nodes_to_remove;
20306 for (int n = 0; n < dc->Nodes.Data.Size; n++)
20307 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20308 {
20309 bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
20310 if (want_removal)
20311 {
20312 if (node->IsCentralNode())
20313 has_central_node = true;
20314 if (root_id != 0)
20315 DockContextQueueNotifyRemovedNode(ctx: &g, node);
20316 if (root_node)
20317 {
20318 DockNodeMoveWindows(dst_node: root_node, src_node: node);
20319 DockSettingsRenameNodeReferences(old_node_id: node->ID, new_node_id: root_node->ID);
20320 }
20321 nodes_to_remove.push_back(v: node);
20322 }
20323 }
20324
20325 // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
20326 // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
20327 if (root_node)
20328 {
20329 root_node->AuthorityForPos = backup_root_node_authority_for_pos;
20330 root_node->AuthorityForSize = backup_root_node_authority_for_size;
20331 }
20332
20333 // Apply to settings
20334 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
20335 if (ImGuiID window_settings_dock_id = settings->DockId)
20336 for (int n = 0; n < nodes_to_remove.Size; n++)
20337 if (nodes_to_remove[n]->ID == window_settings_dock_id)
20338 {
20339 settings->DockId = root_id;
20340 break;
20341 }
20342
20343 // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
20344 if (nodes_to_remove.Size > 1)
20345 ImQsort(base: nodes_to_remove.Data, count: nodes_to_remove.Size, size_of_element: sizeof(ImGuiDockNode*), compare_func: DockNodeComparerDepthMostFirst);
20346 for (int n = 0; n < nodes_to_remove.Size; n++)
20347 DockContextRemoveNode(ctx: &g, node: nodes_to_remove[n], merge_sibling_into_parent_node: false);
20348
20349 if (root_id == 0)
20350 {
20351 dc->Nodes.Clear();
20352 dc->Requests.clear();
20353 }
20354 else if (has_central_node)
20355 {
20356 root_node->CentralNode = root_node;
20357 root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20358 }
20359}
20360
20361void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
20362{
20363 // Clear references in settings
20364 ImGuiContext& g = *GImGui;
20365 if (clear_settings_refs)
20366 {
20367 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
20368 {
20369 bool want_removal = (root_id == 0) || (settings->DockId == root_id);
20370 if (!want_removal && settings->DockId != 0)
20371 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: settings->DockId))
20372 if (DockNodeGetRootNode(node)->ID == root_id)
20373 want_removal = true;
20374 if (want_removal)
20375 settings->DockId = 0;
20376 }
20377 }
20378
20379 // Clear references in windows
20380 for (int n = 0; n < g.Windows.Size; n++)
20381 {
20382 ImGuiWindow* window = g.Windows[n];
20383 bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(node: window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
20384 if (want_removal)
20385 {
20386 const ImGuiID backup_dock_id = window->DockId;
20387 IM_UNUSED(backup_dock_id);
20388 DockContextProcessUndockWindow(ctx: &g, window, clear_persistent_docking_ref: clear_settings_refs);
20389 if (!clear_settings_refs)
20390 IM_ASSERT(window->DockId == backup_dock_id);
20391 }
20392 }
20393}
20394
20395// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
20396// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
20397// FIXME-DOCK: We are not exposing nor using split_outer.
20398ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
20399{
20400 ImGuiContext& g = *GImGui;
20401 IM_ASSERT(split_dir != ImGuiDir_None);
20402 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
20403
20404 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id);
20405 if (node == NULL)
20406 {
20407 IM_ASSERT(node != NULL);
20408 return 0;
20409 }
20410
20411 ImGuiDockRequest req;
20412 req.Type = ImGuiDockRequestType_Split;
20413 req.DockTargetWindow = NULL;
20414 req.DockTargetNode = node;
20415 req.DockPayload = NULL;
20416 req.DockSplitDir = split_dir;
20417 req.DockSplitRatio = ImSaturate(f: (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
20418 req.DockSplitOuter = false;
20419 DockContextProcessDock(ctx: &g, req: &req);
20420
20421 ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
20422 ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
20423 if (out_id_at_dir)
20424 *out_id_at_dir = id_at_dir;
20425 if (out_id_at_opposite_dir)
20426 *out_id_at_opposite_dir = id_at_opposite_dir;
20427 return id_at_dir;
20428}
20429
20430static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
20431{
20432 ImGuiContext& g = *GImGui;
20433 ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx: &g, id: dst_node_id_if_known);
20434 dst_node->SharedFlags = src_node->SharedFlags;
20435 dst_node->LocalFlags = src_node->LocalFlags;
20436 dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
20437 dst_node->Pos = src_node->Pos;
20438 dst_node->Size = src_node->Size;
20439 dst_node->SizeRef = src_node->SizeRef;
20440 dst_node->SplitAxis = src_node->SplitAxis;
20441 dst_node->UpdateMergedFlags();
20442
20443 out_node_remap_pairs->push_back(v: src_node->ID);
20444 out_node_remap_pairs->push_back(v: dst_node->ID);
20445
20446 for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
20447 if (src_node->ChildNodes[child_n])
20448 {
20449 dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node: src_node->ChildNodes[child_n], dst_node_id_if_known: 0, out_node_remap_pairs);
20450 dst_node->ChildNodes[child_n]->ParentNode = dst_node;
20451 }
20452
20453 IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
20454 return dst_node;
20455}
20456
20457void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
20458{
20459 ImGuiContext& g = *GImGui;
20460 IM_ASSERT(src_node_id != 0);
20461 IM_ASSERT(dst_node_id != 0);
20462 IM_ASSERT(out_node_remap_pairs != NULL);
20463
20464 DockBuilderRemoveNode(node_id: dst_node_id);
20465
20466 ImGuiDockNode* src_node = DockContextFindNodeByID(ctx: &g, id: src_node_id);
20467 IM_ASSERT(src_node != NULL);
20468
20469 out_node_remap_pairs->clear();
20470 DockBuilderCopyNodeRec(src_node, dst_node_id_if_known: dst_node_id, out_node_remap_pairs);
20471
20472 IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
20473}
20474
20475void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
20476{
20477 ImGuiWindow* src_window = FindWindowByName(name: src_name);
20478 if (src_window == NULL)
20479 return;
20480 if (ImGuiWindow* dst_window = FindWindowByName(name: dst_name))
20481 {
20482 dst_window->Pos = src_window->Pos;
20483 dst_window->Size = src_window->Size;
20484 dst_window->SizeFull = src_window->SizeFull;
20485 dst_window->Collapsed = src_window->Collapsed;
20486 }
20487 else
20488 {
20489 ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(id: ImHashStr(data_p: dst_name));
20490 if (!dst_settings)
20491 dst_settings = CreateNewWindowSettings(name: dst_name);
20492 ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
20493 if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
20494 {
20495 dst_settings->ViewportPos = window_pos_2ih;
20496 dst_settings->ViewportId = src_window->ViewportId;
20497 dst_settings->Pos = ImVec2ih(0, 0);
20498 }
20499 else
20500 {
20501 dst_settings->Pos = window_pos_2ih;
20502 }
20503 dst_settings->Size = ImVec2ih(src_window->SizeFull);
20504 dst_settings->Collapsed = src_window->Collapsed;
20505 }
20506}
20507
20508// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
20509void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
20510{
20511 ImGuiContext& g = *GImGui;
20512 IM_ASSERT(src_dockspace_id != 0);
20513 IM_ASSERT(dst_dockspace_id != 0);
20514 IM_ASSERT(in_window_remap_pairs != NULL);
20515 IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
20516
20517 // Duplicate entire dock
20518 // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
20519 // whereas we could attempt to at least keep them together in a new, same floating node.
20520 ImVector<ImGuiID> node_remap_pairs;
20521 DockBuilderCopyNode(src_node_id: src_dockspace_id, dst_node_id: dst_dockspace_id, out_node_remap_pairs: &node_remap_pairs);
20522
20523 // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
20524 // (The windows associated to src_dockspace_id are staying in place)
20525 ImVector<ImGuiID> src_windows;
20526 for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
20527 {
20528 const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
20529 const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
20530 ImGuiID src_window_id = ImHashStr(data_p: src_window_name);
20531 src_windows.push_back(v: src_window_id);
20532
20533 // Search in the remapping tables
20534 ImGuiID src_dock_id = 0;
20535 if (ImGuiWindow* src_window = FindWindowByID(id: src_window_id))
20536 src_dock_id = src_window->DockId;
20537 else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(id: src_window_id))
20538 src_dock_id = src_window_settings->DockId;
20539 ImGuiID dst_dock_id = 0;
20540 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
20541 if (node_remap_pairs[dock_remap_n] == src_dock_id)
20542 {
20543 dst_dock_id = node_remap_pairs[dock_remap_n + 1];
20544 //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
20545 break;
20546 }
20547
20548 if (dst_dock_id != 0)
20549 {
20550 // Docked windows gets redocked into the new node hierarchy.
20551 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
20552 DockBuilderDockWindow(window_name: dst_window_name, node_id: dst_dock_id);
20553 }
20554 else
20555 {
20556 // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
20557 // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
20558 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
20559 DockBuilderCopyWindowSettings(src_name: src_window_name, dst_name: dst_window_name);
20560 }
20561 }
20562
20563 // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
20564 // Find those windows and move to them to the cloned dock node. This may be optional?
20565 // Dock those are a second step as undocking would invalidate source dock nodes.
20566 struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
20567 ImVector<DockRemainingWindowTask> dock_remaining_windows;
20568 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
20569 if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
20570 {
20571 ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
20572 ImGuiDockNode* node = DockBuilderGetNode(node_id: src_dock_id);
20573 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
20574 {
20575 ImGuiWindow* window = node->Windows[window_n];
20576 if (src_windows.contains(v: window->ID))
20577 continue;
20578
20579 // Docked windows gets redocked into the new node hierarchy.
20580 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
20581 dock_remaining_windows.push_back(v: DockRemainingWindowTask(window, dst_dock_id));
20582 }
20583 }
20584 for (const DockRemainingWindowTask& task : dock_remaining_windows)
20585 DockBuilderDockWindow(window_name: task.Window->Name, node_id: task.DockId);
20586}
20587
20588// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
20589void ImGui::DockBuilderFinish(ImGuiID root_id)
20590{
20591 ImGuiContext& g = *GImGui;
20592 //DockContextRebuild(&g);
20593 DockContextBuildAddWindowsToNodes(ctx: &g, root_id);
20594}
20595
20596//-----------------------------------------------------------------------------
20597// Docking: Begin/End Support Functions (called from Begin/End)
20598//-----------------------------------------------------------------------------
20599// - GetWindowAlwaysWantOwnTabBar()
20600// - DockContextBindNodeToWindow()
20601// - BeginDocked()
20602// - BeginDockableDragDropSource()
20603// - BeginDockableDragDropTarget()
20604//-----------------------------------------------------------------------------
20605
20606bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
20607{
20608 ImGuiContext& g = *GImGui;
20609 if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
20610 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
20611 if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
20612 return true;
20613 return false;
20614}
20615
20616static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
20617{
20618 ImGuiContext& g = *ctx;
20619 ImGuiDockNode* node = DockContextFindNodeByID(ctx, id: window->DockId);
20620 IM_ASSERT(window->DockNode == NULL);
20621
20622 // We should not be docking into a split node (SetWindowDock should avoid this)
20623 if (node && node->IsSplitNode())
20624 {
20625 DockContextProcessUndockWindow(ctx, window);
20626 return NULL;
20627 }
20628
20629 // Create node
20630 if (node == NULL)
20631 {
20632 node = DockContextAddNode(ctx, id: window->DockId);
20633 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
20634 node->LastFrameAlive = g.FrameCount;
20635 }
20636
20637 // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
20638 // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
20639 // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
20640 // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
20641 if (!node->IsVisible)
20642 {
20643 ImGuiDockNode* ancestor_node = node;
20644 while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
20645 ancestor_node = ancestor_node->ParentNode;
20646 IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
20647 DockNodeUpdateHasCentralNodeChild(node: DockNodeGetRootNode(node: ancestor_node));
20648 DockNodeTreeUpdatePosSize(node: ancestor_node, pos: ancestor_node->Pos, size: ancestor_node->Size, only_write_to_single_node: node);
20649 }
20650
20651 // Add window to node
20652 bool node_was_visible = node->IsVisible;
20653 DockNodeAddWindow(node, window, add_to_tab_bar: true);
20654 node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
20655 IM_ASSERT(node == window->DockNode);
20656 return node;
20657}
20658
20659static void StoreDockStyleForWindow(ImGuiWindow* window)
20660{
20661 ImGuiContext& g = *GImGui;
20662 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
20663 window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(in: g.Style.Colors[GWindowDockStyleColors[color_n]]);
20664}
20665
20666void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
20667{
20668 ImGuiContext& g = *GImGui;
20669
20670 // Clear fields ahead so most early-out paths don't have to do it
20671 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
20672
20673 const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
20674 if (auto_dock_node)
20675 {
20676 if (window->DockId == 0)
20677 {
20678 IM_ASSERT(window->DockNode == NULL);
20679 window->DockId = DockContextGenNodeID(ctx: &g);
20680 }
20681 }
20682 else
20683 {
20684 // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
20685 bool want_undock = false;
20686 want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
20687 want_undock |= (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
20688 if (want_undock)
20689 {
20690 DockContextProcessUndockWindow(ctx: &g, window);
20691 return;
20692 }
20693 }
20694
20695 // Bind to our dock node
20696 ImGuiDockNode* node = window->DockNode;
20697 if (node != NULL)
20698 IM_ASSERT(window->DockId == node->ID);
20699 if (window->DockId != 0 && node == NULL)
20700 {
20701 node = DockContextBindNodeToWindow(ctx: &g, window);
20702 if (node == NULL)
20703 return;
20704 }
20705
20706#if 0
20707 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
20708 if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
20709 {
20710 DockContextProcessUndockWindow(ctx, window);
20711 return;
20712 }
20713#endif
20714
20715 // Undock if our dockspace node disappeared
20716 // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
20717 if (node->LastFrameAlive < g.FrameCount)
20718 {
20719 // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
20720 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
20721 if (root_node->LastFrameAlive < g.FrameCount)
20722 DockContextProcessUndockWindow(ctx: &g, window);
20723 else
20724 window->DockIsActive = true;
20725 return;
20726 }
20727
20728 // Store style overrides
20729 StoreDockStyleForWindow(window);
20730
20731 // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
20732 // and never create neither a host window neither a tab bar.
20733 // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
20734 if (node->HostWindow == NULL)
20735 {
20736 if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
20737 window->DockIsActive = true;
20738 if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
20739 DockNodeHideWindowDuringHostWindowCreation(window);
20740 return;
20741 }
20742
20743 // We can have zero-sized nodes (e.g. children of a small-size dockspace)
20744 IM_ASSERT(node->HostWindow);
20745 IM_ASSERT(node->IsLeafNode());
20746 IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
20747 node->State = ImGuiDockNodeState_HostWindowVisible;
20748
20749 // Undock if we are submitted earlier than the host window
20750 if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
20751 {
20752 DockContextProcessUndockWindow(ctx: &g, window);
20753 return;
20754 }
20755
20756 // Position/Size window
20757 SetNextWindowPos(pos: node->Pos);
20758 SetNextWindowSize(size: node->Size);
20759 g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
20760 window->DockIsActive = true;
20761 window->DockNodeIsVisible = true;
20762 window->DockTabIsVisible = false;
20763 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
20764 return;
20765
20766 // When the window is selected we mark it as visible.
20767 if (node->VisibleWindow == window)
20768 window->DockTabIsVisible = true;
20769
20770 // Update window flag
20771 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
20772 window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
20773 window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
20774 if (node->IsHiddenTabBar() || node->IsNoTabBar())
20775 window->Flags |= ImGuiWindowFlags_NoTitleBar;
20776 else
20777 window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
20778
20779 // Save new dock order only if the window has been visible once already
20780 // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
20781 if (node->TabBar && window->WasActive)
20782 window->DockOrder = (short)DockNodeGetTabOrder(window);
20783
20784 if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
20785 *p_open = false;
20786
20787 // Update ChildId to allow returning from Child to Parent with Escape
20788 ImGuiWindow* parent_window = window->DockNode->HostWindow;
20789 window->ChildId = parent_window->GetID(str: window->Name);
20790}
20791
20792void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
20793{
20794 ImGuiContext& g = *GImGui;
20795 IM_ASSERT(g.ActiveId == window->MoveId);
20796 IM_ASSERT(g.MovingWindow == window);
20797 IM_ASSERT(g.CurrentWindow == window);
20798
20799 // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
20800 if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
20801 {
20802 // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
20803 // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
20804 // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
20805 IM_ASSERT(g.NextWindowData.HasFlags == 0);
20806 if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
20807 SetTooltip("%s", LocalizeGetMsg(key: ImGuiLocKey_DockingHoldShiftToDock));
20808 return;
20809 }
20810
20811 g.LastItemData.ID = window->MoveId;
20812 window = window->RootWindowDockTree;
20813 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
20814 bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(p: g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
20815 ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
20816 if (is_drag_docking && BeginDragDropSource(flags: drag_drop_flags))
20817 {
20818 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, data: &window, data_size: sizeof(window));
20819 EndDragDropSource();
20820 StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
20821 }
20822}
20823
20824void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
20825{
20826 ImGuiContext& g = *GImGui;
20827
20828 //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
20829 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
20830 if (!g.DragDropActive)
20831 return;
20832 //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20833 if (!BeginDragDropTargetCustom(bb: window->Rect(), id: window->ID))
20834 return;
20835
20836 // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
20837 // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
20838 const ImGuiPayload* payload = &g.DragDropPayload;
20839 if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(host_window: window, root_payload: *(ImGuiWindow**)payload->Data))
20840 {
20841 EndDragDropTarget();
20842 return;
20843 }
20844
20845 ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
20846 if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, flags: ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
20847 {
20848 // Select target node
20849 // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
20850 bool dock_into_floating_window = false;
20851 ImGuiDockNode* node = NULL;
20852 if (window->DockNodeAsHost)
20853 {
20854 // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
20855 node = DockNodeTreeFindVisibleNodeByPos(node: window->DockNodeAsHost, pos: g.IO.MousePos);
20856
20857 // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
20858 // In this case we need to fallback into any leaf mode, possibly the central node.
20859 // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
20860 if (node && node->IsDockSpace() && node->IsRootNode())
20861 node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
20862 }
20863 else
20864 {
20865 if (window->DockNode)
20866 node = window->DockNode;
20867 else
20868 dock_into_floating_window = true; // Dock into a regular window
20869 }
20870
20871 const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
20872 const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(r_min: explicit_target_rect.Min, r_max: explicit_target_rect.Max);
20873
20874 // Preview docking request and find out split direction/ratio
20875 //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
20876 const bool do_preview = payload->IsPreview() || payload->IsDelivery();
20877 if (do_preview && (node != NULL || dock_into_floating_window))
20878 {
20879 // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
20880 ImGuiDockPreviewData split_inner;
20881 ImGuiDockPreviewData split_outer;
20882 ImGuiDockPreviewData* split_data = &split_inner;
20883 if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
20884 if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
20885 {
20886 DockNodePreviewDockSetup(host_window: window, host_node: root_node, payload_window, NULL, data: &split_outer, is_explicit_target, is_outer_docking: true);
20887 if (split_outer.IsSplitDirExplicit)
20888 split_data = &split_outer;
20889 }
20890 if (!node || node->IsLeafNode())
20891 DockNodePreviewDockSetup(host_window: window, host_node: node, payload_window, NULL, data: &split_inner, is_explicit_target, is_outer_docking: false);
20892 if (split_data == &split_outer)
20893 split_inner.IsDropAllowed = false;
20894
20895 // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
20896 DockNodePreviewDockRender(host_window: window, host_node: node, root_payload: payload_window, data: &split_inner);
20897 DockNodePreviewDockRender(host_window: window, host_node: node, root_payload: payload_window, data: &split_outer);
20898
20899 // Queue docking request
20900 if (split_data->IsDropAllowed && payload->IsDelivery())
20901 DockContextQueueDock(ctx: &g, target: window, target_node: split_data->SplitNode, payload: payload_window, split_dir: split_data->SplitDir, split_ratio: split_data->SplitRatio, split_outer: split_data == &split_outer);
20902 }
20903 }
20904 EndDragDropTarget();
20905}
20906
20907//-----------------------------------------------------------------------------
20908// Docking: Settings
20909//-----------------------------------------------------------------------------
20910// - DockSettingsRenameNodeReferences()
20911// - DockSettingsRemoveNodeReferences()
20912// - DockSettingsFindNodeSettings()
20913// - DockSettingsHandler_ApplyAll()
20914// - DockSettingsHandler_ReadOpen()
20915// - DockSettingsHandler_ReadLine()
20916// - DockSettingsHandler_DockNodeToSettings()
20917// - DockSettingsHandler_WriteAll()
20918//-----------------------------------------------------------------------------
20919
20920static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
20921{
20922 ImGuiContext& g = *GImGui;
20923 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
20924 for (int window_n = 0; window_n < g.Windows.Size; window_n++)
20925 {
20926 ImGuiWindow* window = g.Windows[window_n];
20927 if (window->DockId == old_node_id && window->DockNode == NULL)
20928 window->DockId = new_node_id;
20929 }
20930 //// FIXME-OPT: We could remove this loop by storing the index in the map
20931 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
20932 if (settings->DockId == old_node_id)
20933 settings->DockId = new_node_id;
20934}
20935
20936// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
20937static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
20938{
20939 ImGuiContext& g = *GImGui;
20940 int found = 0;
20941 //// FIXME-OPT: We could remove this loop by storing the index in the map
20942 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
20943 for (int node_n = 0; node_n < node_ids_count; node_n++)
20944 if (settings->DockId == node_ids[node_n])
20945 {
20946 settings->DockId = 0;
20947 settings->DockOrder = -1;
20948 if (++found < node_ids_count)
20949 break;
20950 return;
20951 }
20952}
20953
20954static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
20955{
20956 // FIXME-OPT
20957 ImGuiDockContext* dc = &ctx->DockContext;
20958 for (int n = 0; n < dc->NodesSettings.Size; n++)
20959 if (dc->NodesSettings[n].ID == id)
20960 return &dc->NodesSettings[n];
20961 return NULL;
20962}
20963
20964// Clear settings data
20965static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
20966{
20967 ImGuiDockContext* dc = &ctx->DockContext;
20968 dc->NodesSettings.clear();
20969 DockContextClearNodes(ctx, root_id: 0, clear_settings_refs: true);
20970}
20971
20972// Recreate nodes based on settings data
20973static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
20974{
20975 // Prune settings at boot time only
20976 ImGuiDockContext* dc = &ctx->DockContext;
20977 if (ctx->Windows.Size == 0)
20978 DockContextPruneUnusedSettingsNodes(ctx);
20979 DockContextBuildNodesFromSettings(ctx, node_settings_array: dc->NodesSettings.Data, node_settings_count: dc->NodesSettings.Size);
20980 DockContextBuildAddWindowsToNodes(ctx, root_id: 0);
20981}
20982
20983static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
20984{
20985 if (strcmp(s1: name, s2: "Data") != 0)
20986 return NULL;
20987 return (void*)1;
20988}
20989
20990static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
20991{
20992 char c = 0;
20993 int x = 0, y = 0;
20994 int r = 0;
20995
20996 // Parsing, e.g.
20997 // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
20998 // " DockNode ID=0x00000002 Parent=0x00000001 "
20999 // Important: this code expect currently fields in a fixed order.
21000 ImGuiDockNodeSettings node;
21001 line = ImStrSkipBlank(str: line);
21002 if (strncmp(s1: line, s2: "DockNode", n: 8) == 0) { line = ImStrSkipBlank(str: line + strlen(s: "DockNode")); }
21003 else if (strncmp(s1: line, s2: "DockSpace", n: 9) == 0) { line = ImStrSkipBlank(str: line + strlen(s: "DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
21004 else return;
21005 if (sscanf(s: line, format: "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
21006 if (sscanf(s: line, format: " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
21007 if (sscanf(s: line, format: " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
21008 if (node.ParentNodeId == 0)
21009 {
21010 if (sscanf(s: line, format: " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
21011 if (sscanf(s: line, format: " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
21012 }
21013 else
21014 {
21015 if (sscanf(s: line, format: " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
21016 }
21017 if (sscanf(s: line, format: " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
21018 if (sscanf(s: line, format: " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
21019 if (sscanf(s: line, format: " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
21020 if (sscanf(s: line, format: " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
21021 if (sscanf(s: line, format: " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
21022 if (sscanf(s: line, format: " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
21023 if (sscanf(s: line, format: " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
21024 if (sscanf(s: line, format: " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
21025 if (node.ParentNodeId != 0)
21026 if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, id: node.ParentNodeId))
21027 node.Depth = parent_settings->Depth + 1;
21028 ctx->DockContext.NodesSettings.push_back(v: node);
21029}
21030
21031static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
21032{
21033 ImGuiDockNodeSettings node_settings;
21034 IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
21035 node_settings.ID = node->ID;
21036 node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
21037 node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
21038 node_settings.SelectedTabId = node->SelectedTabId;
21039 node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
21040 node_settings.Depth = (char)depth;
21041 node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
21042 node_settings.Pos = ImVec2ih(node->Pos);
21043 node_settings.Size = ImVec2ih(node->Size);
21044 node_settings.SizeRef = ImVec2ih(node->SizeRef);
21045 dc->NodesSettings.push_back(v: node_settings);
21046 if (node->ChildNodes[0])
21047 DockSettingsHandler_DockNodeToSettings(dc, node: node->ChildNodes[0], depth: depth + 1);
21048 if (node->ChildNodes[1])
21049 DockSettingsHandler_DockNodeToSettings(dc, node: node->ChildNodes[1], depth: depth + 1);
21050}
21051
21052static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
21053{
21054 ImGuiContext& g = *ctx;
21055 ImGuiDockContext* dc = &ctx->DockContext;
21056 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
21057 return;
21058
21059 // Gather settings data
21060 // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
21061 dc->NodesSettings.resize(new_size: 0);
21062 dc->NodesSettings.reserve(new_capacity: dc->Nodes.Data.Size);
21063 for (int n = 0; n < dc->Nodes.Data.Size; n++)
21064 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
21065 if (node->IsRootNode())
21066 DockSettingsHandler_DockNodeToSettings(dc, node, depth: 0);
21067
21068 int max_depth = 0;
21069 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
21070 max_depth = ImMax(lhs: (int)dc->NodesSettings[node_n].Depth, rhs: max_depth);
21071
21072 // Write to text buffer
21073 buf->appendf(fmt: "[%s][Data]\n", handler->TypeName);
21074 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
21075 {
21076 const int line_start_pos = buf->size(); (void)line_start_pos;
21077 const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
21078 buf->appendf(fmt: "%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file
21079 buf->appendf(fmt: " ID=0x%08X", node_settings->ID);
21080 if (node_settings->ParentNodeId)
21081 {
21082 buf->appendf(fmt: " Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
21083 }
21084 else
21085 {
21086 if (node_settings->ParentWindowId)
21087 buf->appendf(fmt: " Window=0x%08X", node_settings->ParentWindowId);
21088 buf->appendf(fmt: " Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
21089 }
21090 if (node_settings->SplitAxis != ImGuiAxis_None)
21091 buf->appendf(fmt: " Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
21092 if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
21093 buf->appendf(fmt: " NoResize=1");
21094 if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
21095 buf->appendf(fmt: " CentralNode=1");
21096 if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
21097 buf->appendf(fmt: " NoTabBar=1");
21098 if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
21099 buf->appendf(fmt: " HiddenTabBar=1");
21100 if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
21101 buf->appendf(fmt: " NoWindowMenuButton=1");
21102 if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
21103 buf->appendf(fmt: " NoCloseButton=1");
21104 if (node_settings->SelectedTabId)
21105 buf->appendf(fmt: " Selected=0x%08X", node_settings->SelectedTabId);
21106
21107 // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
21108 if (g.IO.ConfigDebugIniSettings)
21109 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, id: node_settings->ID))
21110 {
21111 buf->appendf(fmt: "%*s", ImMax(lhs: 2, rhs: (line_start_pos + 92) - buf->size()), ""); // Align everything
21112 if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
21113 buf->appendf(fmt: " ; in '%s'", node->HostWindow->ParentWindow->Name);
21114 // Iterate settings so we can give info about windows that didn't exist during the session.
21115 int contains_window = 0;
21116 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
21117 if (settings->DockId == node_settings->ID)
21118 {
21119 if (contains_window++ == 0)
21120 buf->appendf(fmt: " ; contains ");
21121 buf->appendf(fmt: "'%s' ", settings->GetName());
21122 }
21123 }
21124
21125 buf->appendf(fmt: "\n");
21126 }
21127 buf->appendf(fmt: "\n");
21128}
21129
21130
21131//-----------------------------------------------------------------------------
21132// [SECTION] PLATFORM DEPENDENT HELPERS
21133//-----------------------------------------------------------------------------
21134// - Default clipboard handlers
21135// - Default shell function handlers
21136// - Default IME handlers
21137//-----------------------------------------------------------------------------
21138
21139#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
21140
21141#ifdef _MSC_VER
21142#pragma comment(lib, "user32")
21143#pragma comment(lib, "kernel32")
21144#endif
21145
21146// Win32 clipboard implementation
21147// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
21148static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21149{
21150 ImGuiContext& g = *ctx;
21151 g.ClipboardHandlerData.clear();
21152 if (!::OpenClipboard(NULL))
21153 return NULL;
21154 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
21155 if (wbuf_handle == NULL)
21156 {
21157 ::CloseClipboard();
21158 return NULL;
21159 }
21160 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
21161 {
21162 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
21163 g.ClipboardHandlerData.resize(buf_len);
21164 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
21165 }
21166 ::GlobalUnlock(wbuf_handle);
21167 ::CloseClipboard();
21168 return g.ClipboardHandlerData.Data;
21169}
21170
21171static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
21172{
21173 if (!::OpenClipboard(NULL))
21174 return;
21175 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
21176 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
21177 if (wbuf_handle == NULL)
21178 {
21179 ::CloseClipboard();
21180 return;
21181 }
21182 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
21183 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
21184 ::GlobalUnlock(wbuf_handle);
21185 ::EmptyClipboard();
21186 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
21187 ::GlobalFree(wbuf_handle);
21188 ::CloseClipboard();
21189}
21190
21191#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
21192
21193#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
21194static PasteboardRef main_clipboard = 0;
21195
21196// OSX clipboard implementation
21197// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
21198static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
21199{
21200 if (!main_clipboard)
21201 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
21202 PasteboardClear(main_clipboard);
21203 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text));
21204 if (cf_data)
21205 {
21206 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
21207 CFRelease(cf_data);
21208 }
21209}
21210
21211static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21212{
21213 ImGuiContext& g = *ctx;
21214 if (!main_clipboard)
21215 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
21216 PasteboardSynchronize(main_clipboard);
21217
21218 ItemCount item_count = 0;
21219 PasteboardGetItemCount(main_clipboard, &item_count);
21220 for (ItemCount i = 0; i < item_count; i++)
21221 {
21222 PasteboardItemID item_id = 0;
21223 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
21224 CFArrayRef flavor_type_array = 0;
21225 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
21226 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
21227 {
21228 CFDataRef cf_data;
21229 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
21230 {
21231 g.ClipboardHandlerData.clear();
21232 int length = (int)CFDataGetLength(cf_data);
21233 g.ClipboardHandlerData.resize(length + 1);
21234 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
21235 g.ClipboardHandlerData[length] = 0;
21236 CFRelease(cf_data);
21237 return g.ClipboardHandlerData.Data;
21238 }
21239 }
21240 }
21241 return NULL;
21242}
21243
21244#else
21245
21246// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
21247static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21248{
21249 ImGuiContext& g = *ctx;
21250 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
21251}
21252
21253static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text)
21254{
21255 ImGuiContext& g = *ctx;
21256 g.ClipboardHandlerData.clear();
21257 const char* text_end = text + ImStrlen(s: text);
21258 g.ClipboardHandlerData.resize(new_size: (int)(text_end - text) + 1);
21259 memcpy(dest: &g.ClipboardHandlerData[0], src: text, n: (size_t)(text_end - text));
21260 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
21261}
21262
21263#endif // Default clipboard handlers
21264
21265//-----------------------------------------------------------------------------
21266
21267#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21268#if defined(__APPLE__) && TARGET_OS_IPHONE
21269#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21270#endif
21271#if defined(__3DS__)
21272#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21273#endif
21274#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
21275#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21276#endif
21277#endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21278
21279#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21280#ifdef _WIN32
21281#include <shellapi.h> // ShellExecuteA()
21282#ifdef _MSC_VER
21283#pragma comment(lib, "shell32")
21284#endif
21285static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
21286{
21287 const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
21288 ImVector<wchar_t> path_wbuf;
21289 path_wbuf.resize(path_wsize);
21290 ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize);
21291 return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32;
21292}
21293#else
21294#include <sys/wait.h>
21295#include <unistd.h>
21296static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
21297{
21298#if defined(__APPLE__)
21299 const char* args[] { "open", "--", path, NULL };
21300#else
21301 const char* args[] { "xdg-open", path, NULL };
21302#endif
21303 pid_t pid = fork();
21304 if (pid < 0)
21305 return false;
21306 if (!pid)
21307 {
21308 execvp(file: args[0], argv: const_cast<char **>(args));
21309 exit(status: -1);
21310 }
21311 else
21312 {
21313 int status;
21314 waitpid(pid: pid, stat_loc: &status, options: 0);
21315 return WEXITSTATUS(status) == 0;
21316 }
21317}
21318#endif
21319#else
21320static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
21321#endif // Default shell handlers
21322
21323//-----------------------------------------------------------------------------
21324
21325// Win32 API IME support (for Asian languages, etc.)
21326#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
21327
21328#include <imm.h>
21329#ifdef _MSC_VER
21330#pragma comment(lib, "imm32")
21331#endif
21332
21333static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
21334{
21335 // Notify OS Input Method Editor of text input position
21336 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
21337 if (hwnd == 0)
21338 return;
21339
21340 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
21341 if (HIMC himc = ::ImmGetContext(hwnd))
21342 {
21343 COMPOSITIONFORM composition_form = {};
21344 composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
21345 composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
21346 composition_form.dwStyle = CFS_FORCE_POSITION;
21347 ::ImmSetCompositionWindow(himc, &composition_form);
21348 CANDIDATEFORM candidate_form = {};
21349 candidate_form.dwStyle = CFS_CANDIDATEPOS;
21350 candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
21351 candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
21352 ::ImmSetCandidateWindow(himc, &candidate_form);
21353 ::ImmReleaseContext(hwnd, himc);
21354 }
21355}
21356
21357#else
21358
21359static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
21360
21361#endif // Default IME handlers
21362
21363//-----------------------------------------------------------------------------
21364// [SECTION] METRICS/DEBUGGER WINDOW
21365//-----------------------------------------------------------------------------
21366// - MetricsHelpMarker() [Internal]
21367// - DebugRenderViewportThumbnail() [Internal]
21368// - RenderViewportsThumbnails() [Internal]
21369// - DebugRenderKeyboardPreview() [Internal]
21370// - DebugTextEncoding()
21371// - DebugFlashStyleColorStop() [Internal]
21372// - DebugFlashStyleColor()
21373// - UpdateDebugToolFlashStyleColor() [Internal]
21374// - ShowFontAtlas() [Internal but called by Demo!]
21375// - DebugNodeTexture() [Internal]
21376// - ShowMetricsWindow()
21377// - DebugNodeColumns() [Internal]
21378// - DebugNodeDockNode() [Internal]
21379// - DebugNodeDrawList() [Internal]
21380// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
21381// - DebugNodeFont() [Internal]
21382// - DebugNodeFontGlyph() [Internal]
21383// - DebugNodeStorage() [Internal]
21384// - DebugNodeTabBar() [Internal]
21385// - DebugNodeViewport() [Internal]
21386// - DebugNodeWindow() [Internal]
21387// - DebugNodeWindowSettings() [Internal]
21388// - DebugNodeWindowsList() [Internal]
21389// - DebugNodeWindowsListByBeginStackParent() [Internal]
21390//-----------------------------------------------------------------------------
21391
21392#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
21393// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
21394static void MetricsHelpMarker(const char* desc)
21395{
21396 ImGui::TextDisabled(fmt: "(?)");
21397 if (ImGui::BeginItemTooltip())
21398 {
21399 ImGui::PushTextWrapPos(wrap_pos_x: ImGui::GetFontSize() * 35.0f);
21400 ImGui::TextUnformatted(text: desc);
21401 ImGui::PopTextWrapPos();
21402 ImGui::EndTooltip();
21403 }
21404}
21405#endif
21406
21407#ifndef IMGUI_DISABLE_DEBUG_TOOLS
21408
21409void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
21410{
21411 ImGuiContext& g = *GImGui;
21412 ImGuiWindow* window = g.CurrentWindow;
21413
21414 ImVec2 scale = bb.GetSize() / viewport->Size;
21415 ImVec2 off = bb.Min - viewport->Pos * scale;
21416 float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
21417 window->DrawList->AddRectFilled(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul: alpha_mul * 0.40f));
21418 for (ImGuiWindow* thumb_window : g.Windows)
21419 {
21420 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
21421 continue;
21422 if (thumb_window->Viewport != viewport)
21423 continue;
21424
21425 ImRect thumb_r = thumb_window->Rect();
21426 ImRect title_r = thumb_window->TitleBarRect();
21427 thumb_r = ImRect(ImTrunc(v: off + thumb_r.Min * scale), ImTrunc(v: off + thumb_r.Max * scale));
21428 title_r = ImRect(ImTrunc(v: off + title_r.Min * scale), ImTrunc(v: off + ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
21429 thumb_r.ClipWithFull(r: bb);
21430 title_r.ClipWithFull(r: bb);
21431 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
21432 window->DrawList->AddRectFilled(p_min: thumb_r.Min, p_max: thumb_r.Max, col: GetColorU32(idx: ImGuiCol_WindowBg, alpha_mul));
21433 window->DrawList->AddRectFilled(p_min: title_r.Min, p_max: title_r.Max, col: GetColorU32(idx: window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
21434 window->DrawList->AddRect(p_min: thumb_r.Min, p_max: thumb_r.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul));
21435 window->DrawList->AddText(font: g.Font, font_size: g.FontSize * 1.0f, pos: title_r.Min, col: GetColorU32(idx: ImGuiCol_Text, alpha_mul), text_begin: thumb_window->Name, text_end: FindRenderedTextEnd(text: thumb_window->Name));
21436 }
21437 draw_list->AddRect(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul));
21438 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
21439 window->DrawList->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
21440}
21441
21442static void RenderViewportsThumbnails()
21443{
21444 ImGuiContext& g = *GImGui;
21445 ImGuiWindow* window = g.CurrentWindow;
21446
21447 // Draw monitor and calculate their boundaries
21448 float SCALE = 1.0f / 8.0f;
21449 ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21450 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
21451 bb_full.Add(r: ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
21452 ImVec2 p = window->DC.CursorPos;
21453 ImVec2 off = p - bb_full.Min * SCALE;
21454 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
21455 {
21456 ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
21457 window->DrawList->AddRect(p_min: monitor_draw_bb.Min, p_max: monitor_draw_bb.Max, col: (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(it: &monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(idx: ImGuiCol_Border), rounding: 4.0f);
21458 window->DrawList->AddRectFilled(p_min: monitor_draw_bb.Min, p_max: monitor_draw_bb.Max, col: ImGui::GetColorU32(idx: ImGuiCol_Border, alpha_mul: 0.10f), rounding: 4.0f);
21459 }
21460
21461 // Draw viewports
21462 for (ImGuiViewportP* viewport : g.Viewports)
21463 {
21464 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
21465 ImGui::DebugRenderViewportThumbnail(draw_list: window->DrawList, viewport, bb: viewport_draw_bb);
21466 }
21467 ImGui::Dummy(size: bb_full.GetSize() * SCALE);
21468}
21469
21470static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
21471{
21472 const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
21473 const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
21474 return b->LastFocusedStampCount - a->LastFocusedStampCount;
21475}
21476
21477// Draw an arbitrary US keyboard layout to visualize translated keys
21478void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
21479{
21480 const float scale = ImGui::GetFontSize() / 13.0f;
21481 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
21482 const float key_rounding = 3.0f * scale;
21483 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
21484 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
21485 const float key_face_rounding = 2.0f * scale;
21486 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
21487 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
21488 const float key_row_offset = 9.0f * scale;
21489
21490 ImVec2 board_min = GetCursorScreenPos();
21491 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);
21492 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
21493
21494 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
21495 const KeyLayoutData keys_to_display[] =
21496 {
21497 { .Row: 0, .Col: 0, .Label: "", .Key: ImGuiKey_Tab }, { .Row: 0, .Col: 1, .Label: "Q", .Key: ImGuiKey_Q }, { .Row: 0, .Col: 2, .Label: "W", .Key: ImGuiKey_W }, { .Row: 0, .Col: 3, .Label: "E", .Key: ImGuiKey_E }, { .Row: 0, .Col: 4, .Label: "R", .Key: ImGuiKey_R },
21498 { .Row: 1, .Col: 0, .Label: "", .Key: ImGuiKey_CapsLock }, { .Row: 1, .Col: 1, .Label: "A", .Key: ImGuiKey_A }, { .Row: 1, .Col: 2, .Label: "S", .Key: ImGuiKey_S }, { .Row: 1, .Col: 3, .Label: "D", .Key: ImGuiKey_D }, { .Row: 1, .Col: 4, .Label: "F", .Key: ImGuiKey_F },
21499 { .Row: 2, .Col: 0, .Label: "", .Key: ImGuiKey_LeftShift },{ .Row: 2, .Col: 1, .Label: "Z", .Key: ImGuiKey_Z }, { .Row: 2, .Col: 2, .Label: "X", .Key: ImGuiKey_X }, { .Row: 2, .Col: 3, .Label: "C", .Key: ImGuiKey_C }, { .Row: 2, .Col: 4, .Label: "V", .Key: ImGuiKey_V }
21500 };
21501
21502 // Elements rendered manually via ImDrawList API are not clipped automatically.
21503 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
21504 Dummy(size: board_max - board_min);
21505 if (!IsItemVisible())
21506 return;
21507 draw_list->PushClipRect(clip_rect_min: board_min, clip_rect_max: board_max, intersect_with_current_clip_rect: true);
21508 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
21509 {
21510 const KeyLayoutData* key_data = &keys_to_display[n];
21511 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);
21512 ImVec2 key_max = key_min + key_size;
21513 draw_list->AddRectFilled(p_min: key_min, p_max: key_max, IM_COL32(204, 204, 204, 255), rounding: key_rounding);
21514 draw_list->AddRect(p_min: key_min, p_max: key_max, IM_COL32(24, 24, 24, 255), rounding: key_rounding);
21515 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
21516 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
21517 draw_list->AddRect(p_min: face_min, p_max: face_max, IM_COL32(193, 193, 193, 255), rounding: key_face_rounding, flags: ImDrawFlags_None, thickness: 2.0f);
21518 draw_list->AddRectFilled(p_min: face_min, p_max: face_max, IM_COL32(252, 252, 252, 255), rounding: key_face_rounding);
21519 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
21520 draw_list->AddText(pos: label_min, IM_COL32(64, 64, 64, 255), text_begin: key_data->Label);
21521 if (IsKeyDown(key: key_data->Key))
21522 draw_list->AddRectFilled(p_min: key_min, p_max: key_max, IM_COL32(255, 0, 0, 128), rounding: key_rounding);
21523 }
21524 draw_list->PopClipRect();
21525}
21526
21527// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
21528void ImGui::DebugTextEncoding(const char* str)
21529{
21530 Text(fmt: "Text: \"%s\"", str);
21531 if (!BeginTable(str_id: "##DebugTextEncoding", columns: 4, flags: ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
21532 return;
21533 TableSetupColumn(label: "Offset");
21534 TableSetupColumn(label: "UTF-8");
21535 TableSetupColumn(label: "Glyph");
21536 TableSetupColumn(label: "Codepoint");
21537 TableHeadersRow();
21538 for (const char* p = str; *p != 0; )
21539 {
21540 unsigned int c;
21541 const int c_utf8_len = ImTextCharFromUtf8(out_char: &c, in_text: p, NULL);
21542 TableNextColumn();
21543 Text(fmt: "%d", (int)(p - str));
21544 TableNextColumn();
21545 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
21546 {
21547 if (byte_index > 0)
21548 SameLine();
21549 Text(fmt: "0x%02X", (int)(unsigned char)p[byte_index]);
21550 }
21551 TableNextColumn();
21552 TextUnformatted(text: p, text_end: p + c_utf8_len);
21553 if (!GetFont()->IsGlyphInFont(c: (ImWchar)c))
21554 {
21555 SameLine();
21556 TextUnformatted(text: "[missing]");
21557 }
21558 TableNextColumn();
21559 Text(fmt: "U+%04X", (int)c);
21560 p += c_utf8_len;
21561 }
21562 EndTable();
21563}
21564
21565static void DebugFlashStyleColorStop()
21566{
21567 ImGuiContext& g = *GImGui;
21568 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
21569 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
21570 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
21571}
21572
21573// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
21574void ImGui::DebugFlashStyleColor(ImGuiCol idx)
21575{
21576 ImGuiContext& g = *GImGui;
21577 DebugFlashStyleColorStop();
21578 g.DebugFlashStyleColorTime = 0.5f;
21579 g.DebugFlashStyleColorIdx = idx;
21580 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
21581}
21582
21583void ImGui::UpdateDebugToolFlashStyleColor()
21584{
21585 ImGuiContext& g = *GImGui;
21586 if (g.DebugFlashStyleColorTime <= 0.0f)
21587 return;
21588 ColorConvertHSVtoRGB(ImCos(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, s: 0.5f, v: 0.5f, out_r&: g.Style.Colors[g.DebugFlashStyleColorIdx].x, out_g&: g.Style.Colors[g.DebugFlashStyleColorIdx].y, out_b&: g.Style.Colors[g.DebugFlashStyleColorIdx].z);
21589 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
21590 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
21591 DebugFlashStyleColorStop();
21592}
21593
21594static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21595{
21596 union { void* ptr; int integer; } tex_id_opaque;
21597 memcpy(dest: &tex_id_opaque, src: &tex_id, n: ImMin(lhs: sizeof(void*), rhs: sizeof(tex_id)));
21598 if (sizeof(tex_id) >= sizeof(void*))
21599 ImFormatString(buf, buf_size, fmt: "0x%p", tex_id_opaque.ptr);
21600 else
21601 ImFormatString(buf, buf_size, fmt: "0x%04X", tex_id_opaque.integer);
21602 return buf;
21603}
21604
21605static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const ImDrawCmd* cmd)
21606{
21607 char* buf_end = buf + buf_size;
21608 if (cmd->TexRef._TexData != NULL)
21609 buf += ImFormatString(buf, buf_size: buf_end - buf, fmt: "#%03d: ", cmd->TexRef._TexData->UniqueID);
21610 return FormatTextureIDForDebugDisplay(buf, buf_size: (int)(buf_end - buf), tex_id: cmd->TexRef.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID()
21611}
21612
21613#ifdef IMGUI_ENABLE_FREETYPE
21614namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); }
21615#endif
21616
21617// [DEBUG] List fonts in a font atlas and display its texture
21618void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
21619{
21620 ImGuiContext& g = *GImGui;
21621 ImGuiIO& io = g.IO;
21622 ImGuiStyle& style = g.Style;
21623
21624 BeginDisabled();
21625 CheckboxFlags(label: "io.BackendFlags: RendererHasTextures", flags: &io.BackendFlags, flags_value: ImGuiBackendFlags_RendererHasTextures);
21626 EndDisabled();
21627 ShowFontSelector(label: "Font");
21628 //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0);
21629 if (DragFloat(label: "FontSizeBase", v: &style.FontSizeBase, v_speed: 0.20f, v_min: 5.0f, v_max: 100.0f, format: "%.0f"))
21630 style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work.
21631 SameLine(offset_from_start_x: 0.0f, spacing_w: 0.0f); Text(fmt: " (out %.2f)", GetFontSize());
21632 SameLine(); MetricsHelpMarker(desc: "- This is scaling font only. General scaling will come later.");
21633 DragFloat(label: "FontScaleMain", v: &style.FontScaleMain, v_speed: 0.02f, v_min: 0.5f, v_max: 4.0f);
21634 //BeginDisabled(io.ConfigDpiScaleFonts);
21635 DragFloat(label: "FontScaleDpi", v: &style.FontScaleDpi, v_speed: 0.02f, v_min: 0.5f, v_max: 4.0f);
21636 //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.");
21637 //EndDisabled();
21638 if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
21639 {
21640 BulletText(fmt: "Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!");
21641 BulletText(fmt: "For instructions, see:");
21642 SameLine();
21643 TextLinkOpenURL(label: "docs/BACKENDS.md", url: "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md");
21644 }
21645 BulletText(fmt: "Load a nice font for better results!");
21646 BulletText(fmt: "Please submit feedback:");
21647 SameLine(); TextLinkOpenURL(label: "#8465", url: "https://github.com/ocornut/imgui/issues/8465");
21648 BulletText(fmt: "Read FAQ for more details:");
21649 SameLine(); TextLinkOpenURL(label: "dearimgui.com/faq", url: "https://www.dearimgui.com/faq/");
21650 //EndDisabled();
21651
21652 SeparatorText(label: "Font List");
21653
21654 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21655 Checkbox(label: "Show font preview", v: &cfg->ShowFontPreview);
21656
21657 // Font loaders
21658 if (TreeNode(str_id: "Loader", fmt: "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL"))
21659 {
21660 const ImFontLoader* loader_current = atlas->FontLoader;
21661 BeginDisabled(disabled: !atlas->RendererHasTextures);
21662#ifdef IMGUI_ENABLE_STB_TRUETYPE
21663 const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype();
21664 if (RadioButton(label: "stb_truetype", active: loader_current == loader_stbtruetype))
21665 atlas->SetFontLoader(loader_stbtruetype);
21666#else
21667 BeginDisabled();
21668 RadioButton("stb_truetype", false);
21669 SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE");
21670 EndDisabled();
21671#endif
21672 SameLine();
21673#ifdef IMGUI_ENABLE_FREETYPE
21674 const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader();
21675 if (RadioButton("FreeType", loader_current == loader_freetype))
21676 atlas->SetFontLoader(loader_freetype);
21677 if (loader_current == loader_freetype)
21678 {
21679 unsigned int loader_flags = atlas->FontLoaderFlags;
21680 Text("Shared FreeType Loader Flags: 0x%08X", loader_flags);
21681 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
21682 {
21683 for (ImFont* font : atlas->Fonts)
21684 ImFontAtlasFontDestroyOutput(atlas, font);
21685 atlas->FontLoaderFlags = loader_flags;
21686 for (ImFont* font : atlas->Fonts)
21687 ImFontAtlasFontInitOutput(atlas, font);
21688 }
21689 }
21690#else
21691 BeginDisabled();
21692 RadioButton(label: "FreeType", active: false);
21693 SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp.");
21694 EndDisabled();
21695#endif
21696 EndDisabled();
21697 TreePop();
21698 }
21699
21700 // Font list
21701 for (ImFont* font : atlas->Fonts)
21702 {
21703 PushID(ptr_id: font);
21704 DebugNodeFont(font);
21705 PopID();
21706 }
21707
21708 SeparatorText(label: "Font Atlas");
21709 if (Button(label: "Compact"))
21710 atlas->CompactCache();
21711 SameLine();
21712 if (Button(label: "Grow"))
21713 ImFontAtlasTextureGrow(atlas);
21714 SameLine();
21715 if (Button(label: "Clear All"))
21716 ImFontAtlasBuildClear(atlas);
21717 SetItemTooltip("Destroy cache and custom rectangles.");
21718
21719 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
21720 {
21721 ImTextureData* tex = atlas->TexList[tex_n];
21722 if (tex_n > 0)
21723 SameLine();
21724 Text(fmt: "Tex: %dx%d", tex->Width, tex->Height);
21725 }
21726 const int packed_surface_sqrt = (int)sqrtf(x: (float)atlas->Builder->RectsPackedSurface);
21727 const int discarded_surface_sqrt = (int)sqrtf(x: (float)atlas->Builder->RectsDiscardedSurface);
21728 Text(fmt: "Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt);
21729 Text(fmt: "incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt);
21730
21731 ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid;
21732 if (TreeNode(str_id: "Rects Index", fmt: "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles
21733 {
21734 PushStyleVar(idx: ImGuiStyleVar_ImageBorderSize, val: 1.0f);
21735 if (BeginTable(str_id: "##table", columns: 2, flags: ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, outer_size: ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12)))
21736 {
21737 for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex)
21738 if (entry.IsUsed)
21739 {
21740 ImFontAtlasRectId id = ImFontAtlasRectId_Make(index_idx: atlas->Builder->RectsIndex.index_from_ptr(it: &entry), gen_idx: entry.Generation);
21741 ImFontAtlasRect r = {};
21742 atlas->GetCustomRect(id, out_r: &r);
21743 const char* buf;
21744 ImFormatStringToTempBuffer(out_buf: &buf, NULL, fmt: "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y);
21745 TableNextColumn();
21746 Selectable(label: buf);
21747 if (IsItemHovered())
21748 highlight_r_id = id;
21749 TableNextColumn();
21750 Image(tex_ref: atlas->TexRef, image_size: ImVec2(r.w, r.h), uv0: r.uv0, uv1: r.uv1);
21751 }
21752 EndTable();
21753 }
21754 PopStyleVar();
21755 TreePop();
21756 }
21757
21758 // Texture list
21759 // (ensure the last texture always use the same ID, so we can keep it open neatly)
21760 ImFontAtlasRect highlight_r;
21761 if (highlight_r_id != ImFontAtlasRectId_Invalid)
21762 atlas->GetCustomRect(id: highlight_r_id, out_r: &highlight_r);
21763 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
21764 {
21765 if (tex_n == atlas->TexList.Size - 1)
21766 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
21767 DebugNodeTexture(tex: atlas->TexList[tex_n], int_id: atlas->TexList.Size - 1 - tex_n, highlight_rect: (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL);
21768 }
21769}
21770
21771void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect)
21772{
21773 ImGuiContext& g = *GImGui;
21774 PushID(int_id);
21775 if (TreeNode(str_id: "", fmt: "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height))
21776 {
21777 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21778 Checkbox(label: "Show used rect", v: &cfg->ShowTextureUsedRect);
21779 PushStyleVar(idx: ImGuiStyleVar_ImageBorderSize, val: ImMax(lhs: 1.0f, rhs: g.Style.ImageBorderSize));
21780 ImVec2 p = GetCursorScreenPos();
21781 if (tex->WantDestroyNextFrame)
21782 Dummy(size: ImVec2((float)tex->Width, (float)tex->Height));
21783 else
21784 ImageWithBg(tex_ref: tex->GetTexRef(), image_size: ImVec2((float)tex->Width, (float)tex->Height), uv0: ImVec2(0.0f, 0.0f), uv1: ImVec2(1.0f, 1.0f), bg_col: ImVec4(0.0f, 0.0f, 0.0f, 1.0f));
21785 if (cfg->ShowTextureUsedRect)
21786 GetWindowDrawList()->AddRect(p_min: ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), p_max: ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255));
21787 if (highlight_rect != NULL)
21788 {
21789 ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height);
21790 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);
21791 RenderRectFilledWithHole(draw_list: GetWindowDrawList(), outer: r_outer, inner: r_inner, IM_COL32(0, 0, 0, 100), rounding: 0.0f);
21792 GetWindowDrawList()->AddRect(p_min: r_inner.Min - ImVec2(1, 1), p_max: r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255));
21793 }
21794 PopStyleVar();
21795
21796 char texid_desc[30];
21797 Text(fmt: "Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(status: tex->Status), tex->Status, ImTextureDataGetFormatName(format: tex->Format), tex->Format, tex->UseColors);
21798 Text(fmt: "TexID = %s, BackendUserData = %p", FormatTextureIDForDebugDisplay(buf: texid_desc, IM_ARRAYSIZE(texid_desc), tex_id: tex->TexID), tex->BackendUserData);
21799 TreePop();
21800 }
21801 PopID();
21802}
21803
21804void ImGui::ShowMetricsWindow(bool* p_open)
21805{
21806 ImGuiContext& g = *GImGui;
21807 ImGuiIO& io = g.IO;
21808 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21809 if (cfg->ShowDebugLog)
21810 ShowDebugLogWindow(p_open: &cfg->ShowDebugLog);
21811 if (cfg->ShowIDStackTool)
21812 ShowIDStackToolWindow(p_open: &cfg->ShowIDStackTool);
21813
21814 if (!Begin(name: "Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
21815 {
21816 End();
21817 return;
21818 }
21819
21820 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
21821 DebugBreakClearData();
21822
21823 // Basic info
21824 Text(fmt: "Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
21825 if (g.ContextName[0] != 0)
21826 {
21827 SameLine();
21828 Text(fmt: "(Context Name: \"%s\")", g.ContextName);
21829 }
21830 Text(fmt: "Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
21831 Text(fmt: "%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
21832 Text(fmt: "%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
21833 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
21834
21835 Separator();
21836
21837 // Debugging enums
21838 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
21839 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
21840 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
21841 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
21842 if (cfg->ShowWindowsRectsType < 0)
21843 cfg->ShowWindowsRectsType = WRT_WorkRect;
21844 if (cfg->ShowTablesRectsType < 0)
21845 cfg->ShowTablesRectsType = TRT_WorkRect;
21846
21847 struct Funcs
21848 {
21849 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
21850 {
21851 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent); // Always using last submitted instance
21852 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
21853 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
21854 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
21855 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
21856 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
21857 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
21858 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); }
21859 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); }
21860 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
21861 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
21862 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); }
21863 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); }
21864 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); }
21865 IM_ASSERT(0);
21866 return ImRect();
21867 }
21868
21869 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
21870 {
21871 if (rect_type == WRT_OuterRect) { return window->Rect(); }
21872 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
21873 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
21874 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
21875 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
21876 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
21877 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
21878 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
21879 IM_ASSERT(0);
21880 return ImRect();
21881 }
21882 };
21883
21884#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
21885 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");
21886#endif
21887
21888 // Tools
21889 if (TreeNode(label: "Tools"))
21890 {
21891 // Debug Break features
21892 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
21893 SeparatorTextEx(id: 0, label: "Debug breaks", NULL, extra_width: CalcTextSize(text: "(?)").x + g.Style.SeparatorTextPadding.x);
21894 SameLine();
21895 MetricsHelpMarker(desc: "Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
21896 if (Checkbox(label: "Show Item Picker", v: &g.DebugItemPickerActive) && g.DebugItemPickerActive)
21897 DebugStartItemPicker();
21898 Checkbox(label: "Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", v: &g.IO.ConfigDebugIsDebuggerPresent);
21899
21900 SeparatorText(label: "Visualize");
21901
21902 Checkbox(label: "Show Debug Log", v: &cfg->ShowDebugLog);
21903 SameLine();
21904 MetricsHelpMarker(desc: "You can also call ImGui::ShowDebugLogWindow() from your code.");
21905
21906 Checkbox(label: "Show ID Stack Tool", v: &cfg->ShowIDStackTool);
21907 SameLine();
21908 MetricsHelpMarker(desc: "You can also call ImGui::ShowIDStackToolWindow() from your code.");
21909
21910 Checkbox(label: "Show windows begin order", v: &cfg->ShowWindowsBeginOrder);
21911 Checkbox(label: "Show windows rectangles", v: &cfg->ShowWindowsRects);
21912 SameLine();
21913 SetNextItemWidth(GetFontSize() * 12);
21914 cfg->ShowWindowsRects |= Combo(label: "##show_windows_rect_type", current_item: &cfg->ShowWindowsRectsType, items: wrt_rects_names, items_count: WRT_Count, popup_max_height_in_items: WRT_Count);
21915 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
21916 {
21917 BulletText(fmt: "'%s':", g.NavWindow->Name);
21918 Indent();
21919 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
21920 {
21921 ImRect r = Funcs::GetWindowRect(window: g.NavWindow, rect_type: rect_n);
21922 Text(fmt: "(%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]);
21923 }
21924 Unindent();
21925 }
21926
21927 Checkbox(label: "Show tables rectangles", v: &cfg->ShowTablesRects);
21928 SameLine();
21929 SetNextItemWidth(GetFontSize() * 12);
21930 cfg->ShowTablesRects |= Combo(label: "##show_table_rects_type", current_item: &cfg->ShowTablesRectsType, items: trt_rects_names, items_count: TRT_Count, popup_max_height_in_items: TRT_Count);
21931 if (cfg->ShowTablesRects && g.NavWindow != NULL)
21932 {
21933 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
21934 {
21935 ImGuiTable* table = g.Tables.TryGetMapData(n: table_n);
21936 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
21937 continue;
21938
21939 BulletText(fmt: "Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
21940 if (IsItemHovered())
21941 GetForegroundDrawList()->AddRect(p_min: table->OuterRect.Min - ImVec2(1, 1), p_max: table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), rounding: 0.0f, flags: 0, thickness: 2.0f);
21942 Indent();
21943 char buf[128];
21944 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
21945 {
21946 if (rect_n >= TRT_ColumnsRect)
21947 {
21948 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
21949 continue;
21950 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
21951 {
21952 ImRect r = Funcs::GetTableRect(table, rect_type: rect_n, n: column_n);
21953 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "(%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]);
21954 Selectable(label: buf);
21955 if (IsItemHovered())
21956 GetForegroundDrawList()->AddRect(p_min: r.Min - ImVec2(1, 1), p_max: r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), rounding: 0.0f, flags: 0, thickness: 2.0f);
21957 }
21958 }
21959 else
21960 {
21961 ImRect r = Funcs::GetTableRect(table, rect_type: rect_n, n: -1);
21962 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "(%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]);
21963 Selectable(label: buf);
21964 if (IsItemHovered())
21965 GetForegroundDrawList()->AddRect(p_min: r.Min - ImVec2(1, 1), p_max: r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), rounding: 0.0f, flags: 0, thickness: 2.0f);
21966 }
21967 }
21968 Unindent();
21969 }
21970 }
21971 Checkbox(label: "Show groups rectangles", v: &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
21972
21973 SeparatorText(label: "Validate");
21974
21975 Checkbox(label: "Debug Begin/BeginChild return value", v: &io.ConfigDebugBeginReturnValueLoop);
21976 SameLine();
21977 MetricsHelpMarker(desc: "Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
21978
21979 Checkbox(label: "UTF-8 Encoding viewer", v: &cfg->ShowTextEncodingViewer);
21980 SameLine();
21981 MetricsHelpMarker(desc: "You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
21982 if (cfg->ShowTextEncodingViewer)
21983 {
21984 static char buf[64] = "";
21985 SetNextItemWidth(-FLT_MIN);
21986 InputText(label: "##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
21987 if (buf[0] != 0)
21988 DebugTextEncoding(str: buf);
21989 }
21990
21991 TreePop();
21992 }
21993
21994 // Windows
21995 if (TreeNode(str_id: "Windows", fmt: "Windows (%d)", g.Windows.Size))
21996 {
21997 //SetNextItemOpen(true, ImGuiCond_Once);
21998 DebugNodeWindowsList(windows: &g.Windows, label: "By display order");
21999 DebugNodeWindowsList(windows: &g.WindowsFocusOrder, label: "By focus order (root windows)");
22000 if (TreeNode(label: "By submission order (begin stack)"))
22001 {
22002 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
22003 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
22004 temp_buffer.resize(new_size: 0);
22005 for (ImGuiWindow* window : g.Windows)
22006 if (window->LastFrameActive + 1 >= g.FrameCount)
22007 temp_buffer.push_back(v: window);
22008 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); } };
22009 ImQsort(base: temp_buffer.Data, count: (size_t)temp_buffer.Size, size_of_element: sizeof(ImGuiWindow*), compare_func: Func::WindowComparerByBeginOrder);
22010 DebugNodeWindowsListByBeginStackParent(windows: temp_buffer.Data, windows_size: temp_buffer.Size, NULL);
22011 TreePop();
22012 }
22013
22014 TreePop();
22015 }
22016
22017 // DrawLists
22018 int drawlist_count = 0;
22019 for (ImGuiViewportP* viewport : g.Viewports)
22020 drawlist_count += viewport->DrawDataP.CmdLists.Size;
22021 if (TreeNode(str_id: "DrawLists", fmt: "DrawLists (%d)", drawlist_count))
22022 {
22023 Checkbox(label: "Show ImDrawCmd mesh when hovering", v: &cfg->ShowDrawCmdMesh);
22024 Checkbox(label: "Show ImDrawCmd bounding boxes when hovering", v: &cfg->ShowDrawCmdBoundingBoxes);
22025 for (ImGuiViewportP* viewport : g.Viewports)
22026 {
22027 bool viewport_has_drawlist = false;
22028 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
22029 {
22030 if (!viewport_has_drawlist)
22031 Text(fmt: "Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
22032 viewport_has_drawlist = true;
22033 DebugNodeDrawList(NULL, viewport, draw_list, label: "DrawList");
22034 }
22035 }
22036 TreePop();
22037 }
22038
22039 // Viewports
22040 if (TreeNode(str_id: "Viewports", fmt: "Viewports (%d)", g.Viewports.Size))
22041 {
22042 cfg->HighlightMonitorIdx = -1;
22043 bool open = TreeNode(str_id: "Monitors", fmt: "Monitors (%d)", g.PlatformIO.Monitors.Size);
22044 SameLine();
22045 MetricsHelpMarker(desc: "Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
22046 if (open)
22047 {
22048 for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
22049 {
22050 DebugNodePlatformMonitor(monitor: &g.PlatformIO.Monitors[i], label: "Monitor", idx: i);
22051 if (IsItemHovered())
22052 cfg->HighlightMonitorIdx = i;
22053 }
22054 DebugNodePlatformMonitor(monitor: &g.FallbackMonitor, label: "Fallback", idx: 0);
22055 TreePop();
22056 }
22057
22058 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
22059 if (TreeNode(label: "Windows Minimap"))
22060 {
22061 RenderViewportsThumbnails();
22062 TreePop();
22063 }
22064 cfg->HighlightViewportID = 0;
22065
22066 BulletText(fmt: "MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
22067 if (TreeNode(label: "Inferred Z order (front-to-back)"))
22068 {
22069 static ImVector<ImGuiViewportP*> viewports;
22070 viewports.resize(new_size: g.Viewports.Size);
22071 memcpy(dest: viewports.Data, src: g.Viewports.Data, n: g.Viewports.size_in_bytes());
22072 if (viewports.Size > 1)
22073 ImQsort(base: viewports.Data, count: viewports.Size, size_of_element: sizeof(ImGuiViewport*), compare_func: ViewportComparerByLastFocusedStampCount);
22074 for (ImGuiViewportP* viewport : viewports)
22075 {
22076 BulletText(fmt: "Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
22077 viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
22078 (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
22079 viewport->Window ? viewport->Window->Name : "N/A");
22080 if (IsItemHovered())
22081 cfg->HighlightViewportID = viewport->ID;
22082 }
22083 TreePop();
22084 }
22085
22086 for (ImGuiViewportP* viewport : g.Viewports)
22087 DebugNodeViewport(viewport);
22088 TreePop();
22089 }
22090
22091 // Details for Fonts
22092 for (ImFontAtlas* atlas : g.FontAtlases)
22093 if (TreeNode(ptr_id: (void*)atlas, fmt: "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size))
22094 {
22095 ShowFontAtlas(atlas);
22096 TreePop();
22097 }
22098
22099 // Details for Popups
22100 if (TreeNode(str_id: "Popups", fmt: "Popups (%d)", g.OpenPopupStack.Size))
22101 {
22102 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
22103 {
22104 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
22105 ImGuiWindow* window = popup_data.Window;
22106 BulletText(fmt: "PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
22107 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
22108 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
22109 }
22110 TreePop();
22111 }
22112
22113 // Details for TabBars
22114 if (TreeNode(str_id: "TabBars", fmt: "Tab Bars (%d)", g.TabBars.GetAliveCount()))
22115 {
22116 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
22117 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
22118 {
22119 PushID(ptr_id: tab_bar);
22120 DebugNodeTabBar(tab_bar, label: "TabBar");
22121 PopID();
22122 }
22123 TreePop();
22124 }
22125
22126 // Details for Tables
22127 if (TreeNode(str_id: "Tables", fmt: "Tables (%d)", g.Tables.GetAliveCount()))
22128 {
22129 for (int n = 0; n < g.Tables.GetMapSize(); n++)
22130 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
22131 DebugNodeTable(table);
22132 TreePop();
22133 }
22134
22135 // Details for InputText
22136 if (TreeNode(label: "InputText"))
22137 {
22138 DebugNodeInputTextState(state: &g.InputTextState);
22139 TreePop();
22140 }
22141
22142 // Details for TypingSelect
22143 if (TreeNode(str_id: "TypingSelect", fmt: "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
22144 {
22145 DebugNodeTypingSelectState(state: &g.TypingSelectState);
22146 TreePop();
22147 }
22148
22149 // Details for MultiSelect
22150 if (TreeNode(str_id: "MultiSelect", fmt: "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
22151 {
22152 ImGuiBoxSelectState* bs = &g.BoxSelectState;
22153 BulletText(fmt: "BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
22154 for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
22155 if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
22156 DebugNodeMultiSelectState(state);
22157 TreePop();
22158 }
22159
22160 // Details for Docking
22161#ifdef IMGUI_HAS_DOCK
22162 if (TreeNode(label: "Docking"))
22163 {
22164 static bool root_nodes_only = true;
22165 ImGuiDockContext* dc = &g.DockContext;
22166 Checkbox(label: "List root nodes", v: &root_nodes_only);
22167 Checkbox(label: "Ctrl shows window dock info", v: &cfg->ShowDockingNodes);
22168 if (SmallButton(label: "Clear nodes")) { DockContextClearNodes(ctx: &g, root_id: 0, clear_settings_refs: true); }
22169 SameLine();
22170 if (SmallButton(label: "Rebuild all")) { dc->WantFullRebuild = true; }
22171 for (int n = 0; n < dc->Nodes.Data.Size; n++)
22172 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
22173 if (!root_nodes_only || node->IsRootNode())
22174 DebugNodeDockNode(node, label: "Node");
22175 TreePop();
22176 }
22177#endif // #ifdef IMGUI_HAS_DOCK
22178
22179 // Settings
22180 if (TreeNode(label: "Settings"))
22181 {
22182 if (SmallButton(label: "Clear"))
22183 ClearIniSettings();
22184 SameLine();
22185 if (SmallButton(label: "Save to memory"))
22186 SaveIniSettingsToMemory();
22187 SameLine();
22188 if (SmallButton(label: "Save to disk"))
22189 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
22190 SameLine();
22191 if (g.IO.IniFilename)
22192 Text(fmt: "\"%s\"", g.IO.IniFilename);
22193 else
22194 TextUnformatted(text: "<NULL>");
22195 Checkbox(label: "io.ConfigDebugIniSettings", v: &io.ConfigDebugIniSettings);
22196 Text(fmt: "SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
22197 if (TreeNode(str_id: "SettingsHandlers", fmt: "Settings handlers: (%d)", g.SettingsHandlers.Size))
22198 {
22199 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
22200 BulletText(fmt: "\"%s\"", handler.TypeName);
22201 TreePop();
22202 }
22203 if (TreeNode(str_id: "SettingsWindows", fmt: "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
22204 {
22205 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
22206 DebugNodeWindowSettings(settings);
22207 TreePop();
22208 }
22209
22210 if (TreeNode(str_id: "SettingsTables", fmt: "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
22211 {
22212 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(p: settings))
22213 DebugNodeTableSettings(settings);
22214 TreePop();
22215 }
22216
22217#ifdef IMGUI_HAS_DOCK
22218 if (TreeNode(str_id: "SettingsDocking", fmt: "Settings packed data: Docking"))
22219 {
22220 ImGuiDockContext* dc = &g.DockContext;
22221 Text(fmt: "In SettingsWindows:");
22222 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
22223 if (settings->DockId != 0)
22224 BulletText(fmt: "Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
22225 Text(fmt: "In SettingsNodes:");
22226 for (int n = 0; n < dc->NodesSettings.Size; n++)
22227 {
22228 ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
22229 const char* selected_tab_name = NULL;
22230 if (settings->SelectedTabId)
22231 {
22232 if (ImGuiWindow* window = FindWindowByID(id: settings->SelectedTabId))
22233 selected_tab_name = window->Name;
22234 else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(id: settings->SelectedTabId))
22235 selected_tab_name = window_settings->GetName();
22236 }
22237 BulletText(fmt: "Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
22238 }
22239 TreePop();
22240 }
22241#endif // #ifdef IMGUI_HAS_DOCK
22242
22243 if (TreeNode(str_id: "SettingsIniData", fmt: "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
22244 {
22245 InputTextMultiline(label: "##Ini", buf: (char*)(void*)g.SettingsIniData.c_str(), buf_size: g.SettingsIniData.Buf.Size, size: ImVec2(-FLT_MIN, GetTextLineHeight() * 20), flags: ImGuiInputTextFlags_ReadOnly);
22246 TreePop();
22247 }
22248 TreePop();
22249 }
22250
22251 // Settings
22252 if (TreeNode(label: "Memory allocations"))
22253 {
22254 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
22255 Text(fmt: "%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
22256 if (SmallButton(label: "GC now")) { g.GcCompactAll = true; }
22257 Text(fmt: "Recent frames with allocations:");
22258 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
22259 for (int n = buf_size - 1; n >= 0; n--)
22260 {
22261 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
22262 BulletText(fmt: "Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
22263 if (n == 0)
22264 {
22265 SameLine();
22266 Text(fmt: "<- %d frames ago", g.FrameCount - entry->FrameCount);
22267 }
22268 }
22269 TreePop();
22270 }
22271
22272 if (TreeNode(label: "Inputs"))
22273 {
22274 Text(fmt: "KEYBOARD/GAMEPAD/MOUSE KEYS");
22275 {
22276 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
22277 Indent();
22278 Text(fmt: "Keys down:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue; SameLine(); Text(fmt: IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text(fmt: "(%.02f)", GetKeyData(key)->DownDuration); }
22279 Text(fmt: "Keys pressed:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue; SameLine(); Text(fmt: IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
22280 Text(fmt: "Keys released:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(fmt: IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
22281 Text(fmt: "Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
22282 Text(fmt: "Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text(fmt: "\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
22283 DebugRenderKeyboardPreview(draw_list: GetWindowDrawList());
22284 Unindent();
22285 }
22286
22287 Text(fmt: "MOUSE STATE");
22288 {
22289 Indent();
22290 if (IsMousePosValid())
22291 Text(fmt: "Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
22292 else
22293 Text(fmt: "Mouse pos: <INVALID>");
22294 Text(fmt: "Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
22295 int count = IM_ARRAYSIZE(io.MouseDown);
22296 Text(fmt: "Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(button: i)) { SameLine(); Text(fmt: "b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
22297 Text(fmt: "Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(button: i)) { SameLine(); Text(fmt: "b%d (%d)", i, io.MouseClickedCount[i]); }
22298 Text(fmt: "Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(button: i)) { SameLine(); Text(fmt: "b%d", i); }
22299 Text(fmt: "Mouse wheel: %.1f", io.MouseWheel);
22300 Text(fmt: "MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
22301 Text(fmt: "Mouse source: %s", GetMouseSourceName(source: io.MouseSource));
22302 Text(fmt: "Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
22303 Unindent();
22304 }
22305
22306 Text(fmt: "MOUSE WHEELING");
22307 {
22308 Indent();
22309 Text(fmt: "WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
22310 Text(fmt: "WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
22311 Text(fmt: "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>");
22312 Unindent();
22313 }
22314
22315 Text(fmt: "KEY OWNERS");
22316 {
22317 Indent();
22318 if (BeginChild(str_id: "##owners", size_arg: ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), child_flags: ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, window_flags: ImGuiWindowFlags_NoSavedSettings))
22319 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
22320 {
22321 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
22322 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
22323 continue;
22324 Text(fmt: "%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
22325 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
22326 DebugLocateItemOnHover(target_id: owner_data->OwnerCurr);
22327 }
22328 EndChild();
22329 Unindent();
22330 }
22331 Text(fmt: "SHORTCUT ROUTING");
22332 SameLine();
22333 MetricsHelpMarker(desc: "Declared shortcut routes automatically set key owner when mods matches.");
22334 {
22335 Indent();
22336 if (BeginChild(str_id: "##routes", size_arg: ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), child_flags: ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, window_flags: ImGuiWindowFlags_NoSavedSettings))
22337 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
22338 {
22339 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
22340 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
22341 {
22342 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
22343 ImGuiKeyChord key_chord = key | routing_data->Mods;
22344 Text(fmt: "%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
22345 DebugLocateItemOnHover(target_id: routing_data->RoutingCurr);
22346 if (g.IO.ConfigDebugIsDebuggerPresent)
22347 {
22348 SameLine();
22349 if (DebugBreakButton(label: "**DebugBreak**", description_of_location: "in SetShortcutRouting() for this KeyChord"))
22350 g.DebugBreakInShortcutRouting = key_chord;
22351 }
22352 idx = routing_data->NextEntryIndex;
22353 }
22354 }
22355 EndChild();
22356 Text(fmt: "(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
22357 Unindent();
22358 }
22359 TreePop();
22360 }
22361
22362 if (TreeNode(label: "Internal state"))
22363 {
22364 Text(fmt: "WINDOWING");
22365 Indent();
22366 Text(fmt: "HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
22367 Text(fmt: "HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
22368 Text(fmt: "HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
22369 Text(fmt: "HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
22370 Text(fmt: "MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
22371 Text(fmt: "MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
22372 Unindent();
22373
22374 Text(fmt: "ITEMS");
22375 Indent();
22376 Text(fmt: "ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(source: g.ActiveIdSource));
22377 DebugLocateItemOnHover(target_id: g.ActiveId);
22378 Text(fmt: "ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
22379 Text(fmt: "ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
22380 Text(fmt: "HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
22381 Text(fmt: "HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
22382 Text(fmt: "DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
22383 DebugLocateItemOnHover(target_id: g.DragDropPayload.SourceId);
22384 Unindent();
22385
22386 Text(fmt: "NAV,FOCUS");
22387 Indent();
22388 Text(fmt: "NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
22389 Text(fmt: "NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
22390 DebugLocateItemOnHover(target_id: g.NavId);
22391 Text(fmt: "NavInputSource: %s", GetInputSourceName(source: g.NavInputSource));
22392 Text(fmt: "NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
22393 Text(fmt: "NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
22394 Text(fmt: "NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
22395 Text(fmt: "NavActivateFlags: %04X", g.NavActivateFlags);
22396 Text(fmt: "NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav);
22397 Text(fmt: "NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
22398 Text(fmt: "NavFocusRoute[] = ");
22399 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
22400 {
22401 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
22402 SameLine(offset_from_start_x: 0.0f, spacing_w: 0.0f);
22403 Text(fmt: "0x%08X/", focus_scope.ID);
22404 SetItemTooltip("In window \"%s\"", FindWindowByID(id: focus_scope.WindowID)->Name);
22405 }
22406 Text(fmt: "NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
22407 Unindent();
22408
22409 TreePop();
22410 }
22411
22412 // Overlay: Display windows Rectangles and Begin Order
22413 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
22414 {
22415 for (ImGuiWindow* window : g.Windows)
22416 {
22417 if (!window->WasActive)
22418 continue;
22419 ImDrawList* draw_list = GetForegroundDrawList(window);
22420 if (cfg->ShowWindowsRects)
22421 {
22422 ImRect r = Funcs::GetWindowRect(window, rect_type: cfg->ShowWindowsRectsType);
22423 draw_list->AddRect(p_min: r.Min, p_max: r.Max, IM_COL32(255, 0, 128, 255));
22424 }
22425 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
22426 {
22427 char buf[32];
22428 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "%d", window->BeginOrderWithinContext);
22429 float font_size = GetFontSize();
22430 draw_list->AddRectFilled(p_min: window->Pos, p_max: window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
22431 draw_list->AddText(pos: window->Pos, IM_COL32(255, 255, 255, 255), text_begin: buf);
22432 }
22433 }
22434 }
22435
22436 // Overlay: Display Tables Rectangles
22437 if (cfg->ShowTablesRects)
22438 {
22439 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
22440 {
22441 ImGuiTable* table = g.Tables.TryGetMapData(n: table_n);
22442 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
22443 continue;
22444 ImDrawList* draw_list = GetForegroundDrawList(window: table->OuterWindow);
22445 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
22446 {
22447 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
22448 {
22449 ImRect r = Funcs::GetTableRect(table, rect_type: cfg->ShowTablesRectsType, n: column_n);
22450 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
22451 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
22452 draw_list->AddRect(p_min: r.Min, p_max: r.Max, col, rounding: 0.0f, flags: 0, thickness);
22453 }
22454 }
22455 else
22456 {
22457 ImRect r = Funcs::GetTableRect(table, rect_type: cfg->ShowTablesRectsType, n: -1);
22458 draw_list->AddRect(p_min: r.Min, p_max: r.Max, IM_COL32(255, 0, 128, 255));
22459 }
22460 }
22461 }
22462
22463#ifdef IMGUI_HAS_DOCK
22464 // Overlay: Display Docking info
22465 if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
22466 {
22467 char buf[64] = "";
22468 char* p = buf;
22469 ImGuiDockNode* node = g.DebugHoveredDockNode;
22470 ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(window: node->HostWindow) : GetForegroundDrawList(viewport: GetMainViewport());
22471 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
22472 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "WindowClass: %08X\n", node->WindowClass.ClassId);
22473 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
22474 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
22475 int depth = DockNodeGetDepth(node);
22476 overlay_draw_list->AddRect(p_min: node->Pos + ImVec2(3, 3) * (float)depth, p_max: node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
22477 ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
22478 overlay_draw_list->AddRectFilled(p_min: pos - ImVec2(1, 1), p_max: pos + CalcTextSize(text: buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
22479 overlay_draw_list->AddText(NULL, font_size: 0.0f, pos, IM_COL32(255, 255, 255, 255), text_begin: buf);
22480 }
22481#endif // #ifdef IMGUI_HAS_DOCK
22482
22483 End();
22484}
22485
22486void ImGui::DebugBreakClearData()
22487{
22488 // Those fields are scattered in their respective subsystem to stay in hot-data locations
22489 ImGuiContext& g = *GImGui;
22490 g.DebugBreakInWindow = 0;
22491 g.DebugBreakInTable = 0;
22492 g.DebugBreakInShortcutRouting = ImGuiKey_None;
22493}
22494
22495void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
22496{
22497 if (!BeginItemTooltip())
22498 return;
22499 Text(fmt: "To call IM_DEBUG_BREAK() %s:", description_of_location);
22500 Separator();
22501 TextUnformatted(text: 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.");
22502 Separator();
22503 TextUnformatted(text: "Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
22504 EndTooltip();
22505}
22506
22507// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
22508// In order to reduce interferences with the contents we are trying to debug into.
22509bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
22510{
22511 ImGuiWindow* window = GetCurrentWindow();
22512 if (window->SkipItems)
22513 return false;
22514
22515 ImGuiContext& g = *GImGui;
22516 const ImGuiID id = window->GetID(str: label);
22517 const ImVec2 label_size = CalcTextSize(text: label, NULL, hide_text_after_double_hash: true);
22518 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
22519 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
22520
22521 const ImRect bb(pos, pos + size);
22522 ItemSize(size, text_baseline_y: 0.0f);
22523 if (!ItemAdd(bb, id))
22524 return false;
22525
22526 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
22527 bool hovered = ItemHoverable(bb, id, item_flags: g.CurrentItemFlags);
22528 bool pressed = hovered && (IsKeyChordPressed(key_chord: g.DebugBreakKeyChord) || IsMouseClicked(button: 0) || g.NavActivateId == id);
22529 DebugBreakButtonTooltip(keyboard_only: false, description_of_location);
22530
22531 ImVec4 col4f = GetStyleColorVec4(idx: hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
22532 ImVec4 hsv;
22533 ColorConvertRGBtoHSV(r: col4f.x, g: col4f.y, b: col4f.z, out_h&: hsv.x, out_s&: hsv.y, out_v&: hsv.z);
22534 ColorConvertHSVtoRGB(h: hsv.x + 0.20f, s: hsv.y, v: hsv.z, out_r&: col4f.x, out_g&: col4f.y, out_b&: col4f.z);
22535
22536 RenderNavCursor(bb, id);
22537 RenderFrame(p_min: bb.Min, p_max: bb.Max, fill_col: GetColorU32(col: col4f), borders: true, rounding: g.Style.FrameRounding);
22538 RenderTextClipped(pos_min: bb.Min, pos_max: bb.Max, text: label, NULL, text_size_if_known: &label_size, align: g.Style.ButtonTextAlign, clip_rect: &bb);
22539
22540 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
22541 return pressed;
22542}
22543
22544// [DEBUG] Display contents of Columns
22545void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
22546{
22547 if (!TreeNode(ptr_id: (void*)(uintptr_t)columns->ID, fmt: "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
22548 return;
22549 BulletText(fmt: "Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
22550 for (ImGuiOldColumnData& column : columns->Columns)
22551 BulletText(fmt: "Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(it: &column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, offset_norm: column.OffsetNorm));
22552 TreePop();
22553}
22554
22555static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
22556{
22557 using namespace ImGui;
22558 PushID(str_id: label);
22559 PushStyleVar(idx: ImGuiStyleVar_FramePadding, val: ImVec2(0.0f, 0.0f));
22560 Text(fmt: "%s:", label);
22561 if (!enabled)
22562 BeginDisabled();
22563 CheckboxFlags(label: "NoResize", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoResize);
22564 CheckboxFlags(label: "NoResizeX", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoResizeX);
22565 CheckboxFlags(label: "NoResizeY",flags: p_flags, flags_value: ImGuiDockNodeFlags_NoResizeY);
22566 CheckboxFlags(label: "NoTabBar", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoTabBar);
22567 CheckboxFlags(label: "HiddenTabBar", flags: p_flags, flags_value: ImGuiDockNodeFlags_HiddenTabBar);
22568 CheckboxFlags(label: "NoWindowMenuButton", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoWindowMenuButton);
22569 CheckboxFlags(label: "NoCloseButton", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoCloseButton);
22570 CheckboxFlags(label: "DockedWindowsInFocusRoute", flags: p_flags, flags_value: ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
22571 CheckboxFlags(label: "NoDocking", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDocking); // Multiple flags
22572 CheckboxFlags(label: "NoDockingSplit", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingSplit);
22573 CheckboxFlags(label: "NoDockingSplitOther", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingSplitOther);
22574 CheckboxFlags(label: "NoDockingOver", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingOverMe);
22575 CheckboxFlags(label: "NoDockingOverOther", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingOverOther);
22576 CheckboxFlags(label: "NoDockingOverEmpty", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingOverEmpty);
22577 CheckboxFlags(label: "NoUndocking", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoUndocking);
22578 if (!enabled)
22579 EndDisabled();
22580 PopStyleVar();
22581 PopID();
22582}
22583
22584// [DEBUG] Display contents of ImDockNode
22585void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
22586{
22587 ImGuiContext& g = *GImGui;
22588 const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
22589 const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted
22590 if (!is_alive) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
22591 bool open;
22592 ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
22593 if (node->Windows.Size > 0)
22594 open = TreeNodeEx(ptr_id: (void*)(intptr_t)node->ID, flags: tree_node_flags, fmt: "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
22595 else
22596 open = TreeNodeEx(ptr_id: (void*)(intptr_t)node->ID, flags: tree_node_flags, fmt: "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
22597 if (!is_alive) { PopStyleColor(); }
22598 if (is_active && IsItemHovered())
22599 if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
22600 GetForegroundDrawList(window)->AddRect(p_min: node->Pos, p_max: node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
22601 if (open)
22602 {
22603 IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
22604 IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
22605 BulletText(fmt: "Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
22606 node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
22607 DebugNodeWindow(window: node->HostWindow, label: "HostWindow");
22608 DebugNodeWindow(window: node->VisibleWindow, label: "VisibleWindow");
22609 BulletText(fmt: "SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
22610 BulletText(fmt: "Misc:%s%s%s%s%s%s%s",
22611 node->IsDockSpace() ? " IsDockSpace" : "",
22612 node->IsCentralNode() ? " IsCentralNode" : "",
22613 is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
22614 node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
22615 node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
22616 if (TreeNode(str_id: "flags", fmt: "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
22617 {
22618 if (BeginTable(str_id: "flags", columns: 4))
22619 {
22620 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->MergedFlags, label: "MergedFlags", enabled: false);
22621 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->LocalFlags, label: "LocalFlags", enabled: true);
22622 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->LocalFlagsInWindows, label: "LocalFlagsInWindows", enabled: false);
22623 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->SharedFlags, label: "SharedFlags", enabled: true);
22624 EndTable();
22625 }
22626 TreePop();
22627 }
22628 if (node->ParentNode)
22629 DebugNodeDockNode(node: node->ParentNode, label: "ParentNode");
22630 if (node->ChildNodes[0])
22631 DebugNodeDockNode(node: node->ChildNodes[0], label: "Child[0]");
22632 if (node->ChildNodes[1])
22633 DebugNodeDockNode(node: node->ChildNodes[1], label: "Child[1]");
22634 if (node->TabBar)
22635 DebugNodeTabBar(tab_bar: node->TabBar, label: "TabBar");
22636 DebugNodeWindowsList(windows: &node->Windows, label: "Windows");
22637
22638 TreePop();
22639 }
22640}
22641
22642// [DEBUG] Display contents of ImDrawList
22643// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
22644void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
22645{
22646 ImGuiContext& g = *GImGui;
22647 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22648 int cmd_count = draw_list->CmdBuffer.Size;
22649 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
22650 cmd_count--;
22651 bool node_open = TreeNode(ptr_id: draw_list, fmt: "%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);
22652 if (draw_list == GetWindowDrawList())
22653 {
22654 SameLine();
22655 TextColored(col: ImVec4(1.0f, 0.4f, 0.4f, 1.0f), fmt: "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
22656 if (node_open)
22657 TreePop();
22658 return;
22659 }
22660
22661 ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
22662 if (window && IsItemHovered() && fg_draw_list)
22663 fg_draw_list->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
22664 if (!node_open)
22665 return;
22666
22667 if (window && !window->WasActive)
22668 TextDisabled(fmt: "Warning: owning Window is inactive. This DrawList is not being rendered!");
22669
22670 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
22671 {
22672 if (pcmd->UserCallback)
22673 {
22674 BulletText(fmt: "Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
22675 continue;
22676 }
22677
22678 char texid_desc[30];
22679 FormatTextureIDForDebugDisplay(buf: texid_desc, IM_ARRAYSIZE(texid_desc), cmd: pcmd);
22680 char buf[300];
22681 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
22682 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
22683 bool pcmd_node_open = TreeNode(ptr_id: (void*)(pcmd - draw_list->CmdBuffer.begin()), fmt: "%s", buf);
22684 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
22685 DebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list: fg_draw_list, draw_list, draw_cmd: pcmd, show_mesh: cfg->ShowDrawCmdMesh, show_aabb: cfg->ShowDrawCmdBoundingBoxes);
22686 if (!pcmd_node_open)
22687 continue;
22688
22689 // Calculate approximate coverage area (touched pixel count)
22690 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
22691 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
22692 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
22693 float total_area = 0.0f;
22694 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
22695 {
22696 ImVec2 triangle[3];
22697 for (int n = 0; n < 3; n++, idx_n++)
22698 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
22699 total_area += ImTriangleArea(a: triangle[0], b: triangle[1], c: triangle[2]);
22700 }
22701
22702 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
22703 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
22704 Selectable(label: buf);
22705 if (IsItemHovered() && fg_draw_list)
22706 DebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list: fg_draw_list, draw_list, draw_cmd: pcmd, show_mesh: true, show_aabb: false);
22707
22708 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
22709 ImGuiListClipper clipper;
22710 clipper.Begin(items_count: pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
22711 while (clipper.Step())
22712 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
22713 {
22714 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
22715 ImVec2 triangle[3];
22716 for (int n = 0; n < 3; n++, idx_i++)
22717 {
22718 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
22719 triangle[n] = v.pos;
22720 buf_p += ImFormatString(buf: buf_p, buf_size: buf_end - buf_p, fmt: "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
22721 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
22722 }
22723
22724 Selectable(label: buf, selected: false);
22725 if (fg_draw_list && IsItemHovered())
22726 {
22727 ImDrawListFlags backup_flags = fg_draw_list->Flags;
22728 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
22729 fg_draw_list->AddPolyline(points: triangle, num_points: 3, IM_COL32(255, 255, 0, 255), flags: ImDrawFlags_Closed, thickness: 1.0f);
22730 fg_draw_list->Flags = backup_flags;
22731 }
22732 }
22733 TreePop();
22734 }
22735 TreePop();
22736}
22737
22738// [DEBUG] Display mesh/aabb of a ImDrawCmd
22739void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
22740{
22741 IM_ASSERT(show_mesh || show_aabb);
22742
22743 // Draw wire-frame version of all triangles
22744 ImRect clip_rect = draw_cmd->ClipRect;
22745 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
22746 ImDrawListFlags backup_flags = out_draw_list->Flags;
22747 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
22748 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
22749 {
22750 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
22751 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
22752
22753 ImVec2 triangle[3];
22754 for (int n = 0; n < 3; n++, idx_n++)
22755 vtxs_rect.Add(p: (triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
22756 if (show_mesh)
22757 out_draw_list->AddPolyline(points: triangle, num_points: 3, IM_COL32(255, 255, 0, 255), flags: ImDrawFlags_Closed, thickness: 1.0f); // In yellow: mesh triangles
22758 }
22759 // Draw bounding boxes
22760 if (show_aabb)
22761 {
22762 out_draw_list->AddRect(p_min: ImTrunc(v: clip_rect.Min), p_max: ImTrunc(v: clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
22763 out_draw_list->AddRect(p_min: ImTrunc(v: vtxs_rect.Min), p_max: ImTrunc(v: vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
22764 }
22765 out_draw_list->Flags = backup_flags;
22766}
22767
22768// [DEBUG] Compute mask of inputs with the same codepoint.
22769static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint)
22770{
22771 int mask = 0, count = 0;
22772 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22773 {
22774 ImFontConfig* src = font->Sources[src_n];
22775 if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint))
22776 continue;
22777 mask |= (1 << src_n);
22778 count++;
22779 }
22780 return count > 1 ? mask : 0;
22781}
22782
22783// [DEBUG] Display details for a single font, called by ShowStyleEditor().
22784void ImGui::DebugNodeFont(ImFont* font)
22785{
22786 ImGuiContext& g = *GImGui;
22787 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22788 ImFontAtlas* atlas = font->ContainerAtlas;
22789 bool opened = TreeNode(ptr_id: font, fmt: "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size);
22790
22791 // Display preview text
22792 if (!opened)
22793 Indent();
22794 Indent();
22795 if (cfg->ShowFontPreview)
22796 {
22797 PushFont(font, font_size_base: 0.0f);
22798 Text(fmt: "The quick brown fox jumps over the lazy dog");
22799 PopFont();
22800 }
22801 if (!opened)
22802 {
22803 Unindent();
22804 Unindent();
22805 return;
22806 }
22807 if (SmallButton(label: "Set as default"))
22808 GetIO().FontDefault = font;
22809 SameLine();
22810 BeginDisabled(disabled: atlas->Fonts.Size <= 1 || atlas->Locked);
22811 if (SmallButton(label: "Remove"))
22812 atlas->RemoveFont(font);
22813 EndDisabled();
22814 SameLine();
22815 if (SmallButton(label: "Clear bakes"))
22816 ImFontAtlasFontDiscardBakes(atlas, font, unused_frames: 0);
22817 SameLine();
22818 if (SmallButton(label: "Clear unused"))
22819 ImFontAtlasFontDiscardBakes(atlas, font, unused_frames: 2);
22820
22821 // Display details
22822#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
22823 SetNextItemWidth(GetFontSize() * 8);
22824 DragFloat(label: "Font scale", v: &font->Scale, v_speed: 0.005f, v_min: 0.3f, v_max: 2.0f, format: "%.1f");
22825 /*SameLine(); MetricsHelpMarker(
22826 "Note that the default embedded font is NOT meant to be scaled.\n\n"
22827 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
22828 "You may oversample them to get some flexibility with scaling. "
22829 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
22830 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/
22831#endif
22832
22833 char c_str[5];
22834 ImTextCharToUtf8(out_buf: c_str, c: font->FallbackChar);
22835 Text(fmt: "Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar);
22836 ImTextCharToUtf8(out_buf: c_str, c: font->EllipsisChar);
22837 Text(fmt: "Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar);
22838
22839 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22840 {
22841 ImFontConfig* src = font->Sources[src_n];
22842 if (TreeNode(ptr_id: src, fmt: "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)",
22843 src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y))
22844 {
22845 const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
22846 Text(fmt: "Loader: '%s'", loader->Name ? loader->Name : "N/A");
22847#ifdef IMGUI_ENABLE_FREETYPE
22848 if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0)
22849 {
22850 unsigned int loader_flags = src->FontLoaderFlags;
22851 Text("FreeType Loader Flags: 0x%08X", loader_flags);
22852 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
22853 {
22854 ImFontAtlasFontDestroyOutput(atlas, font);
22855 src->FontLoaderFlags = loader_flags;
22856 ImFontAtlasFontInitOutput(atlas, font);
22857 }
22858 }
22859#endif
22860 TreePop();
22861 }
22862 }
22863 if (font->Sources.Size > 1 && TreeNode(label: "Input Glyphs Overlap Detection Tool"))
22864 {
22865 TextWrapped(fmt: "- First Input that contains the glyph is used.\n"
22866 "- 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!");
22867 if (BeginTable(str_id: "table", columns: 2))
22868 {
22869 for (unsigned int c = 0; c < 0x10000; c++)
22870 if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, codepoint: c))
22871 {
22872 unsigned int c_end = c + 1;
22873 while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, codepoint: c_end) == overlap_mask)
22874 c_end++;
22875 if (TableNextColumn() && TreeNode(ptr_id: (void*)(intptr_t)c, fmt: "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(v: overlap_mask)))
22876 {
22877 char utf8_buf[5];
22878 for (unsigned int n = c; n < c_end; n++)
22879 {
22880 ImTextCharToUtf8(out_buf: utf8_buf, c: n);
22881 BulletText(fmt: "Codepoint U+%04X (%s)", n, utf8_buf);
22882 }
22883 TreePop();
22884 }
22885 TableNextColumn();
22886 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22887 if (overlap_mask & (1 << src_n))
22888 {
22889 Text(fmt: "%d ", src_n);
22890 SameLine();
22891 }
22892 c = c_end - 1;
22893 }
22894 EndTable();
22895 }
22896 TreePop();
22897 }
22898
22899 // Display all glyphs of the fonts in separate pages of 256 characters
22900 for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++)
22901 {
22902 ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n];
22903 if (baked->ContainerFont != font)
22904 continue;
22905 PushID(int_id: baked_n);
22906 if (TreeNode(str_id: "Glyphs", fmt: "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : ""))
22907 {
22908 if (SmallButton(label: "Load all"))
22909 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++)
22910 baked->FindGlyph(c: (ImWchar)base);
22911
22912 const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface);
22913 Text(fmt: "Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent);
22914 Text(fmt: "Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt);
22915 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22916 {
22917 ImFontConfig* src = font->Sources[src_n];
22918 int oversample_h, oversample_v;
22919 ImFontAtlasBuildGetOversampleFactors(src, baked, out_oversample_h: &oversample_h, out_oversample_v: &oversample_v);
22920 BulletText(fmt: "Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
22921 src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y);
22922 }
22923
22924 DebugNodeFontGlyphesForSrcMask(font, baked, src_mask: ~0);
22925 TreePop();
22926 }
22927 PopID();
22928 }
22929 TreePop();
22930 Unindent();
22931}
22932
22933void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask)
22934{
22935 ImDrawList* draw_list = GetWindowDrawList();
22936 const ImU32 glyph_col = GetColorU32(idx: ImGuiCol_Text);
22937 const float cell_size = baked->Size * 1;
22938 const float cell_spacing = GetStyle().ItemSpacing.y;
22939 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
22940 {
22941 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
22942 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
22943 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
22944 if (!(base & 8191) && font->IsGlyphRangeUnused(c_begin: base, c_last: base + 8191))
22945 {
22946 base += 8192 - 256;
22947 continue;
22948 }
22949
22950 int count = 0;
22951 for (unsigned int n = 0; n < 256; n++)
22952 if (const ImFontGlyph* glyph = baked->IsGlyphLoaded(c: (ImWchar)(base + n)) ? baked->FindGlyph(c: (ImWchar)(base + n)) : NULL)
22953 if (src_mask & (1 << glyph->SourceIdx))
22954 count++;
22955 if (count <= 0)
22956 continue;
22957 if (!TreeNode(ptr_id: (void*)(intptr_t)base, fmt: "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
22958 continue;
22959
22960 // Draw a 16x16 grid of glyphs
22961 ImVec2 base_pos = GetCursorScreenPos();
22962 for (unsigned int n = 0; n < 256; n++)
22963 {
22964 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
22965 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
22966 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
22967 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
22968 const ImFontGlyph* glyph = baked->IsGlyphLoaded(c: (ImWchar)(base + n)) ? baked->FindGlyph(c: (ImWchar)(base + n)) : NULL;
22969 draw_list->AddRect(p_min: cell_p1, p_max: cell_p2, col: glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
22970 if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0)
22971 continue;
22972 font->RenderChar(draw_list, size: cell_size, pos: cell_p1, col: glyph_col, c: (ImWchar)(base + n));
22973 if (IsMouseHoveringRect(r_min: cell_p1, r_max: cell_p2) && BeginTooltip())
22974 {
22975 DebugNodeFontGlyph(font, glyph);
22976 EndTooltip();
22977 }
22978 }
22979 Dummy(size: ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
22980 TreePop();
22981 }
22982}
22983
22984void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph)
22985{
22986 Text(fmt: "Codepoint: U+%04X", glyph->Codepoint);
22987 Separator();
22988 Text(fmt: "Visible: %d", glyph->Visible);
22989 Text(fmt: "AdvanceX: %.1f", glyph->AdvanceX);
22990 Text(fmt: "Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
22991 Text(fmt: "UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
22992 if (glyph->PackId >= 0)
22993 {
22994 ImTextureRect* r = ImFontAtlasPackGetRect(atlas: font->ContainerAtlas, id: glyph->PackId);
22995 Text(fmt: "PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);
22996 }
22997 Text(fmt: "SourceIdx: %d", glyph->SourceIdx);
22998}
22999
23000// [DEBUG] Display contents of ImGuiStorage
23001void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
23002{
23003 if (!TreeNode(str_id: label, fmt: "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
23004 return;
23005 for (const ImGuiStoragePair& p : storage->Data)
23006 {
23007 BulletText(fmt: "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.
23008 DebugLocateItemOnHover(target_id: p.key);
23009 }
23010 TreePop();
23011}
23012
23013// [DEBUG] Display contents of ImGuiTabBar
23014void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
23015{
23016 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
23017 char buf[256];
23018 char* p = buf;
23019 const char* buf_end = buf + IM_ARRAYSIZE(buf);
23020 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
23021 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
23022 for (int tab_n = 0; tab_n < ImMin(lhs: tab_bar->Tabs.Size, rhs: 3); tab_n++)
23023 {
23024 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
23025 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
23026 }
23027 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
23028 if (!is_active) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
23029 bool open = TreeNode(str_id: label, fmt: "%s", buf);
23030 if (!is_active) { PopStyleColor(); }
23031 if (is_active && IsItemHovered())
23032 {
23033 ImDrawList* draw_list = GetForegroundDrawList();
23034 draw_list->AddRect(p_min: tab_bar->BarRect.Min, p_max: tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
23035 draw_list->AddLine(p1: ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), p2: ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
23036 draw_list->AddLine(p1: ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), p2: ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
23037 }
23038 if (open)
23039 {
23040 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
23041 {
23042 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
23043 PushID(ptr_id: tab);
23044 if (SmallButton(label: "<")) { TabBarQueueReorder(tab_bar, tab, offset: -1); } SameLine(offset_from_start_x: 0, spacing_w: 2);
23045 if (SmallButton(label: ">")) { TabBarQueueReorder(tab_bar, tab, offset: +1); } SameLine();
23046 Text(fmt: "%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
23047 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
23048 PopID();
23049 }
23050 TreePop();
23051 }
23052}
23053
23054void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
23055{
23056 ImGuiContext& g = *GImGui;
23057 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
23058 bool open = TreeNode(ptr_id: (void*)(intptr_t)viewport->ID, fmt: "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
23059 if (IsItemHovered())
23060 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
23061 if (open)
23062 {
23063 ImGuiWindowFlags flags = viewport->Flags;
23064 BulletText(fmt: "Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nFrameBufferScale: (%.2f,%.2f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
23065 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
23066 viewport->FramebufferScale.x, viewport->FramebufferScale.y,
23067 viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y,
23068 viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
23069 if (viewport->Idx > 0) { SameLine(); if (SmallButton(label: "Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
23070 BulletText(fmt: "Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
23071 //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
23072 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
23073 (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
23074 (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
23075 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
23076 (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
23077 (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
23078 (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
23079 (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
23080 (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
23081 (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
23082 (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
23083 (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
23084 (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
23085 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
23086 DebugNodeDrawList(NULL, viewport, draw_list, label: "DrawList");
23087 TreePop();
23088 }
23089}
23090
23091void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx)
23092{
23093 BulletText(fmt: "%s %d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
23094 label, idx, monitor->DpiScale * 100.0f,
23095 monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y,
23096 monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y);
23097}
23098
23099void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
23100{
23101 if (window == NULL)
23102 {
23103 BulletText(fmt: "%s: NULL", label);
23104 return;
23105 }
23106
23107 ImGuiContext& g = *GImGui;
23108 const bool is_active = window->WasActive;
23109 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
23110 if (!is_active) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
23111 const bool open = TreeNodeEx(str_id: label, flags: tree_node_flags, fmt: "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
23112 if (!is_active) { PopStyleColor(); }
23113 if (IsItemHovered() && is_active)
23114 GetForegroundDrawList(window)->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
23115 if (!open)
23116 return;
23117
23118 if (window->MemoryCompacted)
23119 TextDisabled(fmt: "Note: some memory buffers have been compacted/freed.");
23120
23121 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton(label: "**DebugBreak**", description_of_location: "in Begin()"))
23122 g.DebugBreakInWindow = window->ID;
23123
23124 ImGuiWindowFlags flags = window->Flags;
23125 DebugNodeDrawList(window, viewport: window->Viewport, draw_list: window->DrawList, label: "DrawList");
23126 BulletText(fmt: "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);
23127 BulletText(fmt: "Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
23128 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
23129 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
23130 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
23131 if (flags & ImGuiWindowFlags_ChildWindow)
23132 BulletText(fmt: "ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
23133 (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "",
23134 (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
23135 (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
23136 (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
23137 BulletText(fmt: "WindowClassId: 0x%08X", window->WindowClass.ClassId);
23138 BulletText(fmt: "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" : "");
23139 BulletText(fmt: "Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
23140 BulletText(fmt: "Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
23141 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
23142 {
23143 ImRect r = window->NavRectRel[layer];
23144 if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
23145 BulletText(fmt: "NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
23146 else
23147 BulletText(fmt: "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);
23148 DebugLocateItemOnHover(target_id: window->NavLastIds[layer]);
23149 }
23150 const ImVec2* pr = window->NavPreferredScoringPosRel;
23151 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
23152 BulletText(fmt: "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.
23153 BulletText(fmt: "NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
23154
23155 BulletText(fmt: "Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
23156 BulletText(fmt: "ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
23157 BulletText(fmt: "DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
23158 if (window->DockNode || window->DockNodeAsHost)
23159 DebugNodeDockNode(node: window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, label: window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
23160
23161 if (window->RootWindow != window) { DebugNodeWindow(window: window->RootWindow, label: "RootWindow"); }
23162 if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window: window->RootWindowDockTree, label: "RootWindowDockTree"); }
23163 if (window->ParentWindow != NULL) { DebugNodeWindow(window: window->ParentWindow, label: "ParentWindow"); }
23164 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window: window->ParentWindowForFocusRoute, label: "ParentWindowForFocusRoute"); }
23165 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(windows: &window->DC.ChildWindows, label: "ChildWindows"); }
23166 if (window->ColumnsStorage.Size > 0 && TreeNode(str_id: "Columns", fmt: "Columns sets (%d)", window->ColumnsStorage.Size))
23167 {
23168 for (ImGuiOldColumns& columns : window->ColumnsStorage)
23169 DebugNodeColumns(columns: &columns);
23170 TreePop();
23171 }
23172 DebugNodeStorage(storage: &window->StateStorage, label: "Storage");
23173 TreePop();
23174}
23175
23176void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
23177{
23178 if (settings->WantDelete)
23179 BeginDisabled();
23180 Text(fmt: "0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
23181 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
23182 if (settings->WantDelete)
23183 EndDisabled();
23184}
23185
23186void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
23187{
23188 if (!TreeNode(str_id: label, fmt: "%s (%d)", label, windows->Size))
23189 return;
23190 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
23191 {
23192 PushID(ptr_id: (*windows)[i]);
23193 DebugNodeWindow(window: (*windows)[i], label: "Window");
23194 PopID();
23195 }
23196 TreePop();
23197}
23198
23199// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
23200void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
23201{
23202 for (int i = 0; i < windows_size; i++)
23203 {
23204 ImGuiWindow* window = windows[i];
23205 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
23206 continue;
23207 char buf[20];
23208 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "[%04d] Window", window->BeginOrderWithinContext);
23209 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
23210 DebugNodeWindow(window, label: buf);
23211 TreePush(str_id: buf);
23212 DebugNodeWindowsListByBeginStackParent(windows: windows + i + 1, windows_size: windows_size - i - 1, parent_in_begin_stack: window);
23213 TreePop();
23214 }
23215}
23216
23217//-----------------------------------------------------------------------------
23218// [SECTION] DEBUG LOG WINDOW
23219//-----------------------------------------------------------------------------
23220
23221void ImGui::DebugLog(const char* fmt, ...)
23222{
23223 va_list args;
23224 va_start(args, fmt);
23225 DebugLogV(fmt, args);
23226 va_end(args);
23227}
23228
23229void ImGui::DebugLogV(const char* fmt, va_list args)
23230{
23231 ImGuiContext& g = *GImGui;
23232 const int old_size = g.DebugLogBuf.size();
23233 if (g.ContextName[0] != 0)
23234 g.DebugLogBuf.appendf(fmt: "[%s] [%05d] ", g.ContextName, g.FrameCount);
23235 else
23236 g.DebugLogBuf.appendf(fmt: "[%05d] ", g.FrameCount);
23237 g.DebugLogBuf.appendfv(fmt, args);
23238 g.DebugLogIndex.append(base: g.DebugLogBuf.c_str(), old_size, new_size: g.DebugLogBuf.size());
23239 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
23240 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
23241#ifdef IMGUI_ENABLE_TEST_ENGINE
23242 // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
23243 const int new_size = g.DebugLogBuf.size();
23244 const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
23245 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
23246 IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
23247#endif
23248}
23249
23250// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
23251static void SameLineOrWrap(const ImVec2& size)
23252{
23253 ImGuiContext& g = *GImGui;
23254 ImGuiWindow* window = g.CurrentWindow;
23255 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
23256 if (window->WorkRect.Contains(r: ImRect(pos, pos + size)))
23257 ImGui::SameLine();
23258}
23259
23260static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
23261{
23262 ImGuiContext& g = *GImGui;
23263 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(text: name).x, ImGui::GetFrameHeight());
23264 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
23265
23266 bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0);
23267 if (highlight_errors)
23268 ImGui::PushStyleColor(idx: ImGuiCol_Text, col: ImLerp(a: g.Style.Colors[ImGuiCol_Text], b: ImVec4(1.0f, 0.0f, 0.0f, 1.0f), t: 0.30f));
23269 if (ImGui::CheckboxFlags(label: name, flags: &g.DebugLogFlags, flags_value: flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
23270 {
23271 g.DebugLogAutoDisableFrames = 2;
23272 g.DebugLogAutoDisableFlags |= flags;
23273 }
23274 if (highlight_errors)
23275 {
23276 ImGui::PopStyleColor();
23277 ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors);
23278 }
23279 else
23280 {
23281 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
23282 }
23283}
23284
23285void ImGui::ShowDebugLogWindow(bool* p_open)
23286{
23287 ImGuiContext& g = *GImGui;
23288 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
23289 SetNextWindowSize(size: ImVec2(0.0f, GetFontSize() * 12.0f), cond: ImGuiCond_FirstUseEver);
23290 if (!Begin(name: "Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
23291 {
23292 End();
23293 return;
23294 }
23295
23296 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
23297 CheckboxFlags(label: "All", flags: &g.DebugLogFlags, flags_value: all_enable_flags);
23298 SetItemTooltip("(except InputRouting which is spammy)");
23299
23300 ShowDebugLogFlag(name: "Errors", flags: ImGuiDebugLogFlags_EventError);
23301 ShowDebugLogFlag(name: "ActiveId", flags: ImGuiDebugLogFlags_EventActiveId);
23302 ShowDebugLogFlag(name: "Clipper", flags: ImGuiDebugLogFlags_EventClipper);
23303 ShowDebugLogFlag(name: "Docking", flags: ImGuiDebugLogFlags_EventDocking);
23304 ShowDebugLogFlag(name: "Focus", flags: ImGuiDebugLogFlags_EventFocus);
23305 ShowDebugLogFlag(name: "IO", flags: ImGuiDebugLogFlags_EventIO);
23306 ShowDebugLogFlag(name: "Font", flags: ImGuiDebugLogFlags_EventFont);
23307 ShowDebugLogFlag(name: "Nav", flags: ImGuiDebugLogFlags_EventNav);
23308 ShowDebugLogFlag(name: "Popup", flags: ImGuiDebugLogFlags_EventPopup);
23309 ShowDebugLogFlag(name: "Selection", flags: ImGuiDebugLogFlags_EventSelection);
23310 ShowDebugLogFlag(name: "Viewport", flags: ImGuiDebugLogFlags_EventViewport);
23311 ShowDebugLogFlag(name: "InputRouting", flags: ImGuiDebugLogFlags_EventInputRouting);
23312
23313 if (SmallButton(label: "Clear"))
23314 {
23315 g.DebugLogBuf.clear();
23316 g.DebugLogIndex.clear();
23317 g.DebugLogSkippedErrors = 0;
23318 }
23319 SameLine();
23320 if (SmallButton(label: "Copy"))
23321 SetClipboardText(g.DebugLogBuf.c_str());
23322 SameLine();
23323 if (SmallButton(label: "Configure Outputs.."))
23324 OpenPopup(str_id: "Outputs");
23325 if (BeginPopup(str_id: "Outputs"))
23326 {
23327 CheckboxFlags(label: "OutputToTTY", flags: &g.DebugLogFlags, flags_value: ImGuiDebugLogFlags_OutputToTTY);
23328#ifndef IMGUI_ENABLE_TEST_ENGINE
23329 BeginDisabled();
23330#endif
23331 CheckboxFlags(label: "OutputToTestEngine", flags: &g.DebugLogFlags, flags_value: ImGuiDebugLogFlags_OutputToTestEngine);
23332#ifndef IMGUI_ENABLE_TEST_ENGINE
23333 EndDisabled();
23334#endif
23335 EndPopup();
23336 }
23337
23338 BeginChild(str_id: "##log", size_arg: ImVec2(0.0f, 0.0f), child_flags: ImGuiChildFlags_Borders, window_flags: ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
23339
23340 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
23341 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
23342
23343 ImGuiListClipper clipper;
23344 clipper.Begin(items_count: g.DebugLogIndex.size());
23345 while (clipper.Step())
23346 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
23347 DebugTextUnformattedWithLocateItem(line_begin: g.DebugLogIndex.get_line_begin(base: g.DebugLogBuf.c_str(), n: line_no), line_end: g.DebugLogIndex.get_line_end(base: g.DebugLogBuf.c_str(), n: line_no));
23348 g.DebugLogFlags = backup_log_flags;
23349 if (GetScrollY() >= GetScrollMaxY())
23350 SetScrollHereY(1.0f);
23351 EndChild();
23352
23353 End();
23354}
23355
23356// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
23357void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
23358{
23359 TextUnformatted(text: line_begin, text_end: line_end);
23360 if (!IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
23361 return;
23362 ImGuiContext& g = *GImGui;
23363 ImRect text_rect = g.LastItemData.Rect;
23364 for (const char* p = line_begin; p <= line_end - 10; p++)
23365 {
23366 ImGuiID id = 0;
23367 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(s: p + 2, format: "%X", &id) != 1 || ImCharIsXdigitA(c: p[10]))
23368 continue;
23369 ImVec2 p0 = CalcTextSize(text: line_begin, text_end: p);
23370 ImVec2 p1 = CalcTextSize(text: p, text_end: p + 10);
23371 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
23372 if (IsMouseHoveringRect(r_min: g.LastItemData.Rect.Min, r_max: g.LastItemData.Rect.Max, clip: true))
23373 DebugLocateItemOnHover(target_id: id);
23374 p += 10;
23375 }
23376}
23377
23378//-----------------------------------------------------------------------------
23379// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
23380//-----------------------------------------------------------------------------
23381
23382// Draw a small cross at current CursorPos in current window's DrawList
23383void ImGui::DebugDrawCursorPos(ImU32 col)
23384{
23385 ImGuiContext& g = *GImGui;
23386 ImGuiWindow* window = g.CurrentWindow;
23387 ImVec2 pos = window->DC.CursorPos;
23388 window->DrawList->AddLine(p1: ImVec2(pos.x, pos.y - 3.0f), p2: ImVec2(pos.x, pos.y + 4.0f), col, thickness: 1.0f);
23389 window->DrawList->AddLine(p1: ImVec2(pos.x - 3.0f, pos.y), p2: ImVec2(pos.x + 4.0f, pos.y), col, thickness: 1.0f);
23390}
23391
23392// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
23393void ImGui::DebugDrawLineExtents(ImU32 col)
23394{
23395 ImGuiContext& g = *GImGui;
23396 ImGuiWindow* window = g.CurrentWindow;
23397 float curr_x = window->DC.CursorPos.x;
23398 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
23399 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
23400 window->DrawList->AddLine(p1: ImVec2(curr_x - 5.0f, line_y1), p2: ImVec2(curr_x + 5.0f, line_y1), col, thickness: 1.0f);
23401 window->DrawList->AddLine(p1: ImVec2(curr_x - 0.5f, line_y1), p2: ImVec2(curr_x - 0.5f, line_y2), col, thickness: 1.0f);
23402 window->DrawList->AddLine(p1: ImVec2(curr_x - 5.0f, line_y2), p2: ImVec2(curr_x + 5.0f, line_y2), col, thickness: 1.0f);
23403}
23404
23405// Draw last item rect in ForegroundDrawList (so it is always visible)
23406void ImGui::DebugDrawItemRect(ImU32 col)
23407{
23408 ImGuiContext& g = *GImGui;
23409 ImGuiWindow* window = g.CurrentWindow;
23410 GetForegroundDrawList(window)->AddRect(p_min: g.LastItemData.Rect.Min, p_max: g.LastItemData.Rect.Max, col);
23411}
23412
23413// [DEBUG] Locate item position/rectangle given an ID.
23414static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
23415
23416void ImGui::DebugLocateItem(ImGuiID target_id)
23417{
23418 ImGuiContext& g = *GImGui;
23419 g.DebugLocateId = target_id;
23420 g.DebugLocateFrames = 2;
23421 g.DebugBreakInLocateId = false;
23422}
23423
23424// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
23425void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
23426{
23427 if (target_id == 0 || !IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
23428 return;
23429 ImGuiContext& g = *GImGui;
23430 DebugLocateItem(target_id);
23431 GetForegroundDrawList(window: g.CurrentWindow)->AddRect(p_min: g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), p_max: g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), col: DEBUG_LOCATE_ITEM_COLOR);
23432
23433 // Can't easily use a context menu here because it will mess with focus, active id etc.
23434 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
23435 {
23436 DebugBreakButtonTooltip(keyboard_only: false, description_of_location: "in ItemAdd()");
23437 if (IsKeyChordPressed(key_chord: g.DebugBreakKeyChord))
23438 g.DebugBreakInLocateId = true;
23439 }
23440}
23441
23442void ImGui::DebugLocateItemResolveWithLastItem()
23443{
23444 ImGuiContext& g = *GImGui;
23445
23446 // [DEBUG] Debug break requested by user
23447 if (g.DebugBreakInLocateId)
23448 IM_DEBUG_BREAK();
23449
23450 ImGuiLastItemData item_data = g.LastItemData;
23451 g.DebugLocateId = 0;
23452 ImDrawList* draw_list = GetForegroundDrawList(window: g.CurrentWindow);
23453 ImRect r = item_data.Rect;
23454 r.Expand(amount: 3.0f);
23455 ImVec2 p1 = g.IO.MousePos;
23456 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);
23457 draw_list->AddRect(p_min: r.Min, p_max: r.Max, col: DEBUG_LOCATE_ITEM_COLOR);
23458 draw_list->AddLine(p1, p2, col: DEBUG_LOCATE_ITEM_COLOR);
23459}
23460
23461void ImGui::DebugStartItemPicker()
23462{
23463 ImGuiContext& g = *GImGui;
23464 g.DebugItemPickerActive = true;
23465}
23466
23467// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
23468void ImGui::UpdateDebugToolItemPicker()
23469{
23470 ImGuiContext& g = *GImGui;
23471 g.DebugItemPickerBreakId = 0;
23472 if (!g.DebugItemPickerActive)
23473 return;
23474
23475 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
23476 SetMouseCursor(ImGuiMouseCursor_Hand);
23477 if (IsKeyPressed(key: ImGuiKey_Escape))
23478 g.DebugItemPickerActive = false;
23479 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
23480 if (!change_mapping && IsMouseClicked(button: g.DebugItemPickerMouseButton) && hovered_id)
23481 {
23482 g.DebugItemPickerBreakId = hovered_id;
23483 g.DebugItemPickerActive = false;
23484 }
23485 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
23486 if (change_mapping && IsMouseClicked(button: mouse_button))
23487 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
23488 SetNextWindowBgAlpha(0.70f);
23489 if (!BeginTooltip())
23490 return;
23491 Text(fmt: "HoveredId: 0x%08X", hovered_id);
23492 Text(fmt: "Press ESC to abort picking.");
23493 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
23494 if (change_mapping)
23495 Text(fmt: "Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
23496 else
23497 TextColored(col: GetStyleColorVec4(idx: hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), fmt: "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
23498 EndTooltip();
23499}
23500
23501// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
23502void ImGui::UpdateDebugToolStackQueries()
23503{
23504 ImGuiContext& g = *GImGui;
23505 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23506
23507 // Clear hook when id stack tool is not visible
23508 g.DebugHookIdInfo = 0;
23509 if (g.FrameCount != tool->LastActiveFrame + 1)
23510 return;
23511
23512 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
23513 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
23514 const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
23515 if (tool->QueryId != query_id)
23516 {
23517 tool->QueryId = query_id;
23518 tool->StackLevel = -1;
23519 tool->Results.resize(new_size: 0);
23520 }
23521 if (query_id == 0)
23522 return;
23523
23524 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
23525 int stack_level = tool->StackLevel;
23526 if (stack_level >= 0 && stack_level < tool->Results.Size)
23527 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
23528 tool->StackLevel++;
23529
23530 // Update hook
23531 stack_level = tool->StackLevel;
23532 if (stack_level == -1)
23533 g.DebugHookIdInfo = query_id;
23534 if (stack_level >= 0 && stack_level < tool->Results.Size)
23535 {
23536 g.DebugHookIdInfo = tool->Results[stack_level].ID;
23537 tool->Results[stack_level].QueryFrameCount++;
23538 }
23539}
23540
23541// [DEBUG] ID Stack tool: hooks called by GetID() family functions
23542void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
23543{
23544 ImGuiContext& g = *GImGui;
23545 ImGuiWindow* window = g.CurrentWindow;
23546 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23547
23548 // Step 0: stack query
23549 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
23550 if (tool->StackLevel == -1)
23551 {
23552 tool->StackLevel++;
23553 tool->Results.resize(new_size: window->IDStack.Size + 1, v: ImGuiStackLevelInfo());
23554 for (int n = 0; n < window->IDStack.Size + 1; n++)
23555 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
23556 return;
23557 }
23558
23559 // Step 1+: query for individual level
23560 IM_ASSERT(tool->StackLevel >= 0);
23561 if (tool->StackLevel != window->IDStack.Size)
23562 return;
23563 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
23564 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
23565
23566 switch (data_type)
23567 {
23568 case ImGuiDataType_S32:
23569 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "%d", (int)(intptr_t)data_id);
23570 break;
23571 case ImGuiDataType_String:
23572 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen(s: (const char*)data_id), (const char*)data_id);
23573 break;
23574 case ImGuiDataType_Pointer:
23575 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "(void*)0x%p", data_id);
23576 break;
23577 case ImGuiDataType_ID:
23578 if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
23579 return;
23580 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "0x%08X [override]", id);
23581 break;
23582 default:
23583 IM_ASSERT(0);
23584 }
23585 info->QuerySuccess = true;
23586 info->DataType = data_type;
23587}
23588
23589static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
23590{
23591 ImGuiStackLevelInfo* info = &tool->Results[n];
23592 ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(id: info->ID) : NULL;
23593 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
23594 return ImFormatString(buf, buf_size, fmt: format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
23595 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
23596 return ImFormatString(buf, buf_size, fmt: (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
23597 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
23598 return (*buf = 0);
23599#ifdef IMGUI_ENABLE_TEST_ENGINE
23600 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
23601 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
23602#endif
23603 return ImFormatString(buf, buf_size, fmt: "???");
23604}
23605
23606// ID Stack Tool: Display UI
23607void ImGui::ShowIDStackToolWindow(bool* p_open)
23608{
23609 ImGuiContext& g = *GImGui;
23610 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
23611 SetNextWindowSize(size: ImVec2(0.0f, GetFontSize() * 8.0f), cond: ImGuiCond_FirstUseEver);
23612 if (!Begin(name: "Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
23613 {
23614 End();
23615 return;
23616 }
23617
23618 // Display hovered/active status
23619 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23620
23621 // Build and display path
23622 tool->ResultPathBuf.resize(size: 0);
23623 for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++)
23624 {
23625 char level_desc[256];
23626 StackToolFormatLevelInfo(tool, n: stack_n, format_for_ui: false, buf: level_desc, IM_ARRAYSIZE(level_desc));
23627 tool->ResultPathBuf.append(str: stack_n == 0 ? "//" : "/");
23628 for (int n = 0; level_desc[n]; n++)
23629 {
23630 if (level_desc[n] == '/')
23631 tool->ResultPathBuf.append(str: "\\");
23632 tool->ResultPathBuf.append(str: level_desc + n, str_end: level_desc + n + 1);
23633 }
23634 }
23635 Text(fmt: "0x%08X", tool->QueryId);
23636 SameLine();
23637 MetricsHelpMarker(desc: "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.");
23638
23639 // CTRL+C to copy path
23640 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
23641 SameLine();
23642 PushStyleVarY(idx: ImGuiStyleVar_FramePadding, val_y: 0.0f); Checkbox(label: "Ctrl+C: copy path", v: &tool->CopyToClipboardOnCtrlC); PopStyleVar();
23643 SameLine();
23644 TextColored(col: (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(), fmt: "*COPIED*");
23645 if (tool->CopyToClipboardOnCtrlC && Shortcut(key_chord: ImGuiMod_Ctrl | ImGuiKey_C, flags: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
23646 {
23647 tool->CopyToClipboardLastTime = (float)g.Time;
23648 SetClipboardText(tool->ResultPathBuf.c_str());
23649 }
23650
23651 Text(fmt: "- Path \"%s\"", tool->ResultPathBuf.c_str());
23652#ifdef IMGUI_ENABLE_TEST_ENGINE
23653 Text("- Label \"%s\"", tool->QueryId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryId) : "");
23654#endif
23655
23656 Separator();
23657
23658 // Display decorated stack
23659 tool->LastActiveFrame = g.FrameCount;
23660 if (tool->Results.Size > 0 && BeginTable(str_id: "##table", columns: 3, flags: ImGuiTableFlags_Borders))
23661 {
23662 const float id_width = CalcTextSize(text: "0xDDDDDDDD").x;
23663 TableSetupColumn(label: "Seed", flags: ImGuiTableColumnFlags_WidthFixed, init_width_or_weight: id_width);
23664 TableSetupColumn(label: "PushID", flags: ImGuiTableColumnFlags_WidthStretch);
23665 TableSetupColumn(label: "Result", flags: ImGuiTableColumnFlags_WidthFixed, init_width_or_weight: id_width);
23666 TableHeadersRow();
23667 for (int n = 0; n < tool->Results.Size; n++)
23668 {
23669 ImGuiStackLevelInfo* info = &tool->Results[n];
23670 TableNextColumn();
23671 Text(fmt: "0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
23672 TableNextColumn();
23673 StackToolFormatLevelInfo(tool, n, format_for_ui: true, buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size);
23674 TextUnformatted(text: g.TempBuffer.Data);
23675 TableNextColumn();
23676 Text(fmt: "0x%08X", info->ID);
23677 if (n == tool->Results.Size - 1)
23678 TableSetBgColor(target: ImGuiTableBgTarget_CellBg, color: GetColorU32(idx: ImGuiCol_Header));
23679 }
23680 EndTable();
23681 }
23682 End();
23683}
23684
23685#else
23686
23687void ImGui::ShowMetricsWindow(bool*) {}
23688void ImGui::ShowFontAtlas(ImFontAtlas*) {}
23689void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
23690void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
23691void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
23692void ImGui::DebugNodeFont(ImFont*) {}
23693void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {}
23694void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
23695void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
23696void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
23697void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
23698void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
23699void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
23700
23701void ImGui::ShowDebugLogWindow(bool*) {}
23702void ImGui::ShowIDStackToolWindow(bool*) {}
23703void ImGui::DebugStartItemPicker() {}
23704void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
23705
23706#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
23707
23708#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
23709// Demo helper function to select among loaded fonts.
23710// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.
23711void ImGui::ShowFontSelector(const char* label)
23712{
23713 ImGuiIO& io = GetIO();
23714 ImFont* font_current = GetFont();
23715 if (BeginCombo(label, preview_value: font_current->GetDebugName()))
23716 {
23717 for (ImFont* font : io.Fonts->Fonts)
23718 {
23719 PushID(ptr_id: (void*)font);
23720 if (Selectable(label: font->GetDebugName(), selected: font == font_current))
23721 io.FontDefault = font;
23722 if (font == font_current)
23723 SetItemDefaultFocus();
23724 PopID();
23725 }
23726 EndCombo();
23727 }
23728 SameLine();
23729 if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
23730 MetricsHelpMarker(
23731 desc: "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
23732 "- Read FAQ and docs/FONTS.md for more details.");
23733 else
23734 MetricsHelpMarker(
23735 desc: "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
23736 "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
23737 "- Read FAQ and docs/FONTS.md for more details.\n"
23738 "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
23739}
23740#endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
23741
23742//-----------------------------------------------------------------------------
23743
23744// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
23745// 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.
23746#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
23747#include "imgui_user.inl"
23748#endif
23749
23750//-----------------------------------------------------------------------------
23751
23752#endif // #ifndef IMGUI_DISABLE
23753

source code of imgui/imgui.cpp