Debian Codegraph @

source/code/Libs/imgui/imgui.cpp

raw symbols SCIP
1 // dear imgui, v1.92.3
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
45 Index of this file:
46
47 DOCUMENTATION
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
61 CODE
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
320 USING CUSTOM BACKEND / CUSTOM ENGINE
321 ------------------------------------
322
323 IMPLEMENTING 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
327 IMPLEMENTING 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
331 IMPLEMENTING 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 [there was a bug on 2025/06/12: when using the old config flags names, they were not imported correctly into the new ones, fixed on 2025/09/12]
416 - 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.
417 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/
418 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+).
419 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.
420 - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this!
421 - 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):
422 This WILL NOT map correctly to the new system! Because font will rasterize as requested size.
423 - 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.
424 - 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.
425 - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized.
426 - PushFont() API now has a REQUIRED size parameter.
427 - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize).
428 - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value.
429 - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site.
430 - Kept inline single parameter function. Will obsolete.
431 - Fonts: **IMPORTANT** on Font Merging:
432 - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph.
433 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.
434 - 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!
435 - 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.
436 After the update and when using a new backend, those glyphs may now loaded from Font Source 1!
437 - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source:
438 // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
439 static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
440 ImFontConfig cfg1;
441 cfg1.GlyphExcludeRanges = exclude_ranges;
442 io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
443 // Add Font Source 2, which expects to use the range above
444 ImFontConfig cfg2;
445 cfg2.MergeMode = true;
446 io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
447 - 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
448 - Fonts: **IMPORTANT** on Thread Safety:
449 - 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.
450 - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont().
451 - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font".
452 - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'.
453 - 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().
454 - 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).
455 - 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.
456 - 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().
457 - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327)
458 - 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.
459 - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors.
460 - Fonts: obsoleted ImFont::Scale which is not useful anymore.
461 - 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:
462 - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef.
463 - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef.
464 - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]
465 - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount.
466 - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size.
467 - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance().
468 - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels().
469 - 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.)
470 - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags.
471 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().
472 - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()
473 - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader()
474 - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1]
475 - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV().
476 - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h.
477 - old:
478 const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id);
479 ImVec2 uv0, uv1;
480 atlas->GetCustomRectUV(r, &uv0, &uv1);
481 ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1);
482 - new;
483 ImFontAtlasRect r;
484 atlas->GetCustomRect(custom_rect_id, &r);
485 ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
486 - 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.
487 - 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.
488 - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
489 - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture().
490 - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more.
491 - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition()
492 - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....);
493 - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....);
494 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.
495 - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete).
496 - 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)
497 - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead.
498 - 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.
499 - 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)
500 - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238)
501 - 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));
502 - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1));
503 - 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));
504 - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton().
505 - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize.
506 - 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.
507 - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified.
508 - 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().
509 - 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.
510 - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX.
511 - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior.
512 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.
513 the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls:
514 - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937)
515 - 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.
516 As a result, old .ini data may be partially lost (docking and tables information particularly).
517 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.
518 - 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)
519 - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
520 - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
521 - pre-1.87 backends are not supported:
522 - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
523 - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
524 - for more reference:
525 - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
526 - read https://github.com/ocornut/imgui/issues/4921
527 - 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.
528 - 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?
529 - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
530 - 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).
531 - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
532 moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
533 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!
534 - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
535 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.
536 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().
537 in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
538 - May warn: ImGui::Image((void*)MyTextureData, ...);
539 - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
540 - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData, ...);
541 - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
542 - 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)
543 - 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).
544 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)
545 - 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)
546 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()
547 - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
548 - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
549 - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
550 - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line.
551 - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660)
552 - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
553 - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278)
554 - access those via GetPlatformIO() instead of GetIO().
555 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.
556 - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder:
557 - 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)
558 - new ImageButton() since 1.89 requires an explicit 'const char* str_id'
559 - old ImageButton() before 1.89 had frame_padding' override argument.
560 - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar().
561 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
562 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
563 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
564 - you can use: GetContentRegionAvail().x
565 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
566 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
567 - instead of: GetContentRegionMax()
568 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
569 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
570 - you can use: GetContentRegionAvail() // when called from left edge of window
571 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
572 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
573 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
574 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
575 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
576 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
577 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
578 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
579 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
580 - 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.
581 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
582 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
583 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
584 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
585 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
586 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
587 - 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.
588 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
589 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
590 - old: CaptureKeyboardFromApp(bool)
591 - new: SetNextFrameWantCaptureKeyboard(bool)
592 - old: CaptureMouseFromApp(bool)
593 - new: SetNextFrameWantCaptureMouse(bool)
594 - 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).
595 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
596 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
597 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
598 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
599 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
600 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
601 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
602 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
603 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
604 for various reasons those changes makes sense. They are being made because making some of those API public.
605 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.
606 - 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)
607 - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
608 - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
609 - 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.
610 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
611 - 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)
612 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
613 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
614 - 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).
615 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
616 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
617 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.
618 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
619 - 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)
620 - 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)
621 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
622 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
623 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
624 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
625 - 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.
626 - 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.
627 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
628 - 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).
629 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.
630 - 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.
631 - old: BeginChild("Name", size, true)
632 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
633 - old: BeginChild("Name", size, false)
634 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
635 **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'**
636 - 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.
637 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
638 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
639 - 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).
640 - 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)
641 - 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).
642 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
643 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
644 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
645 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
646 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
647 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
648 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
649 - 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
650 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
651 - 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)
652 - 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).
653 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
654 - 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.
655 - 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)
656 - 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.
657 - 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.
658 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
659 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
660 - ListBoxFooter() -> use EndListBox()
661 - 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().
662 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
663 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
664 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
665 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
666 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
667 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
668 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
669 - 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.
670 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
671 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
672 it has been frequently requested by people to use our own. We had an opt-in define which was
673 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
674 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
675 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
676 - 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.
677 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
678 - 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.
679 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
680 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
681 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
682 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
683 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
684 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
685 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
686 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.
687 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
688 this will require uses of legacy backend-dependent indices to be casted, e.g.
689 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
690 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
691 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
692 - 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);
693 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
694 - 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.
695 - 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.
696 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
697 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
698 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
699 - previously this would make the window content size ~200x200:
700 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
701 - instead, please submit an item:
702 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
703 - alternative:
704 Begin(...) + Dummy(ImVec2(200,200)) + End();
705 - content size is now only extended when submitting an item!
706 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
707 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
708 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
709 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
710 - 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));
711 - 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.
712 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
713 - 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));
714 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
715 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
716 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
717 - Official backends from 1.87+ -> no issue.
718 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
719 - Custom backends not writing to io.NavInputs[] -> no issue.
720 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
721 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
722 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
723 - 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.
724 - 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.
725 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
726 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
727 - 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).
728 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
729 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
730 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
731 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
732 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
733 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
734 read https://github.com/ocornut/imgui/issues/4921 for details.
735 - 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.
736 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
737 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
738 - 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).
739 - 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.*
740 - 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.
741 - 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.
742 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
743 - 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'.
744 - 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)
745 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
746 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
747 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
748 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
749 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
750 - 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
751 - 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.
752 - 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.
753 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
754 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
755 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
756 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
757 - if you are using official backends from the source tree: you have nothing to do.
758 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
759 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
760 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
761 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
762 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
763 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
764 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
765 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
766 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
767 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
768 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
769 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
770 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.
771 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).
772 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
773 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
774 - 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.
775 - 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.
776 - 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'.
777 - 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.
778 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
779 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
780 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
781 - 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.
782 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
783 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
784 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
785 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
786 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
787 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
788 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
789 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
790 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
791 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
792 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
793 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
794 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
795 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
796 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
797 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
798 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
799 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
800 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
801 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
802 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
803 - 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).
804 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
805 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
806 - 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.
807 - 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.
808 - 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!
809 - 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().
810 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
811 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
812 - if you omitted the 'power' parameter (likely!), you are not affected.
813 - 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.
814 - 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.
815 see https://github.com/ocornut/imgui/issues/3361 for all details.
816 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.
817 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
818 - 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.
819 - 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.
820 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
821 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
822 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
823 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
824 - 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.
825 - 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.
826 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
827 - ShowTestWindow() -> use ShowDemoWindow()
828 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
829 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
830 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f))
831 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
832 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
833 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
834 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
835 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
836 - 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.
837 - 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).
838 - 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.
839 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
840 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
841 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
842 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
843 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
844 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
845 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
846 - ImFont::Glyph -> use ImFontGlyph
847 - 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.
848 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.
849 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).
850 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
851 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
852 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
853 - 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.
854 - 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
855 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.
856 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.
857 Please reach out if you are affected.
858 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
859 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
860 - 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.
861 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
862 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
863 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
864 - 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!
865 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
866 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
867 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
868 - 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.
869 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
870 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
871 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
872 - 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.
873 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
874 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
875 - 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.
876 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
877 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
878 - 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).
879 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
880 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
881 - 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.
882 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
883 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
884 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
885 - 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.).
886 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
887 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
888 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
889 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
890 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
891 - 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.
892 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
893 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.
894 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.
895 - 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",
896 consistent with other functions. Kept redirection functions (will obsolete).
897 - 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.
898 - 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).
899 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
900 - 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.
901 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
902 - 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.
903 - 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.
904 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
905 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
906 - removed Shutdown() function, as DestroyContext() serve this purpose.
907 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
908 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
909 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
910 - 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.
911 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
912 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
913 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
914 - 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.
915 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
916 - 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
917 - 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.
918 - 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.
919 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
920 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
921 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
922 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
923 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
924 - 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.
925 - 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.
926 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.
927 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
928 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
929 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
930 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
931 - 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.
932 - 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.
933 - 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.
934 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
935 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
936 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
937 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
938 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
939 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
940 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
941 - 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).
942 - 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)".
943 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
944 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
945 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
946 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
947 - 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.
948 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
949 - 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.
950 - 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).
951 - 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).
952 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
953 - 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.
954 - 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.
955 - 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))'
956 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
957 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
958 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
959 - 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().
960 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
961 - 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.
962 - 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.
963 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
964 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.
965 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:
966 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); }
967 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.
968 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
969 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
970 - 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).
971 - 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.
972 - 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).
973 - 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)
974 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
975 - 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.
976 - 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.
977 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
978 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
979 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
980 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.
981 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!
982 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
983 - 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.
984 - 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
985 - 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.
986 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
987 - 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.
988 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
989 - 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.
990 - the signature of the io.RenderDrawListsFn handler has changed!
991 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
992 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
993 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
994 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
995 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
996 - 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.
997 - 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!
998 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
999 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
1000 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
1001 - 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.
1002 - 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
1003 - 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!
1004 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
1005 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
1006 - 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.
1007 - 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.
1008 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
1009 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
1010 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
1011 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
1012 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
1013 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
1014 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
1015 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
1016 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
1017 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
1018 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
1019 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
1020 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
1021 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
1022 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
1023 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
1024 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
1025 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
1026 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
1027 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
1028 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.
1029 - 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()
1030 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
1031 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
1032 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
1033 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
1034 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
1035 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
1036 - 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)
1037 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
1038 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
1039 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
1040 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
1041 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
1042 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
1043
1044
1045 FREQUENTLY ASKED QUESTIONS (FAQ)
1046 ================================
1047
1048 Read all answers online:
1049 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
1050 Read all answers locally (with a text editor or ideally a Markdown viewer):
1051 docs/FAQ.md
1052 Some answers are copied down here to facilitate searching in code.
1053
1054 Q&A: Basics
1055 ===========
1056
1057 Q: Where is the documentation?
1058 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
1059 - Run the examples/ applications and explore them.
1060 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
1061 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
1062 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
1063 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
1064 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
1065 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
1066 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
1067 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
1068 - Your programming IDE is your friend, find the type or function declaration to find comments
1069 associated with it.
1070
1071 Q: What is this library called?
1072 Q: Which version should I get?
1073 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
1074 >> See https://www.dearimgui.com/faq for details.
1075
1076 Q&A: Integration
1077 ================
1078
1079 Q: How to get started?
1080 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
1081
1082 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
1083 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
1084 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
1085
1086 Q. How can I enable keyboard or gamepad controls?
1087 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
1088 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
1089 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
1090 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
1091 >> See https://www.dearimgui.com/faq
1092
1093 Q&A: Usage
1094 ----------
1095
1096 Q: About the ID Stack system..
1097 - Why is my widget not reacting when I click on it?
1098 - How can I have widgets with an empty label?
1099 - How can I have multiple widgets with the same label?
1100 - How can I have multiple windows with the same label?
1101 Q: How can I display an image? What is ImTextureID, how does it work?
1102 Q: How can I use my own math types instead of ImVec2?
1103 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
1104 Q: How can I display custom shapes? (using low-level ImDrawList API)
1105 >> See https://www.dearimgui.com/faq
1106
1107 Q&A: Fonts, Text
1108 ================
1109
1110 Q: How should I handle DPI in my application?
1111 Q: How can I load a different font than the default?
1112 Q: How can I easily use icons in my application?
1113 Q: How can I load multiple fonts?
1114 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
1115 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
1116
1117 Q&A: Concerns
1118 =============
1119
1120 Q: Who uses Dear ImGui?
1121 Q: Can you create elaborate/serious tools with Dear ImGui?
1122 Q: Can you reskin the look of Dear ImGui?
1123 Q: Why using C++ (as opposed to C)?
1124 >> See https://www.dearimgui.com/faq
1125
1126 Q&A: Community
1127 ==============
1128
1129 Q: How can I help?
1130 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1131 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1132 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1133 >>> See https://github.com/ocornut/imgui/wiki/Funding
1134 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1135 - 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!
1136 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1137 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1138 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1139 - 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).
1140
1141 */
1142
1143 //-------------------------------------------------------------------------
1144 // [SECTION] INCLUDES
1145 //-------------------------------------------------------------------------
1146
1147 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1148 #define _CRT_SECURE_NO_WARNINGS
1149 #endif
1150
1151 #ifndef IMGUI_DEFINE_MATH_OPERATORS
1152 #define IMGUI_DEFINE_MATH_OPERATORS
1153 #endif
1154
1155 #include "imgui.h"
1156 #ifndef IMGUI_DISABLE
1157 #include "imgui_internal.h"
1158
1159 // System includes
1160 #include <stdio.h> // vsnprintf, sscanf, printf
1161 #include <stdint.h> // intptr_t
1162
1163 // [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1164 #if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1165 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1166 #endif
1167
1168 // [Windows] OS specific includes (optional)
1169 #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)
1170 #define IMGUI_DISABLE_WIN32_FUNCTIONS
1171 #endif
1172 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1173 #ifndef WIN32_LEAN_AND_MEAN
1174 #define WIN32_LEAN_AND_MEAN
1175 #endif
1176 #ifndef NOMINMAX
1177 #define NOMINMAX
1178 #endif
1179 #ifndef __MINGW32__
1180 #include <Windows.h> // _wfopen, OpenClipboard
1181 #else
1182 #include <windows.h>
1183 #endif
1184 #if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
1185 // The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1186 #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1187 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1188 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1189 #endif
1190 #endif
1191
1192 // [Apple] OS specific includes
1193 #if defined(__APPLE__)
1194 #include <TargetConditionals.h>
1195 #endif
1196
1197 // Visual Studio warnings
1198 #ifdef _MSC_VER
1199 #pragma warning (disable: 4127) // condition expression is constant
1200 #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1201 #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1202 #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1203 #endif
1204 #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).
1205 #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1206 #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1207 #endif
1208
1209 // Clang/GCC warnings with -Weverything
1210 #if defined(__clang__)
1211 #if __has_warning("-Wunknown-warning-option")
1212 #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!
1213 #endif
1214 #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1215 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1216 #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.
1217 #pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int'
1218 #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.
1219 #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.
1220 #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.
1221 #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1222 #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1223 #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1224 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1225 #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.
1226 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1227 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1228 #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
1229 #pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
1230 #elif defined(__GNUC__)
1231 // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1232 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1233 #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1234 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1235 #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
1236 #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
1237 #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1238 #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1239 #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1240 #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1241 #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
1242 #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
1243 #endif
1244
1245 // Debug options
1246 #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.
1247 #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1248
1249 // Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls.
1250 static const float FONT_DEFAULT_SIZE = 20.0f;
1251
1252 // 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.
1253 static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1254 static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1255 static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1256 static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1257 static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1258
1259 // Tooltip offset
1260 static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1261 static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale
1262 static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale
1263
1264 // Docking
1265 static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1266
1267 //-------------------------------------------------------------------------
1268 // [SECTION] FORWARD DECLARATIONS
1269 //-------------------------------------------------------------------------
1270
1271 static void SetCurrentWindow(ImGuiWindow* window);
1272 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1273 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1274
1275 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1276
1277 // Settings
1278 static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1279 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1280 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1281 static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1282 static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1283
1284 // Platform Dependents default implementation for ImGuiPlatformIO functions
1285 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx);
1286 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text);
1287 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1288 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1289
1290 namespace ImGui
1291 {
1292 // Item
1293 static void ItemHandleShortcut(ImGuiID id);
1294
1295 // Window Focus
1296 static int FindWindowFocusIndex(ImGuiWindow* window);
1297 static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags);
1298
1299 // Navigation
1300 static void NavUpdate();
1301 static void NavUpdateWindowing();
1302 static void NavUpdateWindowingApplyFocus(ImGuiWindow* window);
1303 static void NavUpdateWindowingOverlay();
1304 static void NavUpdateCancelRequest();
1305 static void NavUpdateCreateMoveRequest();
1306 static void NavUpdateCreateTabbingRequest();
1307 static float NavUpdatePageUpPageDown();
1308 static inline void NavUpdateAnyRequestFlag();
1309 static void NavUpdateCreateWrappingRequest();
1310 static void NavEndFrame();
1311 static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb);
1312 static void NavApplyItemToResult(ImGuiNavItemData* result);
1313 static void NavProcessItem();
1314 static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1315 static ImGuiInputSource NavCalcPreferredRefPosSource();
1316 static ImVec2 NavCalcPreferredRefPos();
1317 static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1318 static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1319 static void NavRestoreLayer(ImGuiNavLayer layer);
1320
1321 // Error Checking and Debug Tools
1322 static void ErrorCheckNewFrameSanityChecks();
1323 static void ErrorCheckEndFrameSanityChecks();
1324 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
1325 static void UpdateDebugToolItemPicker();
1326 static void UpdateDebugToolStackQueries();
1327 static void UpdateDebugToolFlashStyleColor();
1328 #endif
1329
1330 // Inputs
1331 static void UpdateKeyboardInputs();
1332 static void UpdateMouseInputs();
1333 static void UpdateMouseWheel();
1334 static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1335
1336 // Misc
1337 static void UpdateFontsNewFrame();
1338 static void UpdateFontsEndFrame();
1339 static void UpdateTexturesNewFrame();
1340 static void UpdateTexturesEndFrame();
1341 static void UpdateSettings();
1342 static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1343 static void RenderWindowOuterBorders(ImGuiWindow* window);
1344 static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1345 static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1346 static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1347 static void RenderDimmedBackgrounds();
1348 static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1349 static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect);
1350
1351 // Viewports
1352 const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1353 static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1354 static void DestroyViewport(ImGuiViewportP* viewport);
1355 static void UpdateViewportsNewFrame();
1356 static void UpdateViewportsEndFrame();
1357 static void WindowSelectViewport(ImGuiWindow* window);
1358 static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1359 static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1360 static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1361 static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1362 static int FindPlatformMonitorForPos(const ImVec2& pos);
1363 static int FindPlatformMonitorForRect(const ImRect& r);
1364 static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1365
1366 }
1367
1368 //-----------------------------------------------------------------------------
1369 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
1370 //-----------------------------------------------------------------------------
1371
1372 // DLL users:
1373 // - Heaps and globals are not shared across DLL boundaries!
1374 // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1375 // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1376 // - 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.
1377 // - 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).
1378
1379 // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1380 // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1381 // Change to a different context by calling ImGui::SetCurrentContext().
1382 // - Important: Dear ImGui functions are not thread-safe because of this pointer.
1383 // If you want thread-safety to allow N threads to access N different contexts:
1384 // - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1385 // struct ImGuiContext;
1386 // extern thread_local ImGuiContext* MyImGuiTLS;
1387 // #define GImGui MyImGuiTLS
1388 // 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.
1389 // - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1390 // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1391 // - DLL users: read comments above.
1392 #ifndef GImGui
1393 ImGuiContext* GImGui = NULL;
1394 #endif
1395
1396 // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1397 // - 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.
1398 // - DLL users: read comments above.
1399 #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1400 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1401 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1402 #else
1403 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1404 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1405 #endif
1406 static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1407 static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1408 static void* GImAllocatorUserData = NULL;
1409
1410 //-----------------------------------------------------------------------------
1411 // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
1412 //-----------------------------------------------------------------------------
1413
1414 ImGuiStyle::ImGuiStyle()
1415 {
1416 FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame.
1417 FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user.
1418 FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
1419
1420 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1421 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1422 WindowPadding = ImVec2(8,8); // Padding within a window
1423 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.
1424 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1425 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.
1426 WindowMinSize = ImVec2(32,32); // Minimum window size
1427 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1428 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1429 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1430 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1431 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1432 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1433 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1434 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1435 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1436 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1437 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1438 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1439 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!
1440 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1441 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1442 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1443 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1444 ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axises)
1445 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1446 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1447 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1448 ImageBorderSize = 0.0f; // Thickness of border around tabs.
1449 TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1450 TabBorderSize = 0.0f; // Thickness of border around tabs.
1451 TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
1452 TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy.
1453 TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
1454 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.
1455 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1456 TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1457 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1458 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1459 TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone;
1460 TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
1461 TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line.
1462 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1463 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1464 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.
1465 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText()
1466 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1467 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.
1468 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.
1469 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.
1470 DockingNodeHasCloseButton = true; // Docking nodes have their own CloseButton() to close all docked windows.
1471 DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
1472 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1473 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1474 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1475 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1476 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.
1477 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.
1478
1479 // Behaviors
1480 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1481 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1482 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1483 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1484 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1485
1486 // [Internal]
1487 _MainScale = 1.0f;
1488 _NextFrameFontSizeBase = 0.0f;
1489
1490 // Default theme
1491 ImGui::StyleColorsDark(this);
1492 }
1493
1494
1495 // Scale all spacing/padding/thickness values. Do not scale fonts.
1496 // 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.
1497 void ImGuiStyle::ScaleAllSizes(float scale_factor)
1498 {
1499 _MainScale *= scale_factor;
1500 WindowPadding = ImTrunc(WindowPadding * scale_factor);
1501 WindowRounding = ImTrunc(WindowRounding * scale_factor);
1502 WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1503 WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor);
1504 ChildRounding = ImTrunc(ChildRounding * scale_factor);
1505 PopupRounding = ImTrunc(PopupRounding * scale_factor);
1506 FramePadding = ImTrunc(FramePadding * scale_factor);
1507 FrameRounding = ImTrunc(FrameRounding * scale_factor);
1508 ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1509 ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1510 CellPadding = ImTrunc(CellPadding * scale_factor);
1511 TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1512 IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1513 ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1514 ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1515 ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1516 ScrollbarPadding = ImTrunc(ScrollbarPadding * scale_factor);
1517 GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1518 GrabRounding = ImTrunc(GrabRounding * scale_factor);
1519 LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1520 ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor);
1521 TabRounding = ImTrunc(TabRounding * scale_factor);
1522 TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor);
1523 TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor);
1524 TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected;
1525 TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected;
1526 TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
1527 TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor);
1528 SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1529 DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1530 DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1531 DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1532 MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1533 }
1534
1535 ImGuiIO::ImGuiIO()
1536 {
1537 // Most fields are initialized with zero
1538 memset(this, 0, sizeof(*this));
1539 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1540
1541 // Settings
1542 ConfigFlags = ImGuiConfigFlags_None;
1543 BackendFlags = ImGuiBackendFlags_None;
1544 DisplaySize = ImVec2(-1.0f, -1.0f);
1545 DeltaTime = 1.0f / 60.0f;
1546 IniSavingRate = 5.0f;
1547 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).
1548 LogFilename = "imgui_log.txt";
1549 UserData = NULL;
1550
1551 Fonts = NULL;
1552 FontDefault = NULL;
1553 FontAllowUserScaling = false;
1554 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1555 FontGlobalScale = 1.0f; // Use style.FontScaleMain instead!
1556 #endif
1557 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1558
1559 // Keyboard/Gamepad Navigation options
1560 ConfigNavSwapGamepadButtons = false;
1561 ConfigNavMoveSetMousePos = false;
1562 ConfigNavCaptureKeyboard = true;
1563 ConfigNavEscapeClearFocusItem = true;
1564 ConfigNavEscapeClearFocusWindow = false;
1565 ConfigNavCursorVisibleAuto = true;
1566 ConfigNavCursorVisibleAlways = false;
1567
1568 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1569 ConfigDockingNoSplit = false;
1570 ConfigDockingWithShift = false;
1571 ConfigDockingAlwaysTabBar = false;
1572 ConfigDockingTransparentPayload = false;
1573
1574 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1575 ConfigViewportsNoAutoMerge = false;
1576 ConfigViewportsNoTaskBarIcon = false;
1577 ConfigViewportsNoDecoration = true;
1578 ConfigViewportsNoDefaultParent = false;
1579 ConfigViewportPlatformFocusSetsImGuiFocus = true;
1580
1581 // Miscellaneous options
1582 MouseDrawCursor = false;
1583 #ifdef __APPLE__
1584 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1585 #else
1586 ConfigMacOSXBehaviors = false;
1587 #endif
1588 ConfigInputTrickleEventQueue = true;
1589 ConfigInputTextCursorBlink = true;
1590 ConfigInputTextEnterKeepActive = false;
1591 ConfigDragClickToInputText = false;
1592 ConfigWindowsResizeFromEdges = true;
1593 ConfigWindowsMoveFromTitleBarOnly = false;
1594 ConfigWindowsCopyContentsWithCtrlC = false;
1595 ConfigScrollbarScrollByPage = true;
1596 ConfigMemoryCompactTimer = 60.0f;
1597 ConfigDebugIsDebuggerPresent = false;
1598 ConfigDebugHighlightIdConflicts = true;
1599 ConfigDebugHighlightIdConflictsShowItemPicker = true;
1600 ConfigDebugBeginReturnValueOnce = false;
1601 ConfigDebugBeginReturnValueLoop = false;
1602
1603 ConfigErrorRecovery = true;
1604 ConfigErrorRecoveryEnableAssert = true;
1605 ConfigErrorRecoveryEnableDebugLog = true;
1606 ConfigErrorRecoveryEnableTooltip = true;
1607
1608 // Inputs Behaviors
1609 MouseDoubleClickTime = 0.30f;
1610 MouseDoubleClickMaxDist = 6.0f;
1611 MouseDragThreshold = 6.0f;
1612 KeyRepeatDelay = 0.275f;
1613 KeyRepeatRate = 0.050f;
1614
1615 // Platform Functions
1616 // Note: Initialize() will setup default clipboard/ime handlers.
1617 BackendPlatformName = BackendRendererName = NULL;
1618 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1619
1620 // Input (NB: we already have memset zero the entire structure!)
1621 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1622 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1623 MouseSource = ImGuiMouseSource_Mouse;
1624 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1625 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1626 AppAcceptingEvents = true;
1627 }
1628
1629 // Pass in translated ASCII characters for text input.
1630 // - with glfw you can get those from the callback set in glfwSetCharCallback()
1631 // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1632 // FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1633 void ImGuiIO::AddInputCharacter(unsigned int c)
1634 {
1635 IM_ASSERT(Ctx != NULL);
1636 ImGuiContext& g = *Ctx;
1637 if (c == 0 || !AppAcceptingEvents)
1638 return;
1639
1640 ImGuiInputEvent e;
1641 e.Type = ImGuiInputEventType_Text;
1642 e.Source = ImGuiInputSource_Keyboard;
1643 e.EventId = g.InputEventsNextEventId++;
1644 e.Text.Char = c;
1645 g.InputEventsQueue.push_back(e);
1646 }
1647
1648 // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1649 // we should save the high surrogate.
1650 void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1651 {
1652 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1653 return;
1654
1655 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1656 {
1657 if (InputQueueSurrogate != 0)
1658 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1659 InputQueueSurrogate = c;
1660 return;
1661 }
1662
1663 ImWchar cp = c;
1664 if (InputQueueSurrogate != 0)
1665 {
1666 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1667 {
1668 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1669 }
1670 else
1671 {
1672 #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1673 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1674 #else
1675 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1676 #endif
1677 }
1678
1679 InputQueueSurrogate = 0;
1680 }
1681 AddInputCharacter((unsigned)cp);
1682 }
1683
1684 void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1685 {
1686 if (!AppAcceptingEvents)
1687 return;
1688 while (*utf8_chars != 0)
1689 {
1690 unsigned int c = 0;
1691 utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1692 AddInputCharacter(c);
1693 }
1694 }
1695
1696 // Clear all incoming events.
1697 void ImGuiIO::ClearEventsQueue()
1698 {
1699 IM_ASSERT(Ctx != NULL);
1700 ImGuiContext& g = *Ctx;
1701 g.InputEventsQueue.clear();
1702 }
1703
1704 // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1705 void ImGuiIO::ClearInputKeys()
1706 {
1707 ImGuiContext& g = *Ctx;
1708 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
1709 {
1710 if (ImGui::IsMouseKey((ImGuiKey)key))
1711 continue;
1712 ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
1713 key_data->Down = false;
1714 key_data->DownDuration = -1.0f;
1715 key_data->DownDurationPrev = -1.0f;
1716 }
1717 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1718 KeyMods = ImGuiMod_None;
1719 InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1720 }
1721
1722 void ImGuiIO::ClearInputMouse()
1723 {
1724 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1725 {
1726 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
1727 key_data->Down = false;
1728 key_data->DownDuration = -1.0f;
1729 key_data->DownDurationPrev = -1.0f;
1730 }
1731 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1732 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1733 {
1734 MouseDown[n] = false;
1735 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1736 }
1737 MouseWheel = MouseWheelH = 0.0f;
1738 }
1739
1740 // Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1741 // Current frame character buffer is now also cleared by ClearInputKeys().
1742 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1743 void ImGuiIO::ClearInputCharacters()
1744 {
1745 InputQueueCharacters.resize(0);
1746 }
1747 #endif
1748
1749 static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1750 {
1751 ImGuiContext& g = *ctx;
1752 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1753 {
1754 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1755 if (e->Type != type)
1756 continue;
1757 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1758 continue;
1759 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1760 continue;
1761 return e;
1762 }
1763 return NULL;
1764 }
1765
1766 // Queue a new key down/up event.
1767 // - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1768 // - bool down: Is the key down? use false to signify a key release.
1769 // - float analog_value: 0.0f..1.0f
1770 // IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1771 // WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1772 void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1773 {
1774 //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); }
1775 IM_ASSERT(Ctx != NULL);
1776 if (key == ImGuiKey_None || !AppAcceptingEvents)
1777 return;
1778 ImGuiContext& g = *Ctx;
1779 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.
1780 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1781
1782 // MacOS: swap Cmd(Super) and Ctrl
1783 if (g.IO.ConfigMacOSXBehaviors)
1784 {
1785 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1786 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1787 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1788 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1789 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1790 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1791 }
1792
1793 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1794 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1795 const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1796 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1797 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1798 if (latest_key_down == down && latest_key_analog == analog_value)
1799 return;
1800
1801 // Add event
1802 ImGuiInputEvent e;
1803 e.Type = ImGuiInputEventType_Key;
1804 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1805 e.EventId = g.InputEventsNextEventId++;
1806 e.Key.Key = key;
1807 e.Key.Down = down;
1808 e.Key.AnalogValue = analog_value;
1809 g.InputEventsQueue.push_back(e);
1810 }
1811
1812 void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1813 {
1814 if (!AppAcceptingEvents)
1815 return;
1816 AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1817 }
1818
1819 // [Optional] Call after AddKeyEvent().
1820 // Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1821 // 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.
1822 void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1823 {
1824 if (key == ImGuiKey_None)
1825 return;
1826 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1827 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1828 IM_UNUSED(key); // Yet unused
1829 IM_UNUSED(native_keycode); // Yet unused
1830 IM_UNUSED(native_scancode); // Yet unused
1831 IM_UNUSED(native_legacy_index); // Yet unused
1832 }
1833
1834 // 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.
1835 void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1836 {
1837 AppAcceptingEvents = accepting_events;
1838 }
1839
1840 // Queue a mouse move event
1841 void ImGuiIO::AddMousePosEvent(float x, float y)
1842 {
1843 IM_ASSERT(Ctx != NULL);
1844 ImGuiContext& g = *Ctx;
1845 if (!AppAcceptingEvents)
1846 return;
1847
1848 // Apply same flooring as UpdateMouseInputs()
1849 ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1850
1851 // Filter duplicate
1852 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1853 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1854 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1855 return;
1856
1857 ImGuiInputEvent e;
1858 e.Type = ImGuiInputEventType_MousePos;
1859 e.Source = ImGuiInputSource_Mouse;
1860 e.EventId = g.InputEventsNextEventId++;
1861 e.MousePos.PosX = pos.x;
1862 e.MousePos.PosY = pos.y;
1863 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1864 g.InputEventsQueue.push_back(e);
1865 }
1866
1867 void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1868 {
1869 IM_ASSERT(Ctx != NULL);
1870 ImGuiContext& g = *Ctx;
1871 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1872 if (!AppAcceptingEvents)
1873 return;
1874
1875 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1876 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1877 {
1878 // Order of both statements matters: this event will still release mouse button 1
1879 mouse_button = 1;
1880 if (!down)
1881 MouseCtrlLeftAsRightClick = false;
1882 }
1883
1884 // Filter duplicate
1885 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1886 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1887 if (latest_button_down == down)
1888 return;
1889
1890 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1891 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1892 // - At this point we want from !down to down, so this is handling the initial press.
1893 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1894 {
1895 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1896 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1897 {
1898 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1899 MouseCtrlLeftAsRightClick = true;
1900 AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1901 return;
1902 }
1903 }
1904
1905 ImGuiInputEvent e;
1906 e.Type = ImGuiInputEventType_MouseButton;
1907 e.Source = ImGuiInputSource_Mouse;
1908 e.EventId = g.InputEventsNextEventId++;
1909 e.MouseButton.Button = mouse_button;
1910 e.MouseButton.Down = down;
1911 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1912 g.InputEventsQueue.push_back(e);
1913 }
1914
1915 // Queue a mouse wheel event (some mouse/API may only have a Y component)
1916 void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1917 {
1918 IM_ASSERT(Ctx != NULL);
1919 ImGuiContext& g = *Ctx;
1920
1921 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1922 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1923 return;
1924
1925 ImGuiInputEvent e;
1926 e.Type = ImGuiInputEventType_MouseWheel;
1927 e.Source = ImGuiInputSource_Mouse;
1928 e.EventId = g.InputEventsNextEventId++;
1929 e.MouseWheel.WheelX = wheel_x;
1930 e.MouseWheel.WheelY = wheel_y;
1931 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1932 g.InputEventsQueue.push_back(e);
1933 }
1934
1935 // This is not a real event, the data is latched in order to be stored in actual Mouse events.
1936 // This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1937 void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1938 {
1939 IM_ASSERT(Ctx != NULL);
1940 ImGuiContext& g = *Ctx;
1941 g.InputEventsNextMouseSource = source;
1942 }
1943
1944 void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1945 {
1946 IM_ASSERT(Ctx != NULL);
1947 ImGuiContext& g = *Ctx;
1948 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1949 if (!AppAcceptingEvents)
1950 return;
1951
1952 // Filter duplicate
1953 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1954 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1955 if (latest_viewport_id == viewport_id)
1956 return;
1957
1958 ImGuiInputEvent e;
1959 e.Type = ImGuiInputEventType_MouseViewport;
1960 e.Source = ImGuiInputSource_Mouse;
1961 e.MouseViewport.HoveredViewportID = viewport_id;
1962 g.InputEventsQueue.push_back(e);
1963 }
1964
1965 void ImGuiIO::AddFocusEvent(bool focused)
1966 {
1967 IM_ASSERT(Ctx != NULL);
1968 ImGuiContext& g = *Ctx;
1969
1970 // Filter duplicate
1971 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1972 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1973 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1974 return;
1975
1976 ImGuiInputEvent e;
1977 e.Type = ImGuiInputEventType_Focus;
1978 e.EventId = g.InputEventsNextEventId++;
1979 e.AppFocused.Focused = focused;
1980 g.InputEventsQueue.push_back(e);
1981 }
1982
1983 ImGuiPlatformIO::ImGuiPlatformIO()
1984 {
1985 // Most fields are initialized with zero
1986 memset(this, 0, sizeof(*this));
1987 Platform_LocaleDecimalPoint = '.';
1988 }
1989
1990 //-----------------------------------------------------------------------------
1991 // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1992 //-----------------------------------------------------------------------------
1993
1994 ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1995 {
1996 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1997 ImVec2 p_last = p1;
1998 ImVec2 p_closest;
1999 float p_closest_dist2 = FLT_MAX;
2000 float t_step = 1.0f / (float)num_segments;
2001 for (int i_step = 1; i_step <= num_segments; i_step++)
2002 {
2003 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
2004 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
2005 float dist2 = ImLengthSqr(p - p_line);
2006 if (dist2 < p_closest_dist2)
2007 {
2008 p_closest = p_line;
2009 p_closest_dist2 = dist2;
2010 }
2011 p_last = p_current;
2012 }
2013 return p_closest;
2014 }
2015
2016 // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
2017 static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
2018 {
2019 float dx = x4 - x1;
2020 float dy = y4 - y1;
2021 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
2022 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
2023 d2 = (d2 >= 0) ? d2 : -d2;
2024 d3 = (d3 >= 0) ? d3 : -d3;
2025 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
2026 {
2027 ImVec2 p_current(x4, y4);
2028 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
2029 float dist2 = ImLengthSqr(p - p_line);
2030 if (dist2 < p_closest_dist2)
2031 {
2032 p_closest = p_line;
2033 p_closest_dist2 = dist2;
2034 }
2035 p_last = p_current;
2036 }
2037 else if (level < 10)
2038 {
2039 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
2040 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
2041 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
2042 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
2043 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
2044 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
2045 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
2046 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
2047 }
2048 }
2049
2050 // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
2051 // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
2052 ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
2053 {
2054 IM_ASSERT(tess_tol > 0.0f);
2055 ImVec2 p_last = p1;
2056 ImVec2 p_closest;
2057 float p_closest_dist2 = FLT_MAX;
2058 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
2059 return p_closest;
2060 }
2061
2062 ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
2063 {
2064 ImVec2 ap = p - a;
2065 ImVec2 ab_dir = b - a;
2066 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
2067 if (dot < 0.0f)
2068 return a;
2069 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
2070 if (dot > ab_len_sqr)
2071 return b;
2072 return a + ab_dir * dot / ab_len_sqr;
2073 }
2074
2075 bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2076 {
2077 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
2078 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
2079 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
2080 return ((b1 == b2) && (b2 == b3));
2081 }
2082
2083 void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
2084 {
2085 ImVec2 v0 = b - a;
2086 ImVec2 v1 = c - a;
2087 ImVec2 v2 = p - a;
2088 const float denom = v0.x * v1.y - v1.x * v0.y;
2089 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
2090 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
2091 out_u = 1.0f - out_v - out_w;
2092 }
2093
2094 ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2095 {
2096 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
2097 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
2098 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
2099 float dist2_ab = ImLengthSqr(p - proj_ab);
2100 float dist2_bc = ImLengthSqr(p - proj_bc);
2101 float dist2_ca = ImLengthSqr(p - proj_ca);
2102 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
2103 if (m == dist2_ab)
2104 return proj_ab;
2105 if (m == dist2_bc)
2106 return proj_bc;
2107 return proj_ca;
2108 }
2109
2110 //-----------------------------------------------------------------------------
2111 // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
2112 //-----------------------------------------------------------------------------
2113
2114 // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
2115 int ImStricmp(const char* str1, const char* str2)
2116 {
2117 int d;
2118 while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
2119 return d;
2120 }
2121
2122 int ImStrnicmp(const char* str1, const char* str2, size_t count)
2123 {
2124 int d = 0;
2125 while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
2126 return d;
2127 }
2128
2129 void ImStrncpy(char* dst, const char* src, size_t count)
2130 {
2131 if (count < 1)
2132 return;
2133 if (count > 1)
2134 strncpy(dst, src, count - 1); // FIXME-OPT: strncpy not only doesn't guarantee 0-termination, it also always writes the whole array
2135 dst[count - 1] = 0;
2136 }
2137
2138 char* ImStrdup(const char* str)
2139 {
2140 size_t len = ImStrlen(str);
2141 void* buf = IM_ALLOC(len + 1);
2142 return (char*)memcpy(buf, (const void*)str, len + 1);
2143 }
2144
2145 void* ImMemdup(const void* src, size_t size)
2146 {
2147 void* dst = IM_ALLOC(size);
2148 return memcpy(dst, src, size);
2149 }
2150
2151 char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
2152 {
2153 size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1;
2154 size_t src_size = ImStrlen(src) + 1;
2155 if (dst_buf_size < src_size)
2156 {
2157 IM_FREE(dst);
2158 dst = (char*)IM_ALLOC(src_size);
2159 if (p_dst_size)
2160 *p_dst_size = src_size;
2161 }
2162 return (char*)memcpy(dst, (const void*)src, src_size);
2163 }
2164
2165 const char* ImStrchrRange(const char* str, const char* str_end, char c)
2166 {
2167 const char* p = (const char*)ImMemchr(str, (int)c, str_end - str);
2168 return p;
2169 }
2170
2171 int ImStrlenW(const ImWchar* str)
2172 {
2173 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
2174 int n = 0;
2175 while (*str++) n++;
2176 return n;
2177 }
2178
2179 // Find end-of-line. Return pointer will point to either first \n, either str_end.
2180 const char* ImStreolRange(const char* str, const char* str_end)
2181 {
2182 const char* p = (const char*)ImMemchr(str, '\n', str_end - str);
2183 return p ? p : str_end;
2184 }
2185
2186 const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
2187 {
2188 IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin));
2189 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2190 buf_mid_line--;
2191 return buf_mid_line;
2192 }
2193
2194 const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2195 {
2196 if (!needle_end)
2197 needle_end = needle + ImStrlen(needle);
2198
2199 const char un0 = (char)ImToUpper(*needle);
2200 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2201 {
2202 if (ImToUpper(*haystack) == un0)
2203 {
2204 const char* b = needle + 1;
2205 for (const char* a = haystack + 1; b < needle_end; a++, b++)
2206 if (ImToUpper(*a) != ImToUpper(*b))
2207 break;
2208 if (b == needle_end)
2209 return haystack;
2210 }
2211 haystack++;
2212 }
2213 return NULL;
2214 }
2215
2216 // 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.
2217 void ImStrTrimBlanks(char* buf)
2218 {
2219 char* p = buf;
2220 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
2221 p++;
2222 char* p_start = p;
2223 while (*p != 0) // Find end of string
2224 p++;
2225 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
2226 p--;
2227 if (p_start != buf) // Copy memory if we had leading blanks
2228 memmove(buf, p_start, p - p_start);
2229 buf[p - p_start] = 0; // Zero terminate
2230 }
2231
2232 const char* ImStrSkipBlank(const char* str)
2233 {
2234 while (str[0] == ' ' || str[0] == '\t')
2235 str++;
2236 return str;
2237 }
2238
2239 // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2240 // 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.
2241 // B) When buf==NULL vsnprintf() will return the output size.
2242 #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2243
2244 // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2245 // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2246 // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2247 // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2248 #ifdef IMGUI_USE_STB_SPRINTF
2249 #ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2250 #define STB_SPRINTF_IMPLEMENTATION
2251 #endif
2252 #ifdef IMGUI_STB_SPRINTF_FILENAME
2253 #include IMGUI_STB_SPRINTF_FILENAME
2254 #else
2255 #include "stb_sprintf.h"
2256 #endif
2257 #endif // #ifdef IMGUI_USE_STB_SPRINTF
2258
2259 #if defined(_MSC_VER) && !defined(vsnprintf)
2260 #define vsnprintf _vsnprintf
2261 #endif
2262
2263 int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2264 {
2265 va_list args;
2266 va_start(args, fmt);
2267 #ifdef IMGUI_USE_STB_SPRINTF
2268 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2269 #else
2270 int w = vsnprintf(buf, buf_size, fmt, args);
2271 #endif
2272 va_end(args);
2273 if (buf == NULL)
2274 return w;
2275 if (w == -1 || w >= (int)buf_size)
2276 w = (int)buf_size - 1;
2277 buf[w] = 0;
2278 return w;
2279 }
2280
2281 int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2282 {
2283 #ifdef IMGUI_USE_STB_SPRINTF
2284 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2285 #else
2286 int w = vsnprintf(buf, buf_size, fmt, args);
2287 #endif
2288 if (buf == NULL)
2289 return w;
2290 if (w == -1 || w >= (int)buf_size)
2291 w = (int)buf_size - 1;
2292 buf[w] = 0;
2293 return w;
2294 }
2295 #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2296
2297 void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2298 {
2299 va_list args;
2300 va_start(args, fmt);
2301 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2302 va_end(args);
2303 }
2304
2305 // FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2306 // by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2307 // ImGuiTempBufferToken token;
2308 // ImFormatStringToTempBuffer(token, ...);
2309 void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2310 {
2311 ImGuiContext& g = *GImGui;
2312 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2313 {
2314 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2315 if (buf == NULL)
2316 buf = "(null)";
2317 *out_buf = buf;
2318 if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); }
2319 }
2320 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2321 {
2322 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2323 const char* buf = va_arg(args, const char*);
2324 if (buf == NULL)
2325 {
2326 buf = "(null)";
2327 buf_len = ImMin(buf_len, 6);
2328 }
2329 *out_buf = buf;
2330 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2331 }
2332 else
2333 {
2334 int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2335 *out_buf = g.TempBuffer.Data;
2336 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2337 }
2338 }
2339
2340 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2341 // CRC32 needs a 1KB lookup table (not cache friendly)
2342 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2343 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2344 static const ImU32 GCrc32LookupTable[256] =
2345 {
2346 #ifdef IMGUI_USE_LEGACY_CRC32_ADLER
2347 // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
2348 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2349 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2350 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2351 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2352 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2353 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2354 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2355 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2356 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2357 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2358 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2359 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2360 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2361 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2362 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2363 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2364 #else
2365 // CRC32c table compatible with SSE 4.2 instructions
2366 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
2367 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
2368 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
2369 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
2370 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
2371 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
2372 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
2373 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
2374 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
2375 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
2376 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
2377 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
2378 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
2379 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
2380 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
2381 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
2382 #endif
2383 };
2384 #endif
2385
2386 // Known size hash
2387 // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2388 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2389 ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2390 {
2391 ImU32 crc = ~seed;
2392 const unsigned char* data = (const unsigned char*)data_p;
2393 const unsigned char *data_end = (const unsigned char*)data_p + data_size;
2394 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2395 const ImU32* crc32_lut = GCrc32LookupTable;
2396 while (data < data_end)
2397 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2398 return ~crc;
2399 #else
2400 while (data + 4 <= data_end)
2401 {
2402 crc = _mm_crc32_u32(crc, *(ImU32*)data);
2403 data += 4;
2404 }
2405 while (data < data_end)
2406 crc = _mm_crc32_u8(crc, *data++);
2407 return ~crc;
2408 #endif
2409 }
2410
2411 // Zero-terminated string hash, with support for ### to reset back to seed value
2412 // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2413 // Because this syntax is rarely used we are optimizing for the common case.
2414 // - If we reach ### in the string we discard the hash so far and reset to the seed.
2415 // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2416 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2417 ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2418 {
2419 seed = ~seed;
2420 ImU32 crc = seed;
2421 const unsigned char* data = (const unsigned char*)data_p;
2422 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2423 const ImU32* crc32_lut = GCrc32LookupTable;
2424 #endif
2425 if (data_size != 0)
2426 {
2427 while (data_size-- != 0)
2428 {
2429 unsigned char c = *data++;
2430 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2431 crc = seed;
2432 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2433 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2434 #else
2435 crc = _mm_crc32_u8(crc, c);
2436 #endif
2437 }
2438 }
2439 else
2440 {
2441 while (unsigned char c = *data++)
2442 {
2443 if (c == '#' && data[0] == '#' && data[1] == '#')
2444 crc = seed;
2445 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2446 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2447 #else
2448 crc = _mm_crc32_u8(crc, c);
2449 #endif
2450 }
2451 }
2452 return ~crc;
2453 }
2454
2455 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
2456 // FIXME-OPT: This is not designed to be optimal. Use with care.
2457 const char* ImHashSkipUncontributingPrefix(const char* label)
2458 {
2459 const char* result = label;
2460 while (unsigned char c = *label++)
2461 if (c == '#' && label[0] == '#' && label[1] == '#')
2462 result = label - 1;
2463 return result;
2464 }
2465
2466 //-----------------------------------------------------------------------------
2467 // [SECTION] MISC HELPERS/UTILITIES (File functions)
2468 //-----------------------------------------------------------------------------
2469
2470 // Default file functions
2471 #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2472
2473 ImFileHandle ImFileOpen(const char* filename, const char* mode)
2474 {
2475 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__)))
2476 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2477 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2478 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2479 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2480
2481 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2482 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2483 wchar_t local_temp_stack[FILENAME_MAX];
2484 ImVector<wchar_t> local_temp_heap;
2485 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2486 local_temp_heap.resize(filename_wsize + mode_wsize);
2487 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2488 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2489 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2490 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2491 return ::_wfopen(filename_wbuf, mode_wbuf);
2492 #else
2493 return fopen(filename, mode);
2494 #endif
2495 }
2496
2497 // 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.
2498 bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
2499 ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2500 ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
2501 ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
2502 #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2503
2504 // Helper: Load file content into memory
2505 // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2506 // This can't really be used with "rt" because fseek size won't match read size.
2507 void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2508 {
2509 IM_ASSERT(filename && mode);
2510 if (out_file_size)
2511 *out_file_size = 0;
2512
2513 ImFileHandle f;
2514 if ((f = ImFileOpen(filename, mode)) == NULL)
2515 return NULL;
2516
2517 size_t file_size = (size_t)ImFileGetSize(f);
2518 if (file_size == (size_t)-1)
2519 {
2520 ImFileClose(f);
2521 return NULL;
2522 }
2523
2524 void* file_data = IM_ALLOC(file_size + padding_bytes);
2525 if (file_data == NULL)
2526 {
2527 ImFileClose(f);
2528 return NULL;
2529 }
2530 if (ImFileRead(file_data, 1, file_size, f) != file_size)
2531 {
2532 ImFileClose(f);
2533 IM_FREE(file_data);
2534 return NULL;
2535 }
2536 if (padding_bytes > 0)
2537 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2538
2539 ImFileClose(f);
2540 if (out_file_size)
2541 *out_file_size = file_size;
2542
2543 return file_data;
2544 }
2545
2546 //-----------------------------------------------------------------------------
2547 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2548 //-----------------------------------------------------------------------------
2549
2550 IM_MSVC_RUNTIME_CHECKS_OFF
2551
2552 // Convert UTF-8 to 32-bit character, process single character input.
2553 // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2554 // We handle UTF-8 decoding error by skipping forward.
2555 int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2556 {
2557 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 };
2558 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2559 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2560 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2561 static const int shifte[] = { 0, 6, 4, 2, 0 };
2562 int len = lengths[*(const unsigned char*)in_text >> 3];
2563 int wanted = len + (len ? 0 : 1);
2564
2565 if (in_text_end == NULL)
2566 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2567
2568 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2569 // so it is fast even with excessive branching.
2570 unsigned char s[4];
2571 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2572 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2573 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2574 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2575
2576 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2577 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2578 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2579 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2580 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2581 *out_char >>= shiftc[len];
2582
2583 // Accumulate the various error conditions.
2584 int e = 0;
2585 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2586 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2587 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve)
2588 e |= (s[1] & 0xc0) >> 2;
2589 e |= (s[2] & 0xc0) >> 4;
2590 e |= (s[3] ) >> 6;
2591 e ^= 0x2a; // top two bits of each tail byte correct?
2592 e >>= shifte[len];
2593
2594 if (e)
2595 {
2596 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2597 // One byte is consumed in case of invalid first byte of in_text.
2598 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2599 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2600 wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2601 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2602 }
2603
2604 return wanted;
2605 }
2606
2607 int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2608 {
2609 ImWchar* buf_out = buf;
2610 ImWchar* buf_end = buf + buf_size;
2611 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2612 {
2613 unsigned int c;
2614 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2615 *buf_out++ = (ImWchar)c;
2616 }
2617 *buf_out = 0;
2618 if (in_text_remaining)
2619 *in_text_remaining = in_text;
2620 return (int)(buf_out - buf);
2621 }
2622
2623 int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2624 {
2625 int char_count = 0;
2626 while ((!in_text_end || in_text < in_text_end) && *in_text)
2627 {
2628 unsigned int c;
2629 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2630 char_count++;
2631 }
2632 return char_count;
2633 }
2634
2635 // Based on stb_to_utf8() from github.com/nothings/stb/
2636 static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2637 {
2638 if (c < 0x80)
2639 {
2640 buf[0] = (char)c;
2641 return 1;
2642 }
2643 if (c < 0x800)
2644 {
2645 if (buf_size < 2) return 0;
2646 buf[0] = (char)(0xc0 + (c >> 6));
2647 buf[1] = (char)(0x80 + (c & 0x3f));
2648 return 2;
2649 }
2650 if (c < 0x10000)
2651 {
2652 if (buf_size < 3) return 0;
2653 buf[0] = (char)(0xe0 + (c >> 12));
2654 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2655 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2656 return 3;
2657 }
2658 if (c <= 0x10FFFF)
2659 {
2660 if (buf_size < 4) return 0;
2661 buf[0] = (char)(0xf0 + (c >> 18));
2662 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2663 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2664 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2665 return 4;
2666 }
2667 // Invalid code point, the max unicode is 0x10FFFF
2668 return 0;
2669 }
2670
2671 int ImTextCharToUtf8(char out_buf[5], unsigned int c)
2672 {
2673 int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2674 out_buf[count] = 0;
2675 return count;
2676 }
2677
2678 // Not optimal but we very rarely use this function.
2679 int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2680 {
2681 unsigned int unused = 0;
2682 return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2683 }
2684
2685 static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2686 {
2687 if (c < 0x80) return 1;
2688 if (c < 0x800) return 2;
2689 if (c < 0x10000) return 3;
2690 if (c <= 0x10FFFF) return 4;
2691 return 3;
2692 }
2693
2694 int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2695 {
2696 char* buf_p = out_buf;
2697 const char* buf_end = out_buf + out_buf_size;
2698 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2699 {
2700 unsigned int c = (unsigned int)(*in_text++);
2701 if (c < 0x80)
2702 *buf_p++ = (char)c;
2703 else
2704 buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2705 }
2706 *buf_p = 0;
2707 return (int)(buf_p - out_buf);
2708 }
2709
2710 int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2711 {
2712 int bytes_count = 0;
2713 while ((!in_text_end || in_text < in_text_end) && *in_text)
2714 {
2715 unsigned int c = (unsigned int)(*in_text++);
2716 if (c < 0x80)
2717 bytes_count++;
2718 else
2719 bytes_count += ImTextCountUtf8BytesFromChar(c);
2720 }
2721 return bytes_count;
2722 }
2723
2724 const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2725 {
2726 while (in_text_curr > in_text_start)
2727 {
2728 in_text_curr--;
2729 if ((*in_text_curr & 0xC0) != 0x80)
2730 return in_text_curr;
2731 }
2732 return in_text_start;
2733 }
2734
2735 int ImTextCountLines(const char* in_text, const char* in_text_end)
2736 {
2737 if (in_text_end == NULL)
2738 in_text_end = in_text + ImStrlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2739 int count = 0;
2740 while (in_text < in_text_end)
2741 {
2742 const char* line_end = (const char*)ImMemchr(in_text, '\n', in_text_end - in_text);
2743 in_text = line_end ? line_end + 1 : in_text_end;
2744 count++;
2745 }
2746 return count;
2747 }
2748
2749 IM_MSVC_RUNTIME_CHECKS_RESTORE
2750
2751 //-----------------------------------------------------------------------------
2752 // [SECTION] MISC HELPERS/UTILITIES (Color functions)
2753 // Note: The Convert functions are early design which are not consistent with other API.
2754 //-----------------------------------------------------------------------------
2755
2756 IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2757 {
2758 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2759 int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2760 int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2761 int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2762 return IM_COL32(r, g, b, 0xFF);
2763 }
2764
2765 ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2766 {
2767 float s = 1.0f / 255.0f;
2768 return ImVec4(
2769 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2770 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2771 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2772 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2773 }
2774
2775 ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2776 {
2777 ImU32 out;
2778 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2779 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2780 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2781 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2782 return out;
2783 }
2784
2785 // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2786 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2787 void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2788 {
2789 float K = 0.f;
2790 if (g < b)
2791 {
2792 ImSwap(g, b);
2793 K = -1.f;
2794 }
2795 if (r < g)
2796 {
2797 ImSwap(r, g);
2798 K = -2.f / 6.f - K;
2799 }
2800
2801 const float chroma = r - (g < b ? g : b);
2802 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2803 out_s = chroma / (r + 1e-20f);
2804 out_v = r;
2805 }
2806
2807 // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2808 // also http://en.wikipedia.org/wiki/HSL_and_HSV
2809 void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2810 {
2811 if (s == 0.0f)
2812 {
2813 // gray
2814 out_r = out_g = out_b = v;
2815 return;
2816 }
2817
2818 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2819 int i = (int)h;
2820 float f = h - (float)i;
2821 float p = v * (1.0f - s);
2822 float q = v * (1.0f - s * f);
2823 float t = v * (1.0f - s * (1.0f - f));
2824
2825 switch (i)
2826 {
2827 case 0: out_r = v; out_g = t; out_b = p; break;
2828 case 1: out_r = q; out_g = v; out_b = p; break;
2829 case 2: out_r = p; out_g = v; out_b = t; break;
2830 case 3: out_r = p; out_g = q; out_b = v; break;
2831 case 4: out_r = t; out_g = p; out_b = v; break;
2832 case 5: default: out_r = v; out_g = p; out_b = q; break;
2833 }
2834 }
2835
2836 //-----------------------------------------------------------------------------
2837 // [SECTION] ImGuiStorage
2838 // Helper: Key->value storage
2839 //-----------------------------------------------------------------------------
2840
2841 // std::lower_bound but without the bullshit
2842 ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2843 {
2844 ImGuiStoragePair* in_p = in_begin;
2845 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2846 {
2847 size_t count2 = count >> 1;
2848 ImGuiStoragePair* mid = in_p + count2;
2849 if (mid->key < key)
2850 {
2851 in_p = ++mid;
2852 count -= count2 + 1;
2853 }
2854 else
2855 {
2856 count = count2;
2857 }
2858 }
2859 return in_p;
2860 }
2861
2862 IM_MSVC_RUNTIME_CHECKS_OFF
2863 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2864 {
2865 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2866 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2867 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2868 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2869 }
2870
2871 // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2872 void ImGuiStorage::BuildSortByKey()
2873 {
2874 ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2875 }
2876
2877 int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2878 {
2879 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2880 if (it == Data.Data + Data.Size || it->key != key)
2881 return default_val;
2882 return it->val_i;
2883 }
2884
2885 bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2886 {
2887 return GetInt(key, default_val ? 1 : 0) != 0;
2888 }
2889
2890 float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2891 {
2892 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2893 if (it == Data.Data + Data.Size || it->key != key)
2894 return default_val;
2895 return it->val_f;
2896 }
2897
2898 void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2899 {
2900 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2901 if (it == Data.Data + Data.Size || it->key != key)
2902 return NULL;
2903 return it->val_p;
2904 }
2905
2906 // 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.
2907 int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2908 {
2909 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2910 if (it == Data.Data + Data.Size || it->key != key)
2911 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2912 return &it->val_i;
2913 }
2914
2915 bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2916 {
2917 return (bool*)GetIntRef(key, default_val ? 1 : 0);
2918 }
2919
2920 float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2921 {
2922 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2923 if (it == Data.Data + Data.Size || it->key != key)
2924 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2925 return &it->val_f;
2926 }
2927
2928 void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2929 {
2930 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2931 if (it == Data.Data + Data.Size || it->key != key)
2932 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2933 return &it->val_p;
2934 }
2935
2936 // 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)
2937 void ImGuiStorage::SetInt(ImGuiID key, int val)
2938 {
2939 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2940 if (it == Data.Data + Data.Size || it->key != key)
2941 Data.insert(it, ImGuiStoragePair(key, val));
2942 else
2943 it->val_i = val;
2944 }
2945
2946 void ImGuiStorage::SetBool(ImGuiID key, bool val)
2947 {
2948 SetInt(key, val ? 1 : 0);
2949 }
2950
2951 void ImGuiStorage::SetFloat(ImGuiID key, float val)
2952 {
2953 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2954 if (it == Data.Data + Data.Size || it->key != key)
2955 Data.insert(it, ImGuiStoragePair(key, val));
2956 else
2957 it->val_f = val;
2958 }
2959
2960 void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2961 {
2962 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2963 if (it == Data.Data + Data.Size || it->key != key)
2964 Data.insert(it, ImGuiStoragePair(key, val));
2965 else
2966 it->val_p = val;
2967 }
2968
2969 void ImGuiStorage::SetAllInt(int v)
2970 {
2971 for (int i = 0; i < Data.Size; i++)
2972 Data[i].val_i = v;
2973 }
2974 IM_MSVC_RUNTIME_CHECKS_RESTORE
2975
2976 //-----------------------------------------------------------------------------
2977 // [SECTION] ImGuiTextFilter
2978 //-----------------------------------------------------------------------------
2979
2980 // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2981 ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2982 {
2983 InputBuf[0] = 0;
2984 CountGrep = 0;
2985 if (default_filter)
2986 {
2987 ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2988 Build();
2989 }
2990 }
2991
2992 bool ImGuiTextFilter::Draw(const char* label, float width)
2993 {
2994 if (width != 0.0f)
2995 ImGui::SetNextItemWidth(width);
2996 bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2997 if (value_changed)
2998 Build();
2999 return value_changed;
3000 }
3001
3002 void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
3003 {
3004 out->resize(0);
3005 const char* wb = b;
3006 const char* we = wb;
3007 while (we < e)
3008 {
3009 if (*we == separator)
3010 {
3011 out->push_back(ImGuiTextRange(wb, we));
3012 wb = we + 1;
3013 }
3014 we++;
3015 }
3016 if (wb != we)
3017 out->push_back(ImGuiTextRange(wb, we));
3018 }
3019
3020 void ImGuiTextFilter::Build()
3021 {
3022 Filters.resize(0);
3023 ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf));
3024 input_range.split(',', &Filters);
3025
3026 CountGrep = 0;
3027 for (ImGuiTextRange& f : Filters)
3028 {
3029 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
3030 f.b++;
3031 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
3032 f.e--;
3033 if (f.empty())
3034 continue;
3035 if (f.b[0] != '-')
3036 CountGrep += 1;
3037 }
3038 }
3039
3040 bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
3041 {
3042 if (Filters.Size == 0)
3043 return true;
3044
3045 if (text == NULL)
3046 text = text_end = "";
3047
3048 for (const ImGuiTextRange& f : Filters)
3049 {
3050 if (f.b == f.e)
3051 continue;
3052 if (f.b[0] == '-')
3053 {
3054 // Subtract
3055 if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
3056 return false;
3057 }
3058 else
3059 {
3060 // Grep
3061 if (ImStristr(text, text_end, f.b, f.e) != NULL)
3062 return true;
3063 }
3064 }
3065
3066 // Implicit * grep
3067 if (CountGrep == 0)
3068 return true;
3069
3070 return false;
3071 }
3072
3073 //-----------------------------------------------------------------------------
3074 // [SECTION] ImGuiTextBuffer, ImGuiTextIndex
3075 //-----------------------------------------------------------------------------
3076
3077 // On some platform vsnprintf() takes va_list by reference and modifies it.
3078 // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
3079 #ifndef va_copy
3080 #if defined(__GNUC__) || defined(__clang__)
3081 #define va_copy(dest, src) __builtin_va_copy(dest, src)
3082 #else
3083 #define va_copy(dest, src) (dest = src)
3084 #endif
3085 #endif
3086
3087 char ImGuiTextBuffer::EmptyString[1] = { 0 };
3088
3089 void ImGuiTextBuffer::append(const char* str, const char* str_end)
3090 {
3091 int len = str_end ? (int)(str_end - str) : (int)ImStrlen(str);
3092
3093 // Add zero-terminator the first time
3094 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3095 const int needed_sz = write_off + len;
3096 if (write_off + len >= Buf.Capacity)
3097 {
3098 int new_capacity = Buf.Capacity * 2;
3099 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
3100 }
3101
3102 Buf.resize(needed_sz);
3103 memcpy(&Buf[write_off - 1], str, (size_t)len);
3104 Buf[write_off - 1 + len] = 0;
3105 }
3106
3107 void ImGuiTextBuffer::appendf(const char* fmt, ...)
3108 {
3109 va_list args;
3110 va_start(args, fmt);
3111 appendfv(fmt, args);
3112 va_end(args);
3113 }
3114
3115 // Helper: Text buffer for logging/accumulating text
3116 void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
3117 {
3118 va_list args_copy;
3119 va_copy(args_copy, args);
3120
3121 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
3122 if (len <= 0)
3123 {
3124 va_end(args_copy);
3125 return;
3126 }
3127
3128 // Add zero-terminator the first time
3129 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3130 const int needed_sz = write_off + len;
3131 if (write_off + len >= Buf.Capacity)
3132 {
3133 int new_capacity = Buf.Capacity * 2;
3134 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
3135 }
3136
3137 Buf.resize(needed_sz);
3138 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
3139 va_end(args_copy);
3140 }
3141
3142 IM_MSVC_RUNTIME_CHECKS_OFF
3143 void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
3144 {
3145 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
3146 if (old_size == new_size)
3147 return;
3148 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
3149 Offsets.push_back(EndOffset);
3150 const char* base_end = base + new_size;
3151 for (const char* p = base + old_size; (p = (const char*)ImMemchr(p, '\n', base_end - p)) != 0; )
3152 if (++p < base_end) // Don't push a trailing offset on last \n
3153 Offsets.push_back((int)(intptr_t)(p - base));
3154 EndOffset = ImMax(EndOffset, new_size);
3155 }
3156 IM_MSVC_RUNTIME_CHECKS_RESTORE
3157
3158 //-----------------------------------------------------------------------------
3159 // [SECTION] ImGuiListClipper
3160 //-----------------------------------------------------------------------------
3161
3162 // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
3163 // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
3164 static bool GetSkipItemForListClipping()
3165 {
3166 ImGuiContext& g = *GImGui;
3167 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
3168 }
3169
3170 static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
3171 {
3172 if (ranges.Size - offset <= 1)
3173 return;
3174
3175 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
3176 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
3177 for (int i = offset; i < sort_end + offset; ++i)
3178 if (ranges[i].Min > ranges[i + 1].Min)
3179 ImSwap(ranges[i], ranges[i + 1]);
3180
3181 // Now fuse ranges together as much as possible.
3182 for (int i = 1 + offset; i < ranges.Size; i++)
3183 {
3184 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
3185 if (ranges[i - 1].Max < ranges[i].Min)
3186 continue;
3187 ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
3188 ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
3189 ranges.erase(ranges.Data + i);
3190 i--;
3191 }
3192 }
3193
3194 static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clipper, float pos_y, float line_height)
3195 {
3196 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
3197 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
3198 // 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?
3199 ImGuiContext& g = *GImGui;
3200 ImGuiWindow* window = g.CurrentWindow;
3201 float off_y = pos_y - window->DC.CursorPos.y;
3202 window->DC.CursorPos.y = pos_y;
3203 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
3204 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.
3205 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.
3206 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
3207 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
3208 if (ImGuiTable* table = g.CurrentTable)
3209 {
3210 if (table->IsInsideRow)
3211 ImGui::TableEndRow(table);
3212 const int row_increase = (int)((off_y / line_height) + 0.5f);
3213 if (row_increase > 0 && (clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886.
3214 {
3215 table->CurrentRow += row_increase;
3216 table->RowBgColorCounter += row_increase;
3217 }
3218 table->RowPosY2 = window->DC.CursorPos.y;
3219 }
3220 }
3221
3222 ImGuiListClipper::ImGuiListClipper()
3223 {
3224 memset(this, 0, sizeof(*this));
3225 }
3226
3227 ImGuiListClipper::~ImGuiListClipper()
3228 {
3229 End();
3230 }
3231
3232 void ImGuiListClipper::Begin(int items_count, float items_height)
3233 {
3234 if (Ctx == NULL)
3235 Ctx = ImGui::GetCurrentContext();
3236
3237 ImGuiContext& g = *Ctx;
3238 ImGuiWindow* window = g.CurrentWindow;
3239 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3240
3241 if (ImGuiTable* table = g.CurrentTable)
3242 if (table->IsInsideRow)
3243 ImGui::TableEndRow(table);
3244
3245 StartPosY = window->DC.CursorPos.y;
3246 ItemsHeight = items_height;
3247 ItemsCount = items_count;
3248 DisplayStart = -1;
3249 DisplayEnd = 0;
3250
3251 // Acquire temporary buffer
3252 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3253 g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3254 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3255 data->Reset(this);
3256 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3257 TempData = data;
3258 StartSeekOffsetY = data->LossynessOffset;
3259 }
3260
3261 void ImGuiListClipper::End()
3262 {
3263 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3264 {
3265 // 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.
3266 ImGuiContext& g = *Ctx;
3267 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3268 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3269 SeekCursorForItem(ItemsCount);
3270
3271 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3272 IM_ASSERT(data->ListClipper == this);
3273 data->StepNo = data->Ranges.Size;
3274 if (--g.ClipperTempDataStacked > 0)
3275 {
3276 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3277 data->ListClipper->TempData = data;
3278 }
3279 TempData = NULL;
3280 }
3281 ItemsCount = -1;
3282 }
3283
3284 void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3285 {
3286 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3287 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3288 IM_ASSERT(item_begin <= item_end);
3289 if (item_begin < item_end)
3290 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3291 }
3292
3293 // This is already called while stepping.
3294 // 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.
3295 void ImGuiListClipper::SeekCursorForItem(int item_n)
3296 {
3297 // - Perform the add and multiply with double to allow seeking through larger ranges.
3298 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3299 // - 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.
3300 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3301 ImGuiListClipper_SeekCursorAndSetupPrevLine(this, pos_y, ItemsHeight);
3302 }
3303
3304 static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3305 {
3306 ImGuiContext& g = *clipper->Ctx;
3307 ImGuiWindow* window = g.CurrentWindow;
3308 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3309 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3310
3311 ImGuiTable* table = g.CurrentTable;
3312 if (table && table->IsInsideRow)
3313 ImGui::TableEndRow(table);
3314
3315 // No items
3316 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3317 return false;
3318
3319 // While we are in frozen row state, keep displaying items one by one, unclipped
3320 // FIXME: Could be stored as a table-agnostic state.
3321 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3322 {
3323 clipper->DisplayStart = data->ItemsFrozen;
3324 clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3325 if (clipper->DisplayStart < clipper->DisplayEnd)
3326 data->ItemsFrozen++;
3327 return true;
3328 }
3329
3330 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3331 bool calc_clipping = false;
3332 if (data->StepNo == 0)
3333 {
3334 clipper->StartPosY = window->DC.CursorPos.y;
3335 if (clipper->ItemsHeight <= 0.0f)
3336 {
3337 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3338 data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3339 clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3340 clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3341 data->StepNo = 1;
3342 return true;
3343 }
3344 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3345 }
3346
3347 // Step 1: Let the clipper infer height from first range
3348 if (clipper->ItemsHeight <= 0.0f)
3349 {
3350 IM_ASSERT(data->StepNo == 1);
3351 if (table)
3352 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3353
3354 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3355 if (affected_by_floating_point_precision)
3356 {
3357 // Mitigation/hack for very large range: assume last time height constitute line height.
3358 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3359 window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight);
3360 }
3361 else
3362 {
3363 clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3364 }
3365 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3366 return false;
3367 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3368 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3369 }
3370
3371 // Step 0 or 1: Calculate the actual ranges of visible elements.
3372 const int already_submitted = clipper->DisplayEnd;
3373 if (calc_clipping)
3374 {
3375 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3376 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3377
3378 if (g.LogEnabled)
3379 {
3380 // If logging is active, do not perform any clipping
3381 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3382 }
3383 else
3384 {
3385 // Add range selected to be included for navigation
3386 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3387 if (is_nav_request)
3388 {
3389 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, 0, 0));
3390 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3391 }
3392 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3393 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3394
3395 // Add focused/active item
3396 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3397 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3398 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3399
3400 float min_y = window->ClipRect.Min.y;
3401 float max_y = window->ClipRect.Max.y;
3402
3403 // Add box selection range
3404 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3405 if (bs->IsActive && bs->Window == window)
3406 {
3407 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3408 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3409 // As a workaround we currently half ItemSpacing worth on each side.
3410 min_y -= g.Style.ItemSpacing.y;
3411 max_y += g.Style.ItemSpacing.y;
3412
3413 // Box-select on 2D area requires different clipping.
3414 if (bs->UnclipMode)
3415 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
3416 }
3417
3418 // Add main visible range
3419 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3420 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3421 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
3422 }
3423
3424 // Convert position ranges to item index ranges
3425 // - 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.
3426 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3427 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3428 for (ImGuiListClipperRange& range : data->Ranges)
3429 if (range.PosToIndexConvert)
3430 {
3431 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3432 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3433 range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3434 range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3435 range.PosToIndexConvert = false;
3436 }
3437 ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3438 }
3439
3440 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3441 while (data->StepNo < data->Ranges.Size)
3442 {
3443 clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3444 clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3445 data->StepNo++;
3446 if (clipper->DisplayStart >= clipper->DisplayEnd)
3447 continue;
3448 if (clipper->DisplayStart > already_submitted)
3449 clipper->SeekCursorForItem(clipper->DisplayStart);
3450 return true;
3451 }
3452
3453 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3454 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3455 if (clipper->ItemsCount < INT_MAX)
3456 clipper->SeekCursorForItem(clipper->ItemsCount);
3457
3458 return false;
3459 }
3460
3461 bool ImGuiListClipper::Step()
3462 {
3463 ImGuiContext& g = *Ctx;
3464 bool need_items_height = (ItemsHeight <= 0.0f);
3465 bool ret = ImGuiListClipper_StepInternal(this);
3466 if (ret && (DisplayStart >= DisplayEnd))
3467 ret = false;
3468 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3469 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3470 if (need_items_height && ItemsHeight > 0.0f)
3471 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3472 if (ret)
3473 {
3474 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3475 }
3476 else
3477 {
3478 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3479 End();
3480 }
3481 return ret;
3482 }
3483
3484 // Generic helper, equivalent to old ImGui::CalcListClipping() but statelesss
3485 void ImGui::CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end)
3486 {
3487 *out_visible_start = ImMax((int)((clip_rect.Min.y - pos.y) / items_height), 0);
3488 *out_visible_end = ImMax((int)ImCeil((clip_rect.Max.y - pos.y) / items_height), *out_visible_start);
3489 }
3490
3491 //-----------------------------------------------------------------------------
3492 // [SECTION] STYLING
3493 //-----------------------------------------------------------------------------
3494
3495 ImGuiStyle& ImGui::GetStyle()
3496 {
3497 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3498 return GImGui->Style;
3499 }
3500
3501 ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3502 {
3503 ImGuiStyle& style = GImGui->Style;
3504 ImVec4 c = style.Colors[idx];
3505 c.w *= style.Alpha * alpha_mul;
3506 return ColorConvertFloat4ToU32(c);
3507 }
3508
3509 ImU32 ImGui::GetColorU32(const ImVec4& col)
3510 {
3511 ImGuiStyle& style = GImGui->Style;
3512 ImVec4 c = col;
3513 c.w *= style.Alpha;
3514 return ColorConvertFloat4ToU32(c);
3515 }
3516
3517 const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3518 {
3519 ImGuiStyle& style = GImGui->Style;
3520 return style.Colors[idx];
3521 }
3522
3523 ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3524 {
3525 ImGuiStyle& style = GImGui->Style;
3526 alpha_mul *= style.Alpha;
3527 if (alpha_mul >= 1.0f)
3528 return col;
3529 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3530 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3531 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3532 }
3533
3534 // 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
3535 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3536 {
3537 ImGuiContext& g = *GImGui;
3538 ImGuiColorMod backup;
3539 backup.Col = idx;
3540 backup.BackupValue = g.Style.Colors[idx];
3541 g.ColorStack.push_back(backup);
3542 if (g.DebugFlashStyleColorIdx != idx)
3543 g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3544 }
3545
3546 void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3547 {
3548 ImGuiContext& g = *GImGui;
3549 ImGuiColorMod backup;
3550 backup.Col = idx;
3551 backup.BackupValue = g.Style.Colors[idx];
3552 g.ColorStack.push_back(backup);
3553 if (g.DebugFlashStyleColorIdx != idx)
3554 g.Style.Colors[idx] = col;
3555 }
3556
3557 void ImGui::PopStyleColor(int count)
3558 {
3559 ImGuiContext& g = *GImGui;
3560 if (g.ColorStack.Size < count)
3561 {
3562 IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
3563 count = g.ColorStack.Size;
3564 }
3565 while (count > 0)
3566 {
3567 ImGuiColorMod& backup = g.ColorStack.back();
3568 g.Style.Colors[backup.Col] = backup.BackupValue;
3569 g.ColorStack.pop_back();
3570 count--;
3571 }
3572 }
3573
3574 static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3575 {
3576 ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3577 };
3578
3579 static const ImGuiStyleVarInfo GStyleVarsInfo[] =
3580 {
3581 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3582 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3583 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3584 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3585 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3586 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3587 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3588 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3589 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3590 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3591 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3592 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3593 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3594 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3595 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3596 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3597 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3598 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3599 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3600 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3601 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarPadding) }, // ImGuiStyleVar_ScrollbarPadding
3602 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3603 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3604 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize
3605 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3606 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3607 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase
3608 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink
3609 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3610 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3611 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3612 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3613 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize
3614 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding
3615 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3616 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3617 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3618 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3619 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3620 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3621 };
3622
3623 const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3624 {
3625 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3626 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT);
3627 return &GStyleVarsInfo[idx];
3628 }
3629
3630 void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3631 {
3632 ImGuiContext& g = *GImGui;
3633 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3634 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1)
3635 {
3636 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3637 return;
3638 }
3639 float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3640 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3641 *pvar = val;
3642 }
3643
3644 void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
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(&g.Style);
3654 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3655 pvar->x = val_x;
3656 }
3657
3658 void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
3659 {
3660 ImGuiContext& g = *GImGui;
3661 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3662 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3663 {
3664 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3665 return;
3666 }
3667 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3668 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3669 pvar->y = val_y;
3670 }
3671
3672 void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3673 {
3674 ImGuiContext& g = *GImGui;
3675 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3676 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3677 {
3678 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3679 return;
3680 }
3681 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3682 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3683 *pvar = val;
3684 }
3685
3686 void ImGui::PopStyleVar(int count)
3687 {
3688 ImGuiContext& g = *GImGui;
3689 if (g.StyleVarStack.Size < count)
3690 {
3691 IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
3692 count = g.StyleVarStack.Size;
3693 }
3694 while (count > 0)
3695 {
3696 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3697 ImGuiStyleMod& backup = g.StyleVarStack.back();
3698 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(backup.VarIdx);
3699 void* data = var_info->GetVarPtr(&g.Style);
3700 if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3701 else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3702 g.StyleVarStack.pop_back();
3703 count--;
3704 }
3705 }
3706
3707 const char* ImGui::GetStyleColorName(ImGuiCol idx)
3708 {
3709 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3710 switch (idx)
3711 {
3712 case ImGuiCol_Text: return "Text";
3713 case ImGuiCol_TextDisabled: return "TextDisabled";
3714 case ImGuiCol_WindowBg: return "WindowBg";
3715 case ImGuiCol_ChildBg: return "ChildBg";
3716 case ImGuiCol_PopupBg: return "PopupBg";
3717 case ImGuiCol_Border: return "Border";
3718 case ImGuiCol_BorderShadow: return "BorderShadow";
3719 case ImGuiCol_FrameBg: return "FrameBg";
3720 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3721 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3722 case ImGuiCol_TitleBg: return "TitleBg";
3723 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3724 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3725 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3726 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3727 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3728 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3729 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3730 case ImGuiCol_CheckMark: return "CheckMark";
3731 case ImGuiCol_SliderGrab: return "SliderGrab";
3732 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3733 case ImGuiCol_Button: return "Button";
3734 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3735 case ImGuiCol_ButtonActive: return "ButtonActive";
3736 case ImGuiCol_Header: return "Header";
3737 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3738 case ImGuiCol_HeaderActive: return "HeaderActive";
3739 case ImGuiCol_Separator: return "Separator";
3740 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3741 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3742 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3743 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3744 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3745 case ImGuiCol_InputTextCursor: return "InputTextCursor";
3746 case ImGuiCol_TabHovered: return "TabHovered";
3747 case ImGuiCol_Tab: return "Tab";
3748 case ImGuiCol_TabSelected: return "TabSelected";
3749 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3750 case ImGuiCol_TabDimmed: return "TabDimmed";
3751 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3752 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3753 case ImGuiCol_DockingPreview: return "DockingPreview";
3754 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3755 case ImGuiCol_PlotLines: return "PlotLines";
3756 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3757 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3758 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3759 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3760 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3761 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3762 case ImGuiCol_TableRowBg: return "TableRowBg";
3763 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3764 case ImGuiCol_TextLink: return "TextLink";
3765 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3766 case ImGuiCol_TreeLines: return "TreeLines";
3767 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3768 case ImGuiCol_NavCursor: return "NavCursor";
3769 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3770 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3771 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3772 }
3773 IM_ASSERT(0);
3774 return "Unknown";
3775 }
3776
3777 //-----------------------------------------------------------------------------
3778 // [SECTION] RENDER HELPERS
3779 // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3780 // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3781 // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3782 //-----------------------------------------------------------------------------
3783
3784 const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3785 {
3786 const char* text_display_end = text;
3787 if (!text_end)
3788 text_end = (const char*)-1;
3789
3790 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3791 text_display_end++;
3792 return text_display_end;
3793 }
3794
3795 // Internal ImGui functions to render text
3796 // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3797 void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3798 {
3799 ImGuiContext& g = *GImGui;
3800 ImGuiWindow* window = g.CurrentWindow;
3801
3802 // Hide anything after a '##' string
3803 const char* text_display_end;
3804 if (hide_text_after_hash)
3805 {
3806 text_display_end = FindRenderedTextEnd(text, text_end);
3807 }
3808 else
3809 {
3810 if (!text_end)
3811 text_end = text + ImStrlen(text); // FIXME-OPT
3812 text_display_end = text_end;
3813 }
3814
3815 if (text != text_display_end)
3816 {
3817 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3818 if (g.LogEnabled)
3819 LogRenderedText(&pos, text, text_display_end);
3820 }
3821 }
3822
3823 void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3824 {
3825 ImGuiContext& g = *GImGui;
3826 ImGuiWindow* window = g.CurrentWindow;
3827
3828 if (!text_end)
3829 text_end = text + ImStrlen(text); // FIXME-OPT
3830
3831 if (text != text_end)
3832 {
3833 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3834 if (g.LogEnabled)
3835 LogRenderedText(&pos, text, text_end);
3836 }
3837 }
3838
3839 // Default clip_rect uses (pos_min,pos_max)
3840 // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3841 // FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList.
3842 // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3843 // better advantage of the render function taking size into account for coarse clipping.
3844 void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3845 {
3846 // Perform CPU side clipping for single clipped element to avoid using scissor state
3847 ImVec2 pos = pos_min;
3848 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3849
3850 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3851 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3852 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3853 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3854 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3855
3856 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3857 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3858 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3859
3860 // Render
3861 if (need_clipping)
3862 {
3863 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3864 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3865 }
3866 else
3867 {
3868 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3869 }
3870 }
3871
3872 void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3873 {
3874 // Hide anything after a '##' string
3875 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3876 const int text_len = (int)(text_display_end - text);
3877 if (text_len == 0)
3878 return;
3879
3880 ImGuiContext& g = *GImGui;
3881 ImGuiWindow* window = g.CurrentWindow;
3882 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3883 if (g.LogEnabled)
3884 LogRenderedText(&pos_min, text, text_display_end);
3885 }
3886
3887 // Another overly complex function until we reorganize everything into a nice all-in-one helper.
3888 // 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.
3889 // 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.
3890 // (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.
3891 void 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)
3892 {
3893 ImGuiContext& g = *GImGui;
3894 if (text_end_full == NULL)
3895 text_end_full = FindRenderedTextEnd(text);
3896 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3897
3898 //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));
3899 //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));
3900
3901 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3902 if (text_size.x > pos_max.x - pos_min.x)
3903 {
3904 // Hello wo...
3905 // | | |
3906 // min max ellipsis_max
3907 // <-> this is generally some padding value
3908
3909 ImFont* font = draw_list->_Data->Font;
3910 const float font_size = draw_list->_Data->FontSize;
3911 const float font_scale = draw_list->_Data->FontScale;
3912 const char* text_end_ellipsis = NULL;
3913 ImFontBaked* baked = font->GetFontBaked(font_size);
3914 const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale;
3915
3916 // We can now claim the space between pos_max.x and ellipsis_max.x
3917 const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3918 float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3919 while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3920 {
3921 // 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)
3922 text_end_ellipsis--;
3923 text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3924 }
3925
3926 // Render text, render ellipsis
3927 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3928 ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y);
3929 ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3930 font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect);
3931 }
3932 else
3933 {
3934 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3935 }
3936
3937 if (g.LogEnabled)
3938 LogRenderedText(&pos_min, text, text_end_full);
3939 }
3940
3941 // Render a rectangle shaped with optional rounding and borders
3942 void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding)
3943 {
3944 ImGuiContext& g = *GImGui;
3945 ImGuiWindow* window = g.CurrentWindow;
3946 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3947 const float border_size = g.Style.FrameBorderSize;
3948 if (borders && border_size > 0.0f)
3949 {
3950 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3951 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3952 }
3953 }
3954
3955 void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3956 {
3957 ImGuiContext& g = *GImGui;
3958 ImGuiWindow* window = g.CurrentWindow;
3959 const float border_size = g.Style.FrameBorderSize;
3960 if (border_size > 0.0f)
3961 {
3962 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3963 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3964 }
3965 }
3966
3967 void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags)
3968 {
3969 ImGuiContext& g = *GImGui;
3970 if (id != g.NavId)
3971 return;
3972 if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
3973 return;
3974 if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
3975 return;
3976 ImGuiWindow* window = g.CurrentWindow;
3977 if (window->DC.NavHideHighlightOneFrame)
3978 return;
3979
3980 float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3981 ImRect display_rect = bb;
3982 display_rect.ClipWith(window->ClipRect);
3983 const float thickness = 2.0f;
3984 if (flags & ImGuiNavRenderCursorFlags_Compact)
3985 {
3986 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
3987 }
3988 else
3989 {
3990 const float distance = 3.0f + thickness * 0.5f;
3991 display_rect.Expand(ImVec2(distance, distance));
3992 bool fully_visible = window->ClipRect.Contains(display_rect);
3993 if (!fully_visible)
3994 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3995 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
3996 if (!fully_visible)
3997 window->DrawList->PopClipRect();
3998 }
3999 }
4000
4001 void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
4002 {
4003 ImGuiContext& g = *GImGui;
4004 if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
4005 mouse_cursor = ImGuiMouseCursor_Arrow;
4006 ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas;
4007 for (ImGuiViewportP* viewport : g.Viewports)
4008 {
4009 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
4010 ImVec2 offset, size, uv[4];
4011 if (!ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, &offset, &size, &uv[0], &uv[2]))
4012 continue;
4013 const ImVec2 pos = base_pos - offset;
4014 const float scale = base_scale * viewport->DpiScale;
4015 if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
4016 continue;
4017 ImDrawList* draw_list = GetForegroundDrawList(viewport);
4018 ImTextureRef tex_ref = font_atlas->TexRef;
4019 draw_list->PushTexture(tex_ref);
4020 draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
4021 draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
4022 draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border);
4023 draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill);
4024 if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress)
4025 {
4026 float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI);
4027 float a_max = a_min + IM_PI * 1.65f;
4028 draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max);
4029 draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale);
4030 }
4031 draw_list->PopTexture();
4032 }
4033 }
4034
4035 //-----------------------------------------------------------------------------
4036 // [SECTION] INITIALIZATION, SHUTDOWN
4037 //-----------------------------------------------------------------------------
4038
4039 // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
4040 // 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
4041 ImGuiContext* ImGui::GetCurrentContext()
4042 {
4043 return GImGui;
4044 }
4045
4046 void ImGui::SetCurrentContext(ImGuiContext* ctx)
4047 {
4048 #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
4049 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
4050 #else
4051 GImGui = ctx;
4052 #endif
4053 }
4054
4055 void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
4056 {
4057 GImAllocatorAllocFunc = alloc_func;
4058 GImAllocatorFreeFunc = free_func;
4059 GImAllocatorUserData = user_data;
4060 }
4061
4062 // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
4063 void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
4064 {
4065 *p_alloc_func = GImAllocatorAllocFunc;
4066 *p_free_func = GImAllocatorFreeFunc;
4067 *p_user_data = GImAllocatorUserData;
4068 }
4069
4070 ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
4071 {
4072 ImGuiContext* prev_ctx = GetCurrentContext();
4073 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
4074 SetCurrentContext(ctx);
4075 Initialize();
4076 if (prev_ctx != NULL)
4077 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
4078 return ctx;
4079 }
4080
4081 void ImGui::DestroyContext(ImGuiContext* ctx)
4082 {
4083 ImGuiContext* prev_ctx = GetCurrentContext();
4084 if (ctx == NULL) //-V1051
4085 ctx = prev_ctx;
4086 SetCurrentContext(ctx);
4087 Shutdown();
4088 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
4089 IM_DELETE(ctx);
4090 }
4091
4092 // IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation.
4093 static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
4094 {
4095 { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
4096 { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" },
4097 { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" },
4098 { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" },
4099 { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" },
4100 { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" },
4101 { ImGuiLocKey_WindowingPopup, "(Popup)" },
4102 { ImGuiLocKey_WindowingUntitled, "(Untitled)" },
4103 { ImGuiLocKey_OpenLink_s, "Open '%s'" },
4104 { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" },
4105 { ImGuiLocKey_DockingHideTabBar, "Hide tab bar###HideTabBar" },
4106 { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window." },
4107 { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node." },
4108 };
4109
4110 ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
4111 {
4112 IO.Ctx = this;
4113 InputTextState.Ctx = this;
4114
4115 Initialized = false;
4116 ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None;
4117
4118 Font = NULL;
4119 FontBaked = NULL;
4120 FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f;
4121 FontRasterizerDensity = 1.0f;
4122 IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
4123 if (shared_font_atlas == NULL)
4124 IO.Fonts->OwnerContext = this;
4125 Time = 0.0f;
4126 FrameCount = 0;
4127 FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1;
4128 WithinEndChildID = 0;
4129 WithinFrameScope = WithinFrameScopeWithImplicitWindow = false;
4130 GcCompactAll = false;
4131 TestEngineHookItems = false;
4132 TestEngine = NULL;
4133 memset(ContextName, 0, sizeof(ContextName));
4134
4135 InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
4136 InputEventsNextEventId = 1;
4137
4138 WindowsActiveCount = 0;
4139 WindowsBorderHoverPadding = 0.0f;
4140 CurrentWindow = NULL;
4141 HoveredWindow = NULL;
4142 HoveredWindowUnderMovingWindow = NULL;
4143 HoveredWindowBeforeClear = NULL;
4144 MovingWindow = NULL;
4145 WheelingWindow = NULL;
4146 WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
4147 WheelingWindowReleaseTimer = 0.0f;
4148
4149 DebugDrawIdConflictsId = 0;
4150 DebugHookIdInfoId = 0;
4151 HoveredId = HoveredIdPreviousFrame = 0;
4152 HoveredIdPreviousFrameItemCount = 0;
4153 HoveredIdAllowOverlap = false;
4154 HoveredIdIsDisabled = false;
4155 HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
4156 ItemUnclipByLog = false;
4157 ActiveId = 0;
4158 ActiveIdIsAlive = 0;
4159 ActiveIdTimer = 0.0f;
4160 ActiveIdIsJustActivated = false;
4161 ActiveIdAllowOverlap = false;
4162 ActiveIdNoClearOnFocusLoss = false;
4163 ActiveIdHasBeenPressedBefore = false;
4164 ActiveIdHasBeenEditedBefore = false;
4165 ActiveIdHasBeenEditedThisFrame = false;
4166 ActiveIdFromShortcut = false;
4167 ActiveIdClickOffset = ImVec2(-1, -1);
4168 ActiveIdWindow = NULL;
4169 ActiveIdSource = ImGuiInputSource_None;
4170 ActiveIdDisabledId = 0;
4171 ActiveIdMouseButton = -1;
4172 ActiveIdPreviousFrame = 0;
4173 memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData));
4174 memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation));
4175 LastActiveId = 0;
4176 LastActiveIdTimer = 0.0f;
4177
4178 LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
4179
4180 ActiveIdUsingNavDirMask = 0x00;
4181 ActiveIdUsingAllKeyboardKeys = false;
4182
4183 CurrentFocusScopeId = 0;
4184 CurrentItemFlags = ImGuiItemFlags_None;
4185 DebugShowGroupRects = false;
4186
4187 CurrentViewport = NULL;
4188 MouseViewport = MouseLastHoveredViewport = NULL;
4189 PlatformLastFocusedViewportId = 0;
4190 ViewportCreatedCount = PlatformWindowsCreatedCount = 0;
4191 ViewportFocusedStampCount = 0;
4192
4193 NavCursorVisible = false;
4194 NavHighlightItemUnderNav = false;
4195 NavMousePosDirty = false;
4196 NavIdIsAlive = false;
4197 NavId = 0;
4198 NavWindow = NULL;
4199 NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
4200 NavLayer = ImGuiNavLayer_Main;
4201 NavNextActivateId = 0;
4202 NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
4203 NavHighlightActivatedId = 0;
4204 NavHighlightActivatedTimer = 0.0f;
4205 NavInputSource = ImGuiInputSource_Keyboard;
4206 NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
4207 NavCursorHideFrames = 0;
4208
4209 NavAnyRequest = false;
4210 NavInitRequest = false;
4211 NavInitRequestFromMove = false;
4212 NavMoveSubmitted = false;
4213 NavMoveScoringItems = false;
4214 NavMoveForwardToNextFrame = false;
4215 NavMoveFlags = ImGuiNavMoveFlags_None;
4216 NavMoveScrollFlags = ImGuiScrollFlags_None;
4217 NavMoveKeyMods = ImGuiMod_None;
4218 NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
4219 NavScoringDebugCount = 0;
4220 NavTabbingDir = 0;
4221 NavTabbingCounter = 0;
4222
4223 NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
4224 NavJustMovedToKeyMods = ImGuiMod_None;
4225 NavJustMovedToIsTabbing = false;
4226 NavJustMovedToHasSelectionData = false;
4227
4228 // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
4229 // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
4230 ConfigNavWindowingWithGamepad = true;
4231 ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
4232 ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
4233 NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
4234 NavWindowingInputSource = ImGuiInputSource_None;
4235 NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
4236 NavWindowingToggleLayer = false;
4237 NavWindowingToggleKey = ImGuiKey_None;
4238
4239 DimBgRatio = 0.0f;
4240
4241 DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
4242 DragDropSourceFlags = ImGuiDragDropFlags_None;
4243 DragDropSourceFrameCount = -1;
4244 DragDropMouseButton = -1;
4245 DragDropTargetId = 0;
4246 DragDropAcceptFlags = ImGuiDragDropFlags_None;
4247 DragDropAcceptIdCurrRectSurface = 0.0f;
4248 DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
4249 DragDropAcceptFrameCount = -1;
4250 DragDropHoldJustPressedId = 0;
4251 memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
4252
4253 ClipperTempDataStacked = 0;
4254
4255 CurrentTable = NULL;
4256 TablesTempDataStacked = 0;
4257 CurrentTabBar = NULL;
4258 CurrentMultiSelect = NULL;
4259 MultiSelectTempDataStacked = 0;
4260
4261 HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
4262 HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
4263
4264 MouseCursor = ImGuiMouseCursor_Arrow;
4265 MouseStationaryTimer = 0.0f;
4266
4267 InputTextPasswordFontBackupFlags = ImFontFlags_None;
4268 TempInputId = 0;
4269 memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
4270 BeginMenuDepth = BeginComboDepth = 0;
4271 ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
4272 ColorEditCurrentID = ColorEditSavedID = 0;
4273 ColorEditSavedHue = ColorEditSavedSat = 0.0f;
4274 ColorEditSavedColor = 0;
4275 WindowResizeRelativeMode = false;
4276 ScrollbarSeekMode = 0;
4277 ScrollbarClickDeltaToGrabCenter = 0.0f;
4278 SliderGrabClickOffset = 0.0f;
4279 SliderCurrentAccum = 0.0f;
4280 SliderCurrentAccumDirty = false;
4281 DragCurrentAccumDirty = false;
4282 DragCurrentAccum = 0.0f;
4283 DragSpeedDefaultRatio = 1.0f / 100.0f;
4284 DisabledAlphaBackup = 0.0f;
4285 DisabledStackSize = 0;
4286 TooltipOverrideCount = 0;
4287 TooltipPreviousWindow = NULL;
4288
4289 PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
4290 PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
4291
4292 DockNodeWindowMenuHandler = NULL;
4293
4294 SettingsLoaded = false;
4295 SettingsDirtyTimer = 0.0f;
4296 HookIdNext = 0;
4297
4298 memset(LocalizationTable, 0, sizeof(LocalizationTable));
4299
4300 LogEnabled = false;
4301 LogFlags = ImGuiLogFlags_None;
4302 LogWindow = NULL;
4303 LogNextPrefix = LogNextSuffix = NULL;
4304 LogFile = NULL;
4305 LogLinePosY = FLT_MAX;
4306 LogLineFirstItem = false;
4307 LogDepthRef = 0;
4308 LogDepthToExpand = LogDepthToExpandDefault = 2;
4309
4310 ErrorCallback = NULL;
4311 ErrorCallbackUserData = NULL;
4312 ErrorFirst = true;
4313 ErrorCountCurrentFrame = 0;
4314 StackSizesInBeginForCurrentWindow = NULL;
4315
4316 DebugDrawIdConflictsCount = 0;
4317 DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
4318 DebugLocateId = 0;
4319 DebugLogSkippedErrors = 0;
4320 DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4321 DebugLogAutoDisableFrames = 0;
4322 DebugLocateFrames = 0;
4323 DebugBeginReturnValueCullDepth = -1;
4324 DebugItemPickerActive = false;
4325 DebugItemPickerMouseButton = ImGuiMouseButton_Left;
4326 DebugItemPickerBreakId = 0;
4327 DebugFlashStyleColorTime = 0.0f;
4328 DebugFlashStyleColorIdx = ImGuiCol_COUNT;
4329 DebugHoveredDockNode = NULL;
4330
4331 // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
4332 DebugBreakInWindow = 0;
4333 DebugBreakInTable = 0;
4334 DebugBreakInLocateId = false;
4335 DebugBreakKeyChord = ImGuiKey_Pause;
4336 DebugBreakInShortcutRouting = ImGuiKey_None;
4337
4338 memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
4339 FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
4340 FramerateSecPerFrameAccum = 0.0f;
4341 WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
4342 memset(TempKeychordName, 0, sizeof(TempKeychordName));
4343 }
4344
4345 void ImGui::Initialize()
4346 {
4347 ImGuiContext& g = *GImGui;
4348 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4349
4350 // Add .ini handle for ImGuiWindow and ImGuiTable types
4351 {
4352 ImGuiSettingsHandler ini_handler;
4353 ini_handler.TypeName = "Window";
4354 ini_handler.TypeHash = ImHashStr("Window");
4355 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4356 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4357 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4358 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4359 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4360 AddSettingsHandler(&ini_handler);
4361 }
4362 TableSettingsAddSettingsHandler();
4363
4364 // Setup default localization table
4365 LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
4366
4367 // Setup default ImGuiPlatformIO clipboard/IME handlers.
4368 g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
4369 g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl;
4370 g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl;
4371 g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl;
4372
4373 // Create default viewport
4374 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4375 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4376 viewport->Idx = 0;
4377 viewport->PlatformWindowCreated = true;
4378 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
4379 g.Viewports.push_back(viewport);
4380 g.TempBuffer.resize(1024 * 3 + 1, 0);
4381 g.ViewportCreatedCount++;
4382 g.PlatformIO.Viewports.push_back(g.Viewports[0]);
4383
4384 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
4385 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4386 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
4387 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
4388 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
4389 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
4390 g.KeysMayBeCharInput.SetBit(key);
4391
4392 #ifdef IMGUI_HAS_DOCK
4393 // Initialize Docking
4394 DockContextInitialize(&g);
4395 #endif
4396
4397 // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow.
4398 // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED.
4399 #ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
4400 DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
4401 #endif
4402
4403 // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context.
4404 // But this link allows us to facilitate/handle a few edge cases better.
4405 ImFontAtlas* atlas = g.IO.Fonts;
4406 g.DrawListSharedData.Context = &g;
4407 RegisterFontAtlas(atlas);
4408
4409 g.Initialized = true;
4410 }
4411
4412 // This function is merely here to free heap allocations.
4413 void ImGui::Shutdown()
4414 {
4415 ImGuiContext& g = *GImGui;
4416 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
4417 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
4418
4419 // 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)
4420 for (ImFontAtlas* atlas : g.FontAtlases)
4421 {
4422 UnregisterFontAtlas(atlas);
4423 if (atlas->OwnerContext == &g)
4424 {
4425 atlas->Locked = false;
4426 IM_DELETE(atlas);
4427 }
4428 }
4429 g.DrawListSharedData.TempBuffer.clear();
4430
4431 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4432 if (!g.Initialized)
4433 return;
4434
4435 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4436 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4437 SaveIniSettingsToDisk(g.IO.IniFilename);
4438
4439 // Destroy platform windows
4440 DestroyPlatformWindows();
4441
4442 // Shutdown extensions
4443 DockContextShutdown(&g);
4444
4445 CallContextHooks(&g, ImGuiContextHookType_Shutdown);
4446
4447 // Clear everything else
4448 g.Windows.clear_delete();
4449 g.WindowsFocusOrder.clear();
4450 g.WindowsTempSortBuffer.clear();
4451 g.CurrentWindow = NULL;
4452 g.CurrentWindowStack.clear();
4453 g.WindowsById.Clear();
4454 g.NavWindow = NULL;
4455 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4456 g.ActiveIdWindow = NULL;
4457 g.MovingWindow = NULL;
4458
4459 g.KeysRoutingTable.Clear();
4460
4461 g.ColorStack.clear();
4462 g.StyleVarStack.clear();
4463 g.FontStack.clear();
4464 g.OpenPopupStack.clear();
4465 g.BeginPopupStack.clear();
4466 g.TreeNodeStack.clear();
4467
4468 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
4469 g.Viewports.clear_delete();
4470
4471 g.TabBars.Clear();
4472 g.CurrentTabBarStack.clear();
4473 g.ShrinkWidthBuffer.clear();
4474
4475 g.ClipperTempData.clear_destruct();
4476
4477 g.Tables.Clear();
4478 g.TablesTempData.clear_destruct();
4479 g.DrawChannelsTempMergeBuffer.clear();
4480
4481 g.MultiSelectStorage.Clear();
4482 g.MultiSelectTempData.clear_destruct();
4483
4484 g.ClipboardHandlerData.clear();
4485 g.MenusIdSubmittedThisFrame.clear();
4486 g.InputTextState.ClearFreeMemory();
4487 g.InputTextLineIndex.clear();
4488 g.InputTextDeactivatedState.ClearFreeMemory();
4489
4490 g.SettingsWindows.clear();
4491 g.SettingsHandlers.clear();
4492
4493 if (g.LogFile)
4494 {
4495 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4496 if (g.LogFile != stdout)
4497 #endif
4498 ImFileClose(g.LogFile);
4499 g.LogFile = NULL;
4500 }
4501 g.LogBuffer.clear();
4502 g.DebugLogBuf.clear();
4503 g.DebugLogIndex.clear();
4504
4505 g.Initialized = false;
4506 }
4507
4508 // No specific ordering/dependency support, will see as needed
4509 ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
4510 {
4511 ImGuiContext& g = *ctx;
4512 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
4513 g.Hooks.push_back(*hook);
4514 g.Hooks.back().HookId = ++g.HookIdNext;
4515 return g.HookIdNext;
4516 }
4517
4518 // Deferred removal, avoiding issue with changing vector while iterating it
4519 void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
4520 {
4521 ImGuiContext& g = *ctx;
4522 IM_ASSERT(hook_id != 0);
4523 for (ImGuiContextHook& hook : g.Hooks)
4524 if (hook.HookId == hook_id)
4525 hook.Type = ImGuiContextHookType_PendingRemoval_;
4526 }
4527
4528 // Call context hooks (used by e.g. test engine)
4529 // We assume a small number of hooks so all stored in same array
4530 void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
4531 {
4532 ImGuiContext& g = *ctx;
4533 for (ImGuiContextHook& hook : g.Hooks)
4534 if (hook.Type == hook_type)
4535 hook.Callback(&g, &hook);
4536 }
4537
4538 //-----------------------------------------------------------------------------
4539 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4540 //-----------------------------------------------------------------------------
4541
4542 // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4543 ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4544 {
4545 memset(this, 0, sizeof(*this));
4546 Ctx = ctx;
4547 Name = ImStrdup(name);
4548 NameBufLen = (int)ImStrlen(name) + 1;
4549 ID = ImHashStr(name);
4550 IDStack.push_back(ID);
4551 ViewportAllowPlatformMonitorExtend = -1;
4552 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
4553 MoveId = GetID("#MOVE");
4554 TabId = GetID("#TAB");
4555 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4556 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4557 AutoFitFramesX = AutoFitFramesY = -1;
4558 AutoPosLastDirection = ImGuiDir_None;
4559 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4560 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4561 LastFrameActive = -1;
4562 LastFrameJustFocused = -1;
4563 LastTimeActive = -1.0f;
4564 FontRefSize = 0.0f;
4565 FontWindowScale = FontWindowScaleParents = 1.0f;
4566 SettingsOffset = -1;
4567 DockOrder = -1;
4568 DrawList = &DrawListInst;
4569 DrawList->_OwnerName = Name;
4570 DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData);
4571 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4572 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4573 }
4574
4575 ImGuiWindow::~ImGuiWindow()
4576 {
4577 IM_ASSERT(DrawList == &DrawListInst);
4578 IM_DELETE(Name);
4579 ColumnsStorage.clear_destruct();
4580 }
4581
4582 static void SetCurrentWindow(ImGuiWindow* window)
4583 {
4584 ImGuiContext& g = *GImGui;
4585 g.CurrentWindow = window;
4586 g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
4587 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4588 if (window)
4589 {
4590 bool backup_skip_items = window->SkipItems;
4591 window->SkipItems = false;
4592 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
4593 {
4594 ImGuiViewport* viewport = window->Viewport;
4595 g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity()
4596 }
4597 ImGui::UpdateCurrentFontSize(0.0f);
4598 window->SkipItems = backup_skip_items;
4599 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4600 }
4601 }
4602
4603 void ImGui::GcCompactTransientMiscBuffers()
4604 {
4605 ImGuiContext& g = *GImGui;
4606 g.ItemFlagsStack.clear();
4607 g.GroupStack.clear();
4608 g.InputTextLineIndex.clear();
4609 g.MultiSelectTempDataStacked = 0;
4610 g.MultiSelectTempData.clear_destruct();
4611 TableGcCompactSettings();
4612 for (ImFontAtlas* atlas : g.FontAtlases)
4613 atlas->CompactCache();
4614 }
4615
4616 // Free up/compact internal window buffers, we can use this when a window becomes unused.
4617 // Not freed:
4618 // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4619 // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4620 void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4621 {
4622 window->MemoryCompacted = true;
4623 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4624 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4625 window->IDStack.clear();
4626 window->DrawList->_ClearFreeMemory();
4627 window->DC.ChildWindows.clear();
4628 window->DC.ItemWidthStack.clear();
4629 window->DC.TextWrapPosStack.clear();
4630 }
4631
4632 void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4633 {
4634 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4635 // The other buffers tends to amortize much faster.
4636 window->MemoryCompacted = false;
4637 window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4638 window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4639 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4640 }
4641
4642 void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4643 {
4644 ImGuiContext& g = *GImGui;
4645
4646 // Clear previous active id
4647 if (g.ActiveId != 0)
4648 {
4649 // Store deactivate data
4650 ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData;
4651 deactivated_data->ID = g.ActiveId;
4652 deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData?
4653 deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4654 deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId);
4655
4656 // This could be written in a more general way (e.g associate a hook to ActiveId),
4657 // but since this is currently quite an exception we'll leave it as is.
4658 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
4659 if (g.InputTextState.ID == g.ActiveId)
4660 InputTextDeactivateHook(g.ActiveId);
4661
4662 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4663 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4664 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4665 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4666 {
4667 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4668 StopMouseMovingWindow();
4669 }
4670 }
4671
4672 // Set active id
4673 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4674 if (g.ActiveIdIsJustActivated)
4675 {
4676 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 : "");
4677 g.ActiveIdTimer = 0.0f;
4678 g.ActiveIdHasBeenPressedBefore = false;
4679 g.ActiveIdHasBeenEditedBefore = false;
4680 g.ActiveIdMouseButton = -1;
4681 if (id != 0)
4682 {
4683 g.LastActiveId = id;
4684 g.LastActiveIdTimer = 0.0f;
4685 }
4686 }
4687 g.ActiveId = id;
4688 g.ActiveIdAllowOverlap = false;
4689 g.ActiveIdNoClearOnFocusLoss = false;
4690 g.ActiveIdWindow = window;
4691 g.ActiveIdHasBeenEditedThisFrame = false;
4692 g.ActiveIdFromShortcut = false;
4693 g.ActiveIdDisabledId = 0;
4694 if (id)
4695 {
4696 g.ActiveIdIsAlive = id;
4697 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4698 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4699 }
4700
4701 // Clear declaration of inputs claimed by the widget
4702 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4703 g.ActiveIdUsingNavDirMask = 0x00;
4704 g.ActiveIdUsingAllKeyboardKeys = false;
4705 }
4706
4707 void ImGui::ClearActiveID()
4708 {
4709 SetActiveID(0, NULL); // g.ActiveId = 0;
4710 }
4711
4712 void ImGui::SetHoveredID(ImGuiID id)
4713 {
4714 ImGuiContext& g = *GImGui;
4715 g.HoveredId = id;
4716 g.HoveredIdAllowOverlap = false;
4717 if (id != 0 && g.HoveredIdPreviousFrame != id)
4718 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4719 }
4720
4721 ImGuiID ImGui::GetHoveredID()
4722 {
4723 ImGuiContext& g = *GImGui;
4724 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4725 }
4726
4727 void ImGui::MarkItemEdited(ImGuiID id)
4728 {
4729 // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
4730 // 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.
4731 ImGuiContext& g = *GImGui;
4732 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
4733 return;
4734 if (g.ActiveId == id || g.ActiveId == 0)
4735 {
4736 // FIXME: Can't we fully rely on LastItemData yet?
4737 g.ActiveIdHasBeenEditedThisFrame = true;
4738 g.ActiveIdHasBeenEditedBefore = true;
4739 if (g.DeactivatedItemData.ID == id)
4740 g.DeactivatedItemData.HasBeenEditedBefore = true;
4741 }
4742
4743 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4744 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4745 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4746
4747 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4748 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4749 }
4750
4751 bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4752 {
4753 // An active popup disable hovering on other windows (apart from its own children)
4754 // FIXME-OPT: This could be cached/stored within the window.
4755 ImGuiContext& g = *GImGui;
4756 if (g.NavWindow)
4757 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4758 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4759 {
4760 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4761 // NB: The 'else' is important because Modal windows are also Popups.
4762 bool want_inhibit = false;
4763 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4764 want_inhibit = true;
4765 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4766 want_inhibit = true;
4767
4768 // Inhibit hover unless the window is within the stack of our modal/popup
4769 if (want_inhibit)
4770 if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4771 return false;
4772 }
4773
4774 // Filter by viewport
4775 if (window->Viewport != g.MouseViewport)
4776 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4777 return false;
4778
4779 return true;
4780 }
4781
4782 static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4783 {
4784 ImGuiContext& g = *GImGui;
4785 if (flags & ImGuiHoveredFlags_DelayNormal)
4786 return g.Style.HoverDelayNormal;
4787 if (flags & ImGuiHoveredFlags_DelayShort)
4788 return g.Style.HoverDelayShort;
4789 return 0.0f;
4790 }
4791
4792 static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4793 {
4794 // Allow instance flags to override shared flags
4795 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4796 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4797 return user_flags | shared_flags;
4798 }
4799
4800 // This is roughly matching the behavior of internal-facing ItemHoverable()
4801 // - 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()
4802 // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4803 bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4804 {
4805 ImGuiContext& g = *GImGui;
4806 ImGuiWindow* window = g.CurrentWindow;
4807 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
4808
4809 if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
4810 {
4811 if (!IsItemFocused())
4812 return false;
4813 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4814 return false;
4815
4816 if (flags & ImGuiHoveredFlags_ForTooltip)
4817 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4818 }
4819 else
4820 {
4821 // Test for bounding box overlap, as updated as ItemAdd()
4822 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4823 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4824 return false;
4825
4826 if (flags & ImGuiHoveredFlags_ForTooltip)
4827 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4828
4829 // Done with rectangle culling so we can perform heavier checks now
4830 // Test if we are hovering the right window (our window could be behind another window)
4831 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4832 // [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
4833 // 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
4834 // the test that has been running for a long while.
4835 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4836 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4837 return false;
4838
4839 // Test if another item is active (e.g. being dragged)
4840 const ImGuiID id = g.LastItemData.ID;
4841 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4842 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4843 {
4844 // When ActiveId == MoveId it means that either:
4845 // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag)
4846 // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed.
4847 // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId.
4848 bool cancel_is_hovered = true;
4849 if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id))
4850 cancel_is_hovered = false;
4851 // When ActiveId == TabId it means user clicked docking tab for the window.
4852 if (g.ActiveId == window->TabId)
4853 cancel_is_hovered = false;
4854 if (cancel_is_hovered)
4855 return false;
4856 }
4857
4858 // Test if interactions on this window are blocked by an active popup or modal.
4859 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4860 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4861 return false;
4862
4863 // Test if the item is disabled
4864 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4865 return false;
4866
4867 // Special handling for calling after Begin() which represent the title bar or tab.
4868 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4869 // will never be overwritten so we need to detect the case.
4870 if (id == window->MoveId && window->WriteAccessed)
4871 return false;
4872
4873 // Test if using AllowOverlap and overlapped
4874 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4875 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4876 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4877 return false;
4878 }
4879
4880 // Handle hover delay
4881 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4882 const float delay = CalcDelayFromHoveredFlags(flags);
4883 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4884 {
4885 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(g.LastItemData.Rect.Min);
4886 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4887 g.HoverItemDelayTimer = 0.0f;
4888 g.HoverItemDelayId = hover_delay_id;
4889
4890 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4891 // but once unlocked on a given item we also moving.
4892 //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); }
4893 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4894 return false;
4895
4896 if (g.HoverItemDelayTimer < delay)
4897 return false;
4898 }
4899
4900 return true;
4901 }
4902
4903 // Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK.
4904 // Returns whether the item was hovered, logic differs slightly from IsItemHovered().
4905 // (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4906 // FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4907 // If you used this in your legacy/custom widgets code:
4908 // - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
4909 // - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4910 bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4911 {
4912 ImGuiContext& g = *GImGui;
4913 ImGuiWindow* window = g.CurrentWindow;
4914
4915 // Detect ID conflicts
4916 // (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)
4917 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4918 if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
4919 {
4920 g.HoveredIdPreviousFrameItemCount++;
4921 if (g.DebugDrawIdConflictsId == id)
4922 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);
4923 }
4924 #endif
4925
4926 if (g.HoveredWindow != window)
4927 return false;
4928 if (!IsMouseHoveringRect(bb.Min, bb.Max))
4929 return false;
4930
4931 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4932 return false;
4933 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4934 if (!g.ActiveIdFromShortcut)
4935 return false;
4936
4937 // We are done with rectangle culling so we can perform heavier checks now.
4938 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4939 {
4940 g.HoveredIdIsDisabled = true;
4941 return false;
4942 }
4943
4944 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4945 // hover test in widgets code. We could also decide to split this function is two.
4946 if (id != 0)
4947 {
4948 // Drag source doesn't report as hovered
4949 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4950 return false;
4951
4952 SetHoveredID(id);
4953
4954 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4955 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4956 if (item_flags & ImGuiItemFlags_AllowOverlap)
4957 {
4958 g.HoveredIdAllowOverlap = true;
4959 if (g.HoveredIdPreviousFrame != id)
4960 return false;
4961 }
4962
4963 // Display shortcut (only works with mouse)
4964 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4965 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
4966 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4967 SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4968 }
4969
4970 // When disabled we'll return false but still set HoveredId
4971 if (item_flags & ImGuiItemFlags_Disabled)
4972 {
4973 // Release active id if turning disabled
4974 if (g.ActiveId == id && id != 0)
4975 ClearActiveID();
4976 g.HoveredIdIsDisabled = true;
4977 return false;
4978 }
4979
4980 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4981 if (id != 0)
4982 {
4983 // [DEBUG] Item Picker tool!
4984 // We perform the check here because reaching is path is rare (1~ time a frame),
4985 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4986 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4987 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4988 GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4989 if (g.DebugItemPickerBreakId == id)
4990 IM_DEBUG_BREAK();
4991 }
4992 #endif
4993
4994 if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
4995 return false;
4996
4997 return true;
4998 }
4999
5000 // FIXME: This is inlined/duplicated in ItemAdd()
5001 // FIXME: The id != 0 path is not used by our codebase, may get rid of it?
5002 bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
5003 {
5004 ImGuiContext& g = *GImGui;
5005 ImGuiWindow* window = g.CurrentWindow;
5006 if (!bb.Overlaps(window->ClipRect))
5007 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
5008 if (!g.ItemUnclipByLog)
5009 return true;
5010 return false;
5011 }
5012
5013 // This is also inlined in ItemAdd()
5014 // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
5015 void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect)
5016 {
5017 ImGuiContext& g = *GImGui;
5018 g.LastItemData.ID = item_id;
5019 g.LastItemData.ItemFlags = item_flags;
5020 g.LastItemData.StatusFlags = status_flags;
5021 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
5022 }
5023
5024 static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
5025 {
5026 ImGuiContext& g = *GImGui;
5027 if (window->DockIsActive)
5028 SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.DockTabItemStatusFlags, window->DC.DockTabItemRect);
5029 else
5030 SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect);
5031 }
5032
5033 static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect)
5034 {
5035 ImGuiContext& g = *GImGui;
5036 SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.ChildItemStatusFlags, rect);
5037 }
5038
5039 float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
5040 {
5041 if (wrap_pos_x < 0.0f)
5042 return 0.0f;
5043
5044 ImGuiContext& g = *GImGui;
5045 ImGuiWindow* window = g.CurrentWindow;
5046 if (wrap_pos_x == 0.0f)
5047 {
5048 // We could decide to setup a default wrapping max point for auto-resizing windows,
5049 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
5050 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
5051 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
5052 //else
5053 wrap_pos_x = window->WorkRect.Max.x;
5054 }
5055 else if (wrap_pos_x > 0.0f)
5056 {
5057 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
5058 }
5059
5060 return ImMax(wrap_pos_x - pos.x, 1.0f);
5061 }
5062
5063 // IM_ALLOC() == ImGui::MemAlloc()
5064 void* ImGui::MemAlloc(size_t size)
5065 {
5066 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
5067 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5068 if (ImGuiContext* ctx = GImGui)
5069 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
5070 #endif
5071 return ptr;
5072 }
5073
5074 // IM_FREE() == ImGui::MemFree()
5075 void ImGui::MemFree(void* ptr)
5076 {
5077 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5078 if (ptr != NULL)
5079 if (ImGuiContext* ctx = GImGui)
5080 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
5081 #endif
5082 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
5083 }
5084
5085 // 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"
5086 void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
5087 {
5088 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5089 IM_UNUSED(ptr);
5090 if (entry->FrameCount != frame_count)
5091 {
5092 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
5093 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5094 entry->FrameCount = frame_count;
5095 entry->AllocCount = entry->FreeCount = 0;
5096 }
5097 if (size != (size_t)-1)
5098 {
5099 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
5100 entry->AllocCount++;
5101 info->TotalAllocCount++;
5102 }
5103 else
5104 {
5105 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
5106 entry->FreeCount++;
5107 info->TotalFreeCount++;
5108 }
5109 }
5110
5111 const char* ImGui::GetClipboardText()
5112 {
5113 ImGuiContext& g = *GImGui;
5114 return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : "";
5115 }
5116
5117 void ImGui::SetClipboardText(const char* text)
5118 {
5119 ImGuiContext& g = *GImGui;
5120 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5121 g.PlatformIO.Platform_SetClipboardTextFn(&g, text);
5122 }
5123
5124 const char* ImGui::GetVersion()
5125 {
5126 return IMGUI_VERSION;
5127 }
5128
5129 ImGuiIO& ImGui::GetIO()
5130 {
5131 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5132 return GImGui->IO;
5133 }
5134
5135 // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5136 ImGuiIO& ImGui::GetIO(ImGuiContext* ctx)
5137 {
5138 IM_ASSERT(ctx != NULL);
5139 return ctx->IO;
5140 }
5141
5142 ImGuiPlatformIO& ImGui::GetPlatformIO()
5143 {
5144 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
5145 return GImGui->PlatformIO;
5146 }
5147
5148 // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5149 ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx)
5150 {
5151 IM_ASSERT(ctx != NULL);
5152 return ctx->PlatformIO;
5153 }
5154
5155 // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
5156 ImDrawData* ImGui::GetDrawData()
5157 {
5158 ImGuiContext& g = *GImGui;
5159 ImGuiViewportP* viewport = g.Viewports[0];
5160 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
5161 }
5162
5163 double ImGui::GetTime()
5164 {
5165 return GImGui->Time;
5166 }
5167
5168 int ImGui::GetFrameCount()
5169 {
5170 return GImGui->FrameCount;
5171 }
5172
5173 static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
5174 {
5175 // Create the draw list on demand, because they are not frequently used for all viewports
5176 ImGuiContext& g = *GImGui;
5177 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
5178 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
5179 if (draw_list == NULL)
5180 {
5181 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
5182 draw_list->_OwnerName = drawlist_name;
5183 viewport->BgFgDrawLists[drawlist_no] = draw_list;
5184 }
5185
5186 // Our ImDrawList system requires that there is always a command
5187 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
5188 {
5189 draw_list->_ResetForNewFrame();
5190 draw_list->PushTexture(g.IO.Fonts->TexRef);
5191 draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
5192 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
5193 }
5194 return draw_list;
5195 }
5196
5197 ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
5198 {
5199 if (viewport == NULL)
5200 viewport = GImGui->CurrentWindow->Viewport;
5201 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
5202 }
5203
5204 ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
5205 {
5206 if (viewport == NULL)
5207 viewport = GImGui->CurrentWindow->Viewport;
5208 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
5209 }
5210
5211 ImDrawListSharedData* ImGui::GetDrawListSharedData()
5212 {
5213 return &GImGui->DrawListSharedData;
5214 }
5215
5216 void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
5217 {
5218 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
5219 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
5220 // This is because we want ActiveId to be set even when the window is not permitted to move.
5221 ImGuiContext& g = *GImGui;
5222 FocusWindow(window);
5223 SetActiveID(window->MoveId, window);
5224 if (g.IO.ConfigNavCursorVisibleAuto)
5225 g.NavCursorVisible = false;
5226 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
5227 g.ActiveIdNoClearOnFocusLoss = true;
5228 SetActiveIdUsingAllKeyboardKeys();
5229
5230 bool can_move_window = true;
5231 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
5232 can_move_window = false;
5233 if (ImGuiDockNode* node = window->DockNodeAsHost)
5234 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
5235 can_move_window = false;
5236 if (can_move_window)
5237 g.MovingWindow = window;
5238 }
5239
5240 // We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
5241 void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
5242 {
5243 ImGuiContext& g = *GImGui;
5244 bool can_undock_node = false;
5245 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
5246 {
5247 // Can undock if:
5248 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
5249 // - 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.
5250 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
5251 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
5252 can_undock_node = true;
5253 }
5254
5255 const bool clicked = IsMouseClicked(0);
5256 const bool dragging = IsMouseDragging(0);
5257 if (can_undock_node && dragging)
5258 DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
5259 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
5260 StartMouseMovingWindow(window);
5261 }
5262
5263 // This is not 100% symetric with StartMouseMovingWindow().
5264 // We do NOT clear ActiveID, because:
5265 // - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired.
5266 // - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item).
5267 void ImGui::StopMouseMovingWindow()
5268 {
5269 ImGuiContext& g = *GImGui;
5270 ImGuiWindow* window = g.MovingWindow;
5271
5272 // Ref commits 6b7766817, 36055213c for some partial history on checking if viewport != NULL.
5273 if (window && window->Viewport)
5274 {
5275 // Try to merge the window back into the main viewport.
5276 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
5277 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
5278 UpdateTryMergeWindowIntoHostViewport(window, g.MouseViewport);
5279
5280 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
5281 if (!IsDragDropPayloadBeingAccepted())
5282 g.MouseViewport = window->Viewport;
5283
5284 // Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport()
5285 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
5286 if (window_can_use_inputs)
5287 window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
5288 }
5289 g.MovingWindow = NULL;
5290 }
5291
5292 // Handle mouse moving window
5293 // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
5294 // FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId.
5295 // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
5296 // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
5297 void ImGui::UpdateMouseMovingWindowNewFrame()
5298 {
5299 ImGuiContext& g = *GImGui;
5300 if (g.MovingWindow != NULL)
5301 {
5302 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
5303 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
5304 KeepAliveID(g.ActiveId);
5305 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
5306 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
5307
5308 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
5309 const bool window_disappeared = (!moving_window->WasActive && !moving_window->Active);
5310 if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappeared)
5311 {
5312 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
5313 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
5314 {
5315 SetWindowPos(moving_window, pos, ImGuiCond_Always);
5316 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
5317 {
5318 moving_window->Viewport->Pos = pos;
5319 moving_window->Viewport->UpdateWorkRect();
5320 }
5321 }
5322 FocusWindow(g.MovingWindow);
5323 }
5324 else
5325 {
5326 StopMouseMovingWindow();
5327 ClearActiveID();
5328 }
5329 }
5330 else
5331 {
5332 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
5333 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
5334 {
5335 KeepAliveID(g.ActiveId);
5336 if (!g.IO.MouseDown[0])
5337 ClearActiveID();
5338 }
5339 }
5340 }
5341
5342 // Initiate focusing and moving window when clicking on empty space or title bar.
5343 // Initiate focusing window when clicking on a disabled item.
5344 // Handle left-click and right-click focus.
5345 void ImGui::UpdateMouseMovingWindowEndFrame()
5346 {
5347 ImGuiContext& g = *GImGui;
5348 if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
5349 return;
5350
5351 // Unless we just made a window/popup appear
5352 if (g.NavWindow && g.NavWindow->Appearing)
5353 return;
5354
5355 // Click on empty space to focus window and start moving
5356 // (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!)
5357 if (g.IO.MouseClicked[0])
5358 {
5359 // Handle the edge case of a popup being closed while clicking in its empty space.
5360 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
5361 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
5362 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
5363
5364 if (root_window != NULL && !is_closed_popup)
5365 {
5366 StartMouseMovingWindow(g.HoveredWindow); //-V595
5367
5368 // FIXME: In principal we might be able to call StopMouseMovingWindow() below.
5369 // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId.
5370
5371 // Cancel moving if clicked outside of title bar
5372 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
5373 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
5374 if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
5375 g.MovingWindow = NULL;
5376
5377 // Cancel moving if clicked over an item which was disabled or inhibited by popups
5378 // (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)
5379 if (g.HoveredIdIsDisabled)
5380 {
5381 g.MovingWindow = NULL;
5382 g.ActiveIdDisabledId = g.HoveredId;
5383 }
5384 }
5385 else if (root_window == NULL && g.NavWindow != NULL)
5386 {
5387 // Clicking on void disable focus
5388 FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
5389 }
5390 }
5391
5392 // With right mouse button we close popups without changing focus based on where the mouse is aimed
5393 // Instead, focus will be restored to the window under the bottom-most closed popup.
5394 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
5395 if (g.IO.MouseClicked[1] && g.HoveredId == 0)
5396 {
5397 // Find the top-most window between HoveredWindow and the top-most Modal Window.
5398 // This is where we can trim the popup stack.
5399 ImGuiWindow* modal = GetTopMostPopupModal();
5400 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
5401 ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
5402 }
5403 }
5404
5405 // This is called during NewFrame()->UpdateViewportsNewFrame() only.
5406 // Need to keep in sync with SetWindowPos()
5407 static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
5408 {
5409 window->Pos += delta;
5410 window->ClipRect.Translate(delta);
5411 window->OuterRectClipped.Translate(delta);
5412 window->InnerRect.Translate(delta);
5413 window->DC.CursorPos += delta;
5414 window->DC.CursorStartPos += delta;
5415 window->DC.CursorMaxPos += delta;
5416 window->DC.IdealMaxPos += delta;
5417 }
5418
5419 static void ScaleWindow(ImGuiWindow* window, float scale)
5420 {
5421 ImVec2 origin = window->Viewport->Pos;
5422 window->Pos = ImFloor((window->Pos - origin) * scale + origin);
5423 window->Size = ImTrunc(window->Size * scale);
5424 window->SizeFull = ImTrunc(window->SizeFull * scale);
5425 window->ContentSize = ImTrunc(window->ContentSize * scale);
5426 }
5427
5428 static bool IsWindowActiveAndVisible(ImGuiWindow* window)
5429 {
5430 return (window->Active) && (!window->Hidden);
5431 }
5432
5433 // 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)
5434 void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos)
5435 {
5436 ImGuiContext& g = *GImGui;
5437 ImGuiIO& io = g.IO;
5438
5439 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
5440 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
5441 g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding);
5442
5443 // Find the window hovered by mouse:
5444 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
5445 // - 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.
5446 // - 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.
5447 bool clear_hovered_windows = false;
5448 FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
5449 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
5450 g.HoveredWindowBeforeClear = g.HoveredWindow;
5451
5452 // Modal windows prevents mouse from hovering behind them.
5453 ImGuiWindow* modal_window = GetTopMostPopupModal();
5454 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
5455 clear_hovered_windows = true;
5456
5457 // Disabled mouse hovering (we don't currently clear MousePos, we could)
5458 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
5459 clear_hovered_windows = true;
5460
5461 // We track click ownership. When clicked outside of a window the click is owned by the application and
5462 // won't report hovering nor request capture even while dragging over our windows afterward.
5463 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
5464 const bool has_open_modal = (modal_window != NULL);
5465 int mouse_earliest_down = -1;
5466 bool mouse_any_down = false;
5467 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
5468 {
5469 if (io.MouseClicked[i])
5470 {
5471 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
5472 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
5473 }
5474 mouse_any_down |= io.MouseDown[i];
5475 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
5476 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
5477 mouse_earliest_down = i;
5478 }
5479 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
5480 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
5481
5482 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
5483 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
5484 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
5485 if (!mouse_avail && !mouse_dragging_extern_payload)
5486 clear_hovered_windows = true;
5487
5488 if (clear_hovered_windows)
5489 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5490
5491 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
5492 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
5493 if (g.WantCaptureMouseNextFrame != -1)
5494 {
5495 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
5496 }
5497 else
5498 {
5499 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
5500 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
5501 }
5502
5503 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
5504 io.WantCaptureKeyboard = false;
5505 if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
5506 {
5507 if ((g.ActiveId != 0) || (modal_window != NULL))
5508 io.WantCaptureKeyboard = true;
5509 else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
5510 io.WantCaptureKeyboard = true;
5511 }
5512 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
5513 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
5514
5515 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
5516 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
5517 }
5518
5519 // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
5520 // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
5521 static void SetupDrawListSharedData()
5522 {
5523 ImGuiContext& g = *GImGui;
5524 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
5525 for (ImGuiViewportP* viewport : g.Viewports)
5526 virtual_space.Add(viewport->GetMainRect());
5527 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
5528 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
5529 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
5530 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
5531 if (g.Style.AntiAliasedLines)
5532 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
5533 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
5534 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
5535 if (g.Style.AntiAliasedFill)
5536 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
5537 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
5538 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
5539 g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments.
5540 }
5541
5542 void ImGui::NewFrame()
5543 {
5544 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5545 ImGuiContext& g = *GImGui;
5546
5547 // Remove pending delete hooks before frame start.
5548 // This deferred removal avoid issues of removal while iterating the hook vector
5549 for (int n = g.Hooks.Size - 1; n >= 0; n--)
5550 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
5551 g.Hooks.erase(&g.Hooks[n]);
5552
5553 CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
5554
5555 // Check and assert for various common IO and Configuration mistakes
5556 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
5557 ErrorCheckNewFrameSanityChecks();
5558 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
5559
5560 // Load settings on first frame, save settings when modified (after a delay)
5561 UpdateSettings();
5562
5563 g.Time += g.IO.DeltaTime;
5564 g.FrameCount += 1;
5565 g.TooltipOverrideCount = 0;
5566 g.WindowsActiveCount = 0;
5567 g.MenusIdSubmittedThisFrame.resize(0);
5568
5569 // Calculate frame-rate for the user, as a purely luxurious feature
5570 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
5571 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
5572 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
5573 g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
5574 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
5575
5576 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
5577 g.InputEventsTrail.resize(0);
5578 UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
5579
5580 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
5581 UpdateViewportsNewFrame();
5582
5583 // Update texture list (collect destroyed textures, etc.)
5584 UpdateTexturesNewFrame();
5585
5586 // Setup current font and draw list shared data
5587 SetupDrawListSharedData();
5588 UpdateFontsNewFrame();
5589
5590 g.WithinFrameScope = true;
5591
5592 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
5593 for (ImGuiViewportP* viewport : g.Viewports)
5594 {
5595 viewport->DrawData = NULL;
5596 viewport->DrawDataP.Valid = false;
5597 }
5598
5599 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
5600 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
5601 KeepAliveID(g.DragDropPayload.SourceId);
5602
5603 // [DEBUG]
5604 if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
5605 g.DebugDrawIdConflictsId = 0;
5606 if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
5607 g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame;
5608
5609 // Update HoveredId data
5610 if (!g.HoveredIdPreviousFrame)
5611 g.HoveredIdTimer = 0.0f;
5612 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
5613 g.HoveredIdNotActiveTimer = 0.0f;
5614 if (g.HoveredId)
5615 g.HoveredIdTimer += g.IO.DeltaTime;
5616 if (g.HoveredId && g.ActiveId != g.HoveredId)
5617 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
5618 g.HoveredIdPreviousFrame = g.HoveredId;
5619 g.HoveredIdPreviousFrameItemCount = 0;
5620 g.HoveredId = 0;
5621 g.HoveredIdAllowOverlap = false;
5622 g.HoveredIdIsDisabled = false;
5623
5624 // Clear ActiveID if the item is not alive anymore.
5625 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
5626 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
5627 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
5628 {
5629 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
5630 ClearActiveID();
5631 }
5632
5633 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
5634 if (g.ActiveId)
5635 g.ActiveIdTimer += g.IO.DeltaTime;
5636 g.LastActiveIdTimer += g.IO.DeltaTime;
5637 g.ActiveIdPreviousFrame = g.ActiveId;
5638 g.ActiveIdIsAlive = 0;
5639 g.ActiveIdHasBeenEditedThisFrame = false;
5640 g.ActiveIdIsJustActivated = false;
5641 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
5642 g.TempInputId = 0;
5643 if (g.ActiveId == 0)
5644 {
5645 g.ActiveIdUsingNavDirMask = 0x00;
5646 g.ActiveIdUsingAllKeyboardKeys = false;
5647 }
5648 if (g.DeactivatedItemData.ElapseFrame < g.FrameCount)
5649 g.DeactivatedItemData.ID = 0;
5650 g.DeactivatedItemData.IsAlive = false;
5651
5652 // Record when we have been stationary as this state is preserved while over same item.
5653 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5654 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5655 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5656 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5657 else if (g.HoverItemDelayId == 0)
5658 g.HoverItemUnlockedStationaryId = 0;
5659 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5660 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5661 else if (g.HoveredWindow == NULL)
5662 g.HoverWindowUnlockedStationaryId = 0;
5663
5664 // Update hover delay for IsItemHovered() with delays and tooltips
5665 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5666 if (g.HoverItemDelayId != 0)
5667 {
5668 g.HoverItemDelayTimer += g.IO.DeltaTime;
5669 g.HoverItemDelayClearTimer = 0.0f;
5670 g.HoverItemDelayId = 0;
5671 }
5672 else if (g.HoverItemDelayTimer > 0.0f)
5673 {
5674 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5675 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5676 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5677 if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5678 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.
5679 }
5680
5681 // Drag and drop
5682 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5683 g.DragDropAcceptIdCurr = 0;
5684 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5685 g.DragDropWithinSource = false;
5686 g.DragDropWithinTarget = false;
5687 g.DragDropHoldJustPressedId = 0;
5688 g.TooltipPreviousWindow = NULL;
5689
5690 // Close popups on focus lost (currently wip/opt-in)
5691 //if (g.IO.AppFocusLost)
5692 // ClosePopupsExceptModals();
5693
5694 // Update keyboard input state
5695 UpdateKeyboardInputs();
5696
5697 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5698 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5699 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5700 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5701
5702 // Update keyboard/gamepad navigation
5703 NavUpdate();
5704
5705 // Update mouse input state
5706 UpdateMouseInputs();
5707
5708 // Undocking
5709 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5710 DockContextNewFrameUpdateUndocking(&g);
5711
5712 // Mark all windows as not visible and compact unused memory.
5713 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5714 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5715 for (ImGuiWindow* window : g.Windows)
5716 {
5717 window->WasActive = window->Active;
5718 window->Active = false;
5719 window->WriteAccessed = false;
5720 window->BeginCountPreviousFrame = window->BeginCount;
5721 window->BeginCount = 0;
5722
5723 // Garbage collect transient buffers of recently unused windows
5724 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5725 GcCompactTransientWindowBuffers(window);
5726 }
5727
5728 // Find hovered window
5729 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5730 // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
5731 UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos);
5732
5733 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5734 UpdateMouseMovingWindowNewFrame();
5735
5736 // Background darkening/whitening
5737 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5738 g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5739 else
5740 g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5741
5742 g.MouseCursor = ImGuiMouseCursor_Arrow;
5743 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5744
5745 // Platform IME data: reset for the frame
5746 g.PlatformImeDataPrev = g.PlatformImeData;
5747 g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false;
5748
5749 // Mouse wheel scrolling, scale
5750 UpdateMouseWheel();
5751
5752 // Garbage collect transient buffers of recently unused tables
5753 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5754 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5755 TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5756 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5757 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5758 TableGcCompactTransientBuffers(&table_temp_data);
5759 if (g.GcCompactAll)
5760 GcCompactTransientMiscBuffers();
5761 g.GcCompactAll = false;
5762
5763 // Closing the focused window restore focus to the first active root window in descending z-order
5764 if (g.NavWindow && !g.NavWindow->WasActive)
5765 FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5766
5767 // No window should be open at the beginning of the frame.
5768 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5769 g.CurrentWindowStack.resize(0);
5770 g.BeginPopupStack.resize(0);
5771 g.ItemFlagsStack.resize(0);
5772 g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags
5773 g.CurrentItemFlags = g.ItemFlagsStack.back();
5774 g.GroupStack.resize(0);
5775
5776 // Docking
5777 DockContextNewFrameUpdateDocking(&g);
5778
5779 // [DEBUG] Update debug features
5780 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5781 UpdateDebugToolItemPicker();
5782 UpdateDebugToolStackQueries();
5783 UpdateDebugToolFlashStyleColor();
5784 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5785 {
5786 g.DebugLocateId = 0;
5787 g.DebugBreakInLocateId = false;
5788 }
5789 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5790 {
5791 DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5792 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5793 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5794 }
5795 #endif
5796
5797 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5798 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5799 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5800 g.WithinFrameScopeWithImplicitWindow = true;
5801 SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5802 Begin("Debug##Default");
5803 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5804
5805 // Store stack sizes
5806 g.ErrorCountCurrentFrame = 0;
5807 ErrorRecoveryStoreState(&g.StackSizesInNewFrame);
5808
5809 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5810 // allowing to validate correct Begin/End behavior in user code.
5811 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5812 if (g.IO.ConfigDebugBeginReturnValueLoop)
5813 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5814 else
5815 g.DebugBeginReturnValueCullDepth = -1;
5816 #endif
5817
5818 CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5819 }
5820
5821 // FIXME: Add a more explicit sort order in the window structure.
5822 static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5823 {
5824 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5825 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5826 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5827 return d;
5828 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5829 return d;
5830 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5831 }
5832
5833 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5834 {
5835 out_sorted_windows->push_back(window);
5836 if (window->Active)
5837 {
5838 int count = window->DC.ChildWindows.Size;
5839 ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5840 for (int i = 0; i < count; i++)
5841 {
5842 ImGuiWindow* child = window->DC.ChildWindows[i];
5843 if (child->Active)
5844 AddWindowToSortBuffer(out_sorted_windows, child);
5845 }
5846 }
5847 }
5848
5849 static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5850 {
5851 ImGuiContext& g = *GImGui;
5852 ImGuiViewportP* viewport = window->Viewport;
5853 IM_ASSERT(viewport != NULL);
5854 g.IO.MetricsRenderWindows++;
5855 if (window->DrawList->_Splitter._Count > 1)
5856 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5857 ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5858 for (ImGuiWindow* child : window->DC.ChildWindows)
5859 if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5860 AddWindowToDrawData(child, layer);
5861 }
5862
5863 static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5864 {
5865 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5866 }
5867
5868 // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5869 static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5870 {
5871 AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5872 }
5873
5874 static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5875 {
5876 int n = builder->Layers[0]->Size;
5877 int full_size = n;
5878 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5879 full_size += builder->Layers[i]->Size;
5880 builder->Layers[0]->resize(full_size);
5881 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5882 {
5883 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5884 if (layer->empty())
5885 continue;
5886 memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5887 n += layer->Size;
5888 layer->resize(0);
5889 }
5890 }
5891
5892 static void InitViewportDrawData(ImGuiViewportP* viewport)
5893 {
5894 ImGuiIO& io = ImGui::GetIO();
5895 ImDrawData* draw_data = &viewport->DrawDataP;
5896
5897 viewport->DrawData = draw_data; // Make publicly accessible
5898 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5899 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5900 viewport->DrawDataBuilder.Layers[0]->resize(0);
5901 viewport->DrawDataBuilder.Layers[1]->resize(0);
5902
5903 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5904 // and to allow applications/backends to easily skip rendering.
5905 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5906 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5907 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5908 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5909
5910 draw_data->Valid = true;
5911 draw_data->CmdListsCount = 0;
5912 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5913 draw_data->DisplayPos = viewport->Pos;
5914 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5915 draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale;
5916 draw_data->OwnerViewport = viewport;
5917 draw_data->Textures = &ImGui::GetPlatformIO().Textures;
5918 }
5919
5920 // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5921 // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5922 // so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5923 // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5924 // some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5925 // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5926 // - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
5927 // which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
5928 void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5929 {
5930 ImGuiWindow* window = GetCurrentWindow();
5931 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5932 window->ClipRect = window->DrawList->_ClipRectStack.back();
5933 }
5934
5935 void ImGui::PopClipRect()
5936 {
5937 ImGuiWindow* window = GetCurrentWindow();
5938 window->DrawList->PopClipRect();
5939 window->ClipRect = window->DrawList->_ClipRectStack.back();
5940 }
5941
5942 static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5943 {
5944 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5945 if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5946 return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5947 return window;
5948 }
5949
5950 static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5951 {
5952 if ((col & IM_COL32_A_MASK) == 0)
5953 return;
5954
5955 ImGuiViewportP* viewport = window->Viewport;
5956 ImRect viewport_rect = viewport->GetMainRect();
5957
5958 // Draw behind window by moving the draw command at the FRONT of the draw list
5959 {
5960 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5961 // 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.
5962 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5963 draw_list->ChannelsMerge();
5964 if (draw_list->CmdBuffer.Size == 0)
5965 draw_list->AddDrawCmd();
5966 draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5967 draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5968 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5969 IM_ASSERT(cmd.ElemCount == 6);
5970 draw_list->CmdBuffer.pop_back();
5971 draw_list->CmdBuffer.push_front(cmd);
5972 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5973 draw_list->PopClipRect();
5974 }
5975
5976 // Draw over sibling docking nodes in a same docking tree
5977 if (window->RootWindow->DockIsActive)
5978 {
5979 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5980 draw_list->ChannelsMerge();
5981 if (draw_list->CmdBuffer.Size == 0)
5982 draw_list->AddDrawCmd();
5983 draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5984 RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5985 draw_list->PopClipRect();
5986 }
5987 }
5988
5989 ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5990 {
5991 ImGuiContext& g = *GImGui;
5992 ImGuiWindow* bottom_most_visible_window = parent_window;
5993 for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5994 {
5995 ImGuiWindow* window = g.Windows[i];
5996 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5997 continue;
5998 if (!IsWindowWithinBeginStackOf(window, parent_window))
5999 break;
6000 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
6001 bottom_most_visible_window = window;
6002 }
6003 return bottom_most_visible_window;
6004 }
6005
6006 // Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
6007 // We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
6008 static void ImGui::RenderDimmedBackgrounds()
6009 {
6010 ImGuiContext& g = *GImGui;
6011 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
6012 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
6013 return;
6014 const bool dim_bg_for_modal = (modal_window != NULL);
6015 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
6016 if (!dim_bg_for_modal && !dim_bg_for_window_list)
6017 return;
6018
6019 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
6020 if (dim_bg_for_modal)
6021 {
6022 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
6023 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
6024 RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
6025 viewports_already_dimmed[0] = modal_window->Viewport;
6026 }
6027 else if (dim_bg_for_window_list)
6028 {
6029 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
6030 RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
6031 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
6032 RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
6033 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
6034 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
6035
6036 // Draw border around CTRL+Tab target window
6037 ImGuiWindow* window = g.NavWindowingTargetAnim;
6038 ImGuiViewport* viewport = window->Viewport;
6039 float distance = g.FontSize;
6040 ImRect bb = window->Rect();
6041 bb.Expand(distance);
6042 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
6043 bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
6044 window->DrawList->ChannelsMerge();
6045 if (window->DrawList->CmdBuffer.Size == 0)
6046 window->DrawList->AddDrawCmd();
6047 window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
6048 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); // FIXME-DPI
6049 window->DrawList->PopClipRect();
6050 }
6051
6052 // Draw dimming background on _other_ viewports than the ones our windows are in
6053 for (ImGuiViewportP* viewport : g.Viewports)
6054 {
6055 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
6056 continue;
6057 if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
6058 continue;
6059 ImDrawList* draw_list = GetForegroundDrawList(viewport);
6060 const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
6061 draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
6062 }
6063 }
6064
6065 // 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.
6066 void ImGui::EndFrame()
6067 {
6068 ImGuiContext& g = *GImGui;
6069 IM_ASSERT(g.Initialized);
6070
6071 // Don't process EndFrame() multiple times.
6072 if (g.FrameCountEnded == g.FrameCount)
6073 return;
6074 if (!g.WithinFrameScope)
6075 {
6076 IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?");
6077 return;
6078 }
6079
6080 CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
6081
6082 // [EXPERIMENTAL] Recover from errors
6083 if (g.IO.ConfigErrorRecovery)
6084 ErrorRecoveryTryToRecoverState(&g.StackSizesInNewFrame);
6085 ErrorCheckEndFrameSanityChecks();
6086 ErrorCheckEndFrameFinalizeErrorTooltip();
6087
6088 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
6089 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
6090 if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
6091 {
6092 ImGuiViewport* viewport = FindViewportByID(ime_data->ViewportId);
6093 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);
6094 if (viewport == NULL)
6095 viewport = GetMainViewport();
6096 g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
6097 }
6098 g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0;
6099
6100 // Hide implicit/fallback "Debug" window if it hasn't been used
6101 g.WithinFrameScopeWithImplicitWindow = false;
6102 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
6103 g.CurrentWindow->Active = false;
6104 End();
6105
6106 // Update navigation: CTRL+Tab, wrap-around requests
6107 NavEndFrame();
6108
6109 // Update docking
6110 DockContextEndFrame(&g);
6111
6112 SetCurrentViewport(NULL, NULL);
6113
6114 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
6115 if (g.DragDropActive)
6116 {
6117 bool is_delivered = g.DragDropPayload.Delivery;
6118 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
6119 if (is_delivered || is_elapsed)
6120 ClearDragDrop();
6121 }
6122
6123 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
6124 // If you want to handle source item disappearing: instead of submitting your description tooltip
6125 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
6126 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
6127 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
6128 if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
6129 {
6130 g.DragDropWithinSource = true;
6131 SetTooltip("...");
6132 g.DragDropWithinSource = false;
6133 }
6134
6135 // End frame
6136 g.WithinFrameScope = false;
6137 g.FrameCountEnded = g.FrameCount;
6138 UpdateFontsEndFrame();
6139
6140 // Initiate moving window + handle left-click and right-click focus
6141 UpdateMouseMovingWindowEndFrame();
6142
6143 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
6144 UpdateViewportsEndFrame();
6145
6146 // Sort the window list so that all child windows are after their parent
6147 // We cannot do that on FocusWindow() because children may not exist yet
6148 g.WindowsTempSortBuffer.resize(0);
6149 g.WindowsTempSortBuffer.reserve(g.Windows.Size);
6150 for (ImGuiWindow* window : g.Windows)
6151 {
6152 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
6153 continue;
6154 AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
6155 }
6156
6157 // 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.
6158 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
6159 g.Windows.swap(g.WindowsTempSortBuffer);
6160 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
6161
6162 UpdateTexturesEndFrame();
6163
6164 // Unlock font atlas
6165 for (ImFontAtlas* atlas : g.FontAtlases)
6166 atlas->Locked = false;
6167
6168 // Clear Input data for next frame
6169 g.IO.MousePosPrev = g.IO.MousePos;
6170 g.IO.AppFocusLost = false;
6171 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
6172 g.IO.InputQueueCharacters.resize(0);
6173
6174 CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
6175 }
6176
6177 // Prepare the data for rendering so you can call GetDrawData()
6178 // (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all:
6179 // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
6180 void ImGui::Render()
6181 {
6182 ImGuiContext& g = *GImGui;
6183 IM_ASSERT(g.Initialized);
6184
6185 if (g.FrameCountEnded != g.FrameCount)
6186 EndFrame();
6187 if (g.FrameCountRendered == g.FrameCount)
6188 return;
6189 g.FrameCountRendered = g.FrameCount;
6190
6191 g.IO.MetricsRenderWindows = 0;
6192 CallContextHooks(&g, ImGuiContextHookType_RenderPre);
6193
6194 // Add background ImDrawList (for each active viewport)
6195 for (ImGuiViewportP* viewport : g.Viewports)
6196 {
6197 InitViewportDrawData(viewport);
6198 if (viewport->BgFgDrawLists[0] != NULL)
6199 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
6200 }
6201
6202 // Draw modal/window whitening backgrounds
6203 RenderDimmedBackgrounds();
6204
6205 // Add ImDrawList to render
6206 ImGuiWindow* windows_to_render_top_most[2];
6207 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
6208 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
6209 for (ImGuiWindow* window : g.Windows)
6210 {
6211 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
6212 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
6213 AddRootWindowToDrawData(window);
6214 }
6215 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
6216 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
6217 AddRootWindowToDrawData(windows_to_render_top_most[n]);
6218
6219 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
6220 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
6221 RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
6222
6223 // Setup ImDrawData structures for end-user
6224 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
6225 for (ImGuiViewportP* viewport : g.Viewports)
6226 {
6227 FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
6228
6229 // Add foreground ImDrawList (for each active viewport)
6230 if (viewport->BgFgDrawLists[1] != NULL)
6231 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
6232
6233 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
6234 ImDrawData* draw_data = &viewport->DrawDataP;
6235 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
6236 for (ImDrawList* draw_list : draw_data->CmdLists)
6237 draw_list->_PopUnusedDrawCmd();
6238
6239 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
6240 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
6241 }
6242
6243 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
6244 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
6245 for (ImFontAtlas* atlas : g.FontAtlases)
6246 ImFontAtlasDebugLogTextureRequests(atlas);
6247 #endif
6248
6249 CallContextHooks(&g, ImGuiContextHookType_RenderPost);
6250 }
6251
6252 // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
6253 // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
6254 ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
6255 {
6256 ImGuiContext& g = *GImGui;
6257
6258 const char* text_display_end;
6259 if (hide_text_after_double_hash)
6260 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
6261 else
6262 text_display_end = text_end;
6263
6264 ImFont* font = g.Font;
6265 const float font_size = g.FontSize;
6266 if (text == text_display_end)
6267 return ImVec2(0.0f, font_size);
6268 ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
6269
6270 // Round
6271 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
6272 // FIXME: Investigate using ceilf or e.g.
6273 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
6274 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
6275 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
6276
6277 return text_size;
6278 }
6279
6280 // Find window given position, search front-to-back
6281 // - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
6282 // - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
6283 // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
6284 // called, aka before the next Begin(). Moving window isn't affected.
6285 // - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
6286 void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
6287 {
6288 ImGuiContext& g = *GImGui;
6289 ImGuiWindow* hovered_window = NULL;
6290 ImGuiWindow* hovered_window_under_moving_window = NULL;
6291
6292 // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
6293 ImGuiViewportP* backup_moving_window_viewport = NULL;
6294 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6295 {
6296 backup_moving_window_viewport = g.MovingWindow->Viewport;
6297 g.MovingWindow->Viewport = g.MouseViewport;
6298 if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
6299 hovered_window = g.MovingWindow;
6300 }
6301
6302 ImVec2 padding_regular = g.Style.TouchExtraPadding;
6303 ImVec2 padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding));
6304 for (int i = g.Windows.Size - 1; i >= 0; i--)
6305 {
6306 ImGuiWindow* window = g.Windows[i];
6307 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6308 if (!window->WasActive || window->Hidden)
6309 continue;
6310 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
6311 continue;
6312 IM_ASSERT(window->Viewport);
6313 if (window->Viewport != g.MouseViewport)
6314 continue;
6315
6316 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
6317 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
6318 if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
6319 continue;
6320
6321 // Support for one rectangular hole in any given window
6322 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
6323 if (window->HitTestHoleSize.x != 0)
6324 {
6325 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
6326 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
6327 if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
6328 continue;
6329 }
6330
6331 if (find_first_and_in_any_viewport)
6332 {
6333 hovered_window = window;
6334 break;
6335 }
6336 else
6337 {
6338 if (hovered_window == NULL)
6339 hovered_window = window;
6340 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6341 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
6342 hovered_window_under_moving_window = window;
6343 if (hovered_window && hovered_window_under_moving_window)
6344 break;
6345 }
6346 }
6347
6348 *out_hovered_window = hovered_window;
6349 if (out_hovered_window_under_moving_window != NULL)
6350 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
6351 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6352 g.MovingWindow->Viewport = backup_moving_window_viewport;
6353 }
6354
6355 bool ImGui::IsItemActive()
6356 {
6357 ImGuiContext& g = *GImGui;
6358 if (g.ActiveId)
6359 return g.ActiveId == g.LastItemData.ID;
6360 return false;
6361 }
6362
6363 bool ImGui::IsItemActivated()
6364 {
6365 ImGuiContext& g = *GImGui;
6366 if (g.ActiveId)
6367 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
6368 return true;
6369 return false;
6370 }
6371
6372 bool ImGui::IsItemDeactivated()
6373 {
6374 ImGuiContext& g = *GImGui;
6375 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
6376 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
6377 return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount);
6378 }
6379
6380 bool ImGui::IsItemDeactivatedAfterEdit()
6381 {
6382 ImGuiContext& g = *GImGui;
6383 return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore;
6384 }
6385
6386 // == (GetItemID() == GetFocusID() && GetFocusID() != 0)
6387 bool ImGui::IsItemFocused()
6388 {
6389 ImGuiContext& g = *GImGui;
6390 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
6391 return false;
6392
6393 // Special handling for the dummy item after Begin() which represent the title bar or tab.
6394 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
6395 ImGuiWindow* window = g.CurrentWindow;
6396 if (g.LastItemData.ID == window->ID && window->WriteAccessed)
6397 return false;
6398
6399 return true;
6400 }
6401
6402 // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
6403 // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
6404 bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
6405 {
6406 return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
6407 }
6408
6409 bool ImGui::IsItemToggledOpen()
6410 {
6411 ImGuiContext& g = *GImGui;
6412 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
6413 }
6414
6415 // Call after a Selectable() or TreeNode() involved in multi-selection.
6416 // Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
6417 // This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
6418 // (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
6419 // return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
6420 bool ImGui::IsItemToggledSelection()
6421 {
6422 ImGuiContext& g = *GImGui;
6423 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
6424 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
6425 }
6426
6427 // IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
6428 // you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
6429 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
6430 bool ImGui::IsAnyItemHovered()
6431 {
6432 ImGuiContext& g = *GImGui;
6433 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
6434 }
6435
6436 bool ImGui::IsAnyItemActive()
6437 {
6438 ImGuiContext& g = *GImGui;
6439 return g.ActiveId != 0;
6440 }
6441
6442 bool ImGui::IsAnyItemFocused()
6443 {
6444 ImGuiContext& g = *GImGui;
6445 return g.NavId != 0 && g.NavCursorVisible;
6446 }
6447
6448 bool ImGui::IsItemVisible()
6449 {
6450 ImGuiContext& g = *GImGui;
6451 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
6452 }
6453
6454 bool ImGui::IsItemEdited()
6455 {
6456 ImGuiContext& g = *GImGui;
6457 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
6458 }
6459
6460 // Allow next item to be overlapped by subsequent items.
6461 // This works by requiring HoveredId to match for two subsequent frames,
6462 // so if a following items overwrite it our interactions will naturally be disabled.
6463 void ImGui::SetNextItemAllowOverlap()
6464 {
6465 ImGuiContext& g = *GImGui;
6466 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
6467 }
6468
6469 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6470 // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
6471 // FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
6472 void ImGui::SetItemAllowOverlap()
6473 {
6474 ImGuiContext& g = *GImGui;
6475 ImGuiID id = g.LastItemData.ID;
6476 if (g.HoveredId == id)
6477 g.HoveredIdAllowOverlap = true;
6478 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
6479 g.ActiveIdAllowOverlap = true;
6480 }
6481 #endif
6482
6483 // This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
6484 // FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
6485 void ImGui::SetActiveIdUsingAllKeyboardKeys()
6486 {
6487 ImGuiContext& g = *GImGui;
6488 IM_ASSERT(g.ActiveId != 0);
6489 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
6490 g.ActiveIdUsingAllKeyboardKeys = true;
6491 NavMoveRequestCancel();
6492 }
6493
6494 ImGuiID ImGui::GetItemID()
6495 {
6496 ImGuiContext& g = *GImGui;
6497 return g.LastItemData.ID;
6498 }
6499
6500 ImVec2 ImGui::GetItemRectMin()
6501 {
6502 ImGuiContext& g = *GImGui;
6503 return g.LastItemData.Rect.Min;
6504 }
6505
6506 ImVec2 ImGui::GetItemRectMax()
6507 {
6508 ImGuiContext& g = *GImGui;
6509 return g.LastItemData.Rect.Max;
6510 }
6511
6512 ImVec2 ImGui::GetItemRectSize()
6513 {
6514 ImGuiContext& g = *GImGui;
6515 return g.LastItemData.Rect.GetSize();
6516 }
6517
6518 // Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
6519 // ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
6520 bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6521 {
6522 ImGuiID id = GetCurrentWindow()->GetID(str_id);
6523 return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
6524 }
6525
6526 bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6527 {
6528 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
6529 }
6530
6531 bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6532 {
6533 ImGuiContext& g = *GImGui;
6534 ImGuiWindow* parent_window = g.CurrentWindow;
6535 IM_ASSERT(id != 0);
6536
6537 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
6538 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
6539 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
6540 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
6541 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
6542 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
6543 {
6544 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6545 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6546 }
6547 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6548 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
6549 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
6550 if (window_flags & ImGuiWindowFlags_NavFlattened)
6551 child_flags |= ImGuiChildFlags_NavFlattened;
6552 #endif
6553 if (child_flags & ImGuiChildFlags_AutoResizeX)
6554 child_flags &= ~ImGuiChildFlags_ResizeX;
6555 if (child_flags & ImGuiChildFlags_AutoResizeY)
6556 child_flags &= ~ImGuiChildFlags_ResizeY;
6557
6558 // Set window flags
6559 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
6560 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
6561 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
6562 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
6563 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
6564 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
6565
6566 // Special framed style
6567 if (child_flags & ImGuiChildFlags_FrameStyle)
6568 {
6569 PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
6570 PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
6571 PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
6572 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
6573 child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding;
6574 window_flags |= ImGuiWindowFlags_NoMove;
6575 }
6576
6577 // Forward size
6578 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
6579 // (the alternative would to store conditional flags per axis, which is possible but more code)
6580 const ImVec2 size_avail = GetContentRegionAvail();
6581 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
6582 ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
6583
6584 // A SetNextWindowSize() call always has priority (#8020)
6585 // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
6586 // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
6587 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
6588 {
6589 if (g.NextWindowData.SizeVal.x > 0.0f)
6590 {
6591 size.x = g.NextWindowData.SizeVal.x;
6592 child_flags &= ~ImGuiChildFlags_ResizeX;
6593 }
6594 if (g.NextWindowData.SizeVal.y > 0.0f)
6595 {
6596 size.y = g.NextWindowData.SizeVal.y;
6597 child_flags &= ~ImGuiChildFlags_ResizeY;
6598 }
6599 }
6600 SetNextWindowSize(size);
6601
6602 // Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
6603 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
6604 g.NextWindowData.ChildFlags |= child_flags;
6605 else
6606 g.NextWindowData.ChildFlags = child_flags;
6607 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
6608
6609 // 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.
6610 // 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.
6611 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
6612 const char* temp_window_name;
6613 /*if (name && parent_window->IDStack.back() == parent_window->ID)
6614 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
6615 else*/
6616 if (name)
6617 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
6618 else
6619 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
6620
6621 // Set style
6622 const float backup_border_size = g.Style.ChildBorderSize;
6623 if ((child_flags & ImGuiChildFlags_Borders) == 0)
6624 g.Style.ChildBorderSize = 0.0f;
6625
6626 // Begin into window
6627 const bool ret = Begin(temp_window_name, NULL, window_flags);
6628
6629 // Restore style
6630 g.Style.ChildBorderSize = backup_border_size;
6631 if (child_flags & ImGuiChildFlags_FrameStyle)
6632 {
6633 PopStyleVar(3);
6634 PopStyleColor();
6635 }
6636
6637 ImGuiWindow* child_window = g.CurrentWindow;
6638 child_window->ChildId = id;
6639
6640 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
6641 // While this is not really documented/defined, it seems that the expected thing to do.
6642 if (child_window->BeginCount == 1)
6643 parent_window->DC.CursorPos = child_window->Pos;
6644
6645 // Process navigation-in immediately so NavInit can run on first frame
6646 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
6647 const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
6648 if (g.ActiveId == temp_id_for_activation)
6649 ClearActiveID();
6650 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
6651 {
6652 FocusWindow(child_window);
6653 NavInitWindow(child_window, false);
6654 SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
6655 g.ActiveIdSource = g.NavInputSource;
6656 }
6657 return ret;
6658 }
6659
6660 void ImGui::EndChild()
6661 {
6662 ImGuiContext& g = *GImGui;
6663 ImGuiWindow* child_window = g.CurrentWindow;
6664
6665 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
6666 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
6667
6668 g.WithinEndChildID = child_window->ID;
6669 ImVec2 child_size = child_window->Size;
6670 End();
6671 if (child_window->BeginCount == 1)
6672 {
6673 ImGuiWindow* parent_window = g.CurrentWindow;
6674 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
6675 ItemSize(child_size);
6676 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
6677 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
6678 {
6679 ItemAdd(bb, child_window->ChildId);
6680 RenderNavCursor(bb, child_window->ChildId);
6681
6682 // 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)
6683 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
6684 RenderNavCursor(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavRenderCursorFlags_Compact);
6685 }
6686 else
6687 {
6688 // Not navigable into
6689 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
6690 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
6691 ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
6692
6693 // But when flattened we directly reach items, adjust active layer mask accordingly
6694 if (nav_flattened)
6695 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6696 }
6697 if (g.HoveredWindow == child_window)
6698 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6699 child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags;
6700 //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd()
6701 }
6702 else
6703 {
6704 SetLastItemDataForChildWindowItem(child_window, child_window->Rect());
6705 }
6706
6707 g.WithinEndChildID = backup_within_end_child_id;
6708 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6709 }
6710
6711 static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6712 {
6713 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
6714 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
6715 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6716 window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
6717 }
6718
6719 ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6720 {
6721 ImGuiContext& g = *GImGui;
6722 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6723 }
6724
6725 ImGuiWindow* ImGui::FindWindowByName(const char* name)
6726 {
6727 ImGuiID id = ImHashStr(name);
6728 return FindWindowByID(id);
6729 }
6730
6731 static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6732 {
6733 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6734 window->ViewportPos = main_viewport->Pos;
6735 if (settings->ViewportId)
6736 {
6737 window->ViewportId = settings->ViewportId;
6738 window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6739 }
6740 window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6741 if (settings->Size.x > 0 && settings->Size.y > 0)
6742 window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6743 window->Collapsed = settings->Collapsed;
6744 window->DockId = settings->DockId;
6745 window->DockOrder = settings->DockOrder;
6746 }
6747
6748 static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6749 {
6750 // Initial window state with e.g. default/arbitrary window position
6751 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6752 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6753 window->Pos = main_viewport->Pos + ImVec2(60, 60);
6754 window->Size = window->SizeFull = ImVec2(0, 0);
6755 window->ViewportPos = main_viewport->Pos;
6756 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6757
6758 if (settings != NULL)
6759 {
6760 SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6761 ApplyWindowSettings(window, settings);
6762 }
6763 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6764
6765 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6766 {
6767 window->AutoFitFramesX = window->AutoFitFramesY = 2;
6768 window->AutoFitOnlyGrows = false;
6769 }
6770 else
6771 {
6772 if (window->Size.x <= 0.0f)
6773 window->AutoFitFramesX = 2;
6774 if (window->Size.y <= 0.0f)
6775 window->AutoFitFramesY = 2;
6776 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6777 }
6778 }
6779
6780 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6781 {
6782 // Create window the first time
6783 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6784 ImGuiContext& g = *GImGui;
6785 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6786 window->Flags = flags;
6787 g.WindowsById.SetVoidPtr(window->ID, window);
6788
6789 ImGuiWindowSettings* settings = NULL;
6790 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6791 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6792 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6793
6794 InitOrLoadWindowSettings(window, settings);
6795
6796 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6797 g.Windows.push_front(window); // Quite slow but rare and only once
6798 else
6799 g.Windows.push_back(window);
6800
6801 return window;
6802 }
6803
6804 static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6805 {
6806 return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6807 }
6808
6809 static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6810 {
6811 return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6812 }
6813
6814 static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6815 {
6816 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6817 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6818 // Perhaps should tend further a neater test for this.
6819 ImGuiContext& g = *GImGui;
6820 ImVec2 size_min;
6821 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6822 {
6823 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6824 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6825 }
6826 else
6827 {
6828 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6829 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6830 }
6831
6832 // Reduce artifacts with very small windows
6833 ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6834 size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6835 return size_min;
6836 }
6837
6838 static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6839 {
6840 ImGuiContext& g = *GImGui;
6841 ImVec2 new_size = size_desired;
6842 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6843 {
6844 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6845 ImRect cr = g.NextWindowData.SizeConstraintRect;
6846 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6847 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6848 if (g.NextWindowData.SizeCallback)
6849 {
6850 ImGuiSizeCallbackData data;
6851 data.UserData = g.NextWindowData.SizeCallbackUserData;
6852 data.Pos = window->Pos;
6853 data.CurrentSize = window->SizeFull;
6854 data.DesiredSize = new_size;
6855 g.NextWindowData.SizeCallback(&data);
6856 new_size = data.DesiredSize;
6857 }
6858 new_size.x = IM_TRUNC(new_size.x);
6859 new_size.y = IM_TRUNC(new_size.y);
6860 }
6861
6862 // Minimum size
6863 ImVec2 size_min = CalcWindowMinSize(window);
6864 return ImMax(new_size, size_min);
6865 }
6866
6867 static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6868 {
6869 bool preserve_old_content_sizes = false;
6870 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6871 preserve_old_content_sizes = true;
6872 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6873 preserve_old_content_sizes = true;
6874 if (preserve_old_content_sizes)
6875 {
6876 *content_size_current = window->ContentSize;
6877 *content_size_ideal = window->ContentSizeIdeal;
6878 return;
6879 }
6880
6881 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6882 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6883 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6884 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6885 }
6886
6887 static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6888 {
6889 ImGuiContext& g = *GImGui;
6890 ImGuiStyle& style = g.Style;
6891 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6892 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6893 ImVec2 size_pad = window->WindowPadding * 2.0f;
6894 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6895
6896 // Determine maximum window size
6897 // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6898 ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6899 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6900 {
6901 if (!window->ViewportOwned)
6902 size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6903 const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6904 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6905 size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6906 }
6907
6908 if (window->Flags & ImGuiWindowFlags_Tooltip)
6909 {
6910 // Tooltip always resize (up to maximum size)
6911 return ImMin(size_desired, size_max);
6912 }
6913 else
6914 {
6915 ImVec2 size_min = CalcWindowMinSize(window);
6916 ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max);
6917
6918 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6919 // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6920 // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6921 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY)))
6922 size_auto_fit.y = window->SizeFull.y;
6923 else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX)))
6924 size_auto_fit.x = window->SizeFull.x;
6925
6926 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6927 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6928 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6929 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);
6930 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);
6931 if (will_have_scrollbar_x)
6932 size_auto_fit.y += style.ScrollbarSize;
6933 if (will_have_scrollbar_y)
6934 size_auto_fit.x += style.ScrollbarSize;
6935 return size_auto_fit;
6936 }
6937 }
6938
6939 ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6940 {
6941 ImVec2 size_contents_current;
6942 ImVec2 size_contents_ideal;
6943 CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6944 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6945 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6946 return size_final;
6947 }
6948
6949 static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6950 {
6951 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6952 return ImGuiCol_PopupBg;
6953 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6954 return ImGuiCol_ChildBg;
6955 return ImGuiCol_WindowBg;
6956 }
6957
6958 static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6959 {
6960 ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
6961 ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6962 ImVec2 size_expected = pos_max - pos_min;
6963 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6964 *out_pos = pos_min;
6965 if (corner_norm.x == 0.0f)
6966 out_pos->x -= (size_constrained.x - size_expected.x);
6967 if (corner_norm.y == 0.0f)
6968 out_pos->y -= (size_constrained.y - size_expected.y);
6969 *out_size = size_constrained;
6970 }
6971
6972 // Data for resizing from resize grip / corner
6973 struct ImGuiResizeGripDef
6974 {
6975 ImVec2 CornerPosN;
6976 ImVec2 InnerDir;
6977 int AngleMin12, AngleMax12;
6978 };
6979 static const ImGuiResizeGripDef resize_grip_def[4] =
6980 {
6981 { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
6982 { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
6983 { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
6984 { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
6985 };
6986
6987 // Data for resizing from borders
6988 struct ImGuiResizeBorderDef
6989 {
6990 ImVec2 InnerDir; // Normal toward inside
6991 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6992 float OuterAngle; // Angle toward outside
6993 };
6994 static const ImGuiResizeBorderDef resize_border_def[4] =
6995 {
6996 { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6997 { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6998 { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6999 { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
7000 };
7001
7002 static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
7003 {
7004 ImRect rect = window->Rect();
7005 if (thickness == 0.0f)
7006 rect.Max -= ImVec2(1, 1);
7007 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); }
7008 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); }
7009 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); }
7010 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); }
7011 IM_ASSERT(0);
7012 return ImRect();
7013 }
7014
7015 // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
7016 ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
7017 {
7018 IM_ASSERT(n >= 0 && n < 4);
7019 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
7020 id = ImHashStr("#RESIZE", 0, id);
7021 id = ImHashData(&n, sizeof(int), id);
7022 return id;
7023 }
7024
7025 // Borders (Left, Right, Up, Down)
7026 ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
7027 {
7028 IM_ASSERT(dir >= 0 && dir < 4);
7029 int n = (int)dir + 4;
7030 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
7031 id = ImHashStr("#RESIZE", 0, id);
7032 id = ImHashData(&n, sizeof(int), id);
7033 return id;
7034 }
7035
7036 // Handle resize for: Resize Grips, Borders, Gamepad
7037 // Return true when using auto-fit (double-click on resize grip)
7038 static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
7039 {
7040 ImGuiContext& g = *GImGui;
7041 ImGuiWindowFlags flags = window->Flags;
7042
7043 if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7044 return false;
7045 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
7046 return false;
7047 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
7048 return false;
7049
7050 int ret_auto_fit_mask = 0x00;
7051 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7052 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
7053 const float grip_hover_outer_size = g.WindowsBorderHoverPadding;
7054
7055 ImRect clamp_rect = visibility_rect;
7056 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
7057 if (window_move_from_title_bar)
7058 clamp_rect.Min.y -= window->TitleBarHeight;
7059
7060 ImVec2 pos_target(FLT_MAX, FLT_MAX);
7061 ImVec2 size_target(FLT_MAX, FLT_MAX);
7062
7063 // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
7064 // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
7065 // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
7066 // - 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.
7067 // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
7068 // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
7069 const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
7070 if (clip_with_viewport_rect)
7071 window->ClipRect = window->Viewport->GetMainRect();
7072
7073 // Resize grips and borders are on layer 1
7074 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7075
7076 // Manual resize grips
7077 PushID("#RESIZE");
7078 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7079 {
7080 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
7081 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
7082
7083 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
7084 bool hovered, held;
7085 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
7086 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
7087 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
7088 ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
7089 ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
7090 ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7091 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
7092 if (hovered || held)
7093 SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
7094
7095 if (held && g.IO.MouseDoubleClicked[0])
7096 {
7097 // Auto-fit when double-clicking
7098 size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
7099 ret_auto_fit_mask = 0x03; // Both axes
7100 ClearActiveID();
7101 }
7102 else if (held)
7103 {
7104 // Resize from any of the four corners
7105 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
7106 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);
7107 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);
7108 ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
7109 corner_target = ImClamp(corner_target, clamp_min, clamp_max);
7110 CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
7111 }
7112
7113 // Only lower-left grip is visible before hovering/activating
7114 if (resize_grip_n == 0 || held || hovered)
7115 resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
7116 }
7117
7118 int resize_border_mask = 0x00;
7119 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7120 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
7121 else
7122 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
7123 for (int border_n = 0; border_n < 4; border_n++)
7124 {
7125 if ((resize_border_mask & (1 << border_n)) == 0)
7126 continue;
7127 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7128 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
7129
7130 bool hovered, held;
7131 ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding);
7132 ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
7133 ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
7134 ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7135 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
7136 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
7137 hovered = false;
7138 if (hovered || held)
7139 SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
7140 if (held && g.IO.MouseDoubleClicked[0])
7141 {
7142 // Double-clicking bottom or right border auto-fit on this axis
7143 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
7144 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
7145 if (border_n == 1 || border_n == 3) // Right and bottom border
7146 {
7147 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
7148 ret_auto_fit_mask |= (1 << axis);
7149 hovered = held = false; // So border doesn't show highlighted at new position
7150 }
7151 ClearActiveID();
7152 }
7153 else if (held)
7154 {
7155 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
7156 // 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.
7157 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
7158 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
7159 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
7160 {
7161 g.WindowResizeBorderExpectedRect = border_rect;
7162 g.WindowResizeRelativeMode = false;
7163 }
7164 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
7165 g.WindowResizeRelativeMode = true;
7166
7167 const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
7168 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
7169 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above.
7170
7171 // Use absolute mode position
7172 ImVec2 border_target = window->Pos;
7173 border_target[axis] = border_target_abs_mode_for_axis;
7174
7175 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
7176 bool ignore_resize = false;
7177 if (g.WindowResizeRelativeMode)
7178 {
7179 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
7180 border_target[axis] = border_target_rel_mode_for_axis;
7181 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))
7182 ignore_resize = true;
7183 }
7184
7185 // Clamp, apply
7186 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);
7187 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
7188 border_target = ImClamp(border_target, clamp_min, clamp_max);
7189 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
7190 {
7191 ImGuiWindow* parent_window = window->ParentWindow;
7192 ImGuiWindowFlags parent_flags = parent_window->Flags;
7193 ImRect border_limit_rect = parent_window->InnerRect;
7194 border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
7195 if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
7196 border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
7197 if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
7198 border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
7199 }
7200 if (!ignore_resize)
7201 CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
7202 }
7203 if (hovered)
7204 *border_hovered = border_n;
7205 if (held)
7206 *border_held = border_n;
7207 }
7208 PopID();
7209
7210 // Restore nav layer
7211 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7212
7213 // Navigation resize (keyboard/gamepad)
7214 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
7215 // Not even sure the callback works here.
7216 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
7217 {
7218 ImVec2 nav_resize_dir;
7219 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
7220 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
7221 if (g.NavInputSource == ImGuiInputSource_Gamepad)
7222 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
7223 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
7224 {
7225 const float NAV_RESIZE_SPEED = 600.0f;
7226 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
7227 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
7228 g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
7229 g.NavWindowingToggleLayer = false;
7230 g.NavHighlightItemUnderNav = true;
7231 resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
7232 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
7233 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
7234 {
7235 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
7236 size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
7237 g.NavWindowingAccumDeltaSize -= accum_floored;
7238 }
7239 }
7240 }
7241
7242 // Apply back modified position/size to window
7243 const ImVec2 curr_pos = window->Pos;
7244 const ImVec2 curr_size = window->SizeFull;
7245 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
7246 window->Size.x = window->SizeFull.x = size_target.x;
7247 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
7248 window->Size.y = window->SizeFull.y = size_target.y;
7249 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
7250 window->Pos.x = ImTrunc(pos_target.x);
7251 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
7252 window->Pos.y = ImTrunc(pos_target.y);
7253 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)
7254 MarkIniSettingsDirty(window);
7255
7256 // Recalculate next expected border expected coordinates
7257 if (*border_held != -1)
7258 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding);
7259
7260 return ret_auto_fit_mask;
7261 }
7262
7263 static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
7264 {
7265 ImGuiContext& g = *GImGui;
7266 ImVec2 size_for_clamping = window->Size;
7267 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
7268 size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
7269 else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7270 size_for_clamping.y = window->TitleBarHeight;
7271 window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
7272 }
7273
7274 static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
7275 {
7276 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7277 const float rounding = window->WindowRounding;
7278 const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
7279 window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
7280 window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
7281 window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
7282 }
7283
7284 static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
7285 {
7286 ImGuiContext& g = *GImGui;
7287 const float border_size = window->WindowBorderSize;
7288 const ImU32 border_col = GetColorU32(ImGuiCol_Border);
7289 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
7290 window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
7291 else if (border_size > 0.0f)
7292 {
7293 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
7294 RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
7295 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
7296 RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
7297 }
7298 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
7299 {
7300 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
7301 const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
7302 RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
7303 }
7304 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7305 {
7306 float y = window->Pos.y + window->TitleBarHeight - 1;
7307 window->DrawList->AddLine(ImVec2(window->Pos.x + border_size * 0.5f, y), ImVec2(window->Pos.x + window->Size.x - border_size * 0.5f, y), border_col, g.Style.FrameBorderSize);
7308 }
7309 }
7310
7311 // Draw background and borders
7312 // Draw and handle scrollbars
7313 void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
7314 {
7315 ImGuiContext& g = *GImGui;
7316 ImGuiStyle& style = g.Style;
7317 ImGuiWindowFlags flags = window->Flags;
7318
7319 // Ensure that Scrollbar() doesn't read last frame's SkipItems
7320 IM_ASSERT(window->BeginCount == 0);
7321 window->SkipItems = false;
7322 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7323
7324 // Draw window + handle manual resize
7325 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
7326 const float window_rounding = window->WindowRounding;
7327 const float window_border_size = window->WindowBorderSize;
7328 if (window->Collapsed)
7329 {
7330 // Title bar only
7331 const float backup_border_size = style.FrameBorderSize;
7332 g.Style.FrameBorderSize = window->WindowBorderSize;
7333 ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
7334 if (window->ViewportOwned)
7335 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)
7336 RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
7337 g.Style.FrameBorderSize = backup_border_size;
7338 }
7339 else
7340 {
7341 // Window background
7342 if (!(flags & ImGuiWindowFlags_NoBackground))
7343 {
7344 bool is_docking_transparent_payload = false;
7345 if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
7346 if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
7347 is_docking_transparent_payload = true;
7348
7349 ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
7350 if (window->ViewportOwned)
7351 {
7352 bg_col |= IM_COL32_A_MASK; // No alpha
7353 if (is_docking_transparent_payload)
7354 window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
7355 }
7356 else
7357 {
7358 // Adjust alpha. For docking
7359 bool override_alpha = false;
7360 float alpha = 1.0f;
7361 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha)
7362 {
7363 alpha = g.NextWindowData.BgAlphaVal;
7364 override_alpha = true;
7365 }
7366 if (is_docking_transparent_payload)
7367 {
7368 alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
7369 override_alpha = true;
7370 }
7371 if (override_alpha)
7372 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
7373 }
7374
7375 // Render, for docked windows and host windows we ensure bg goes before decorations
7376 if (window->DockIsActive)
7377 window->DockNode->LastBgColor = bg_col;
7378 ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
7379 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7380 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
7381 bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
7382 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7383 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
7384 }
7385 if (window->DockIsActive)
7386 window->DockNode->IsBgDrawnThisFrame = true;
7387
7388 // Title bar
7389 // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
7390 // in order for their pos/size to be matching their undocking state.)
7391 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7392 {
7393 ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
7394 if (window->ViewportOwned)
7395 title_bar_col |= IM_COL32_A_MASK; // No alpha
7396 window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
7397 }
7398
7399 // Menu bar
7400 if (flags & ImGuiWindowFlags_MenuBar)
7401 {
7402 ImRect menu_bar_rect = window->MenuBarRect();
7403 menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
7404 window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
7405 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
7406 window->DrawList->AddLine(menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
7407 }
7408
7409 // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
7410 ImGuiDockNode* node = window->DockNode;
7411 if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
7412 {
7413 float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
7414 float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
7415 ImVec2 p = node->Pos;
7416 ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
7417 ImGuiID unhide_id = window->GetID("#UNHIDE");
7418 KeepAliveID(unhide_id);
7419 bool hovered, held;
7420 if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
7421 node->WantHiddenTabBarToggle = true;
7422 else if (held && IsMouseDragging(0))
7423 StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
7424
7425 // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
7426 ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
7427 window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
7428 }
7429
7430 // Scrollbars
7431 if (window->ScrollbarX)
7432 Scrollbar(ImGuiAxis_X);
7433 if (window->ScrollbarY)
7434 Scrollbar(ImGuiAxis_Y);
7435
7436 // Render resize grips (after their input handling so we don't have a frame of latency)
7437 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
7438 {
7439 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7440 {
7441 const ImU32 col = resize_grip_col[resize_grip_n];
7442 if ((col & IM_COL32_A_MASK) == 0)
7443 continue;
7444 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
7445 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
7446 const float border_inner = IM_ROUND(window_border_size * 0.5f);
7447 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner)));
7448 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size)));
7449 window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12);
7450 window->DrawList->PathFillConvex(col);
7451 }
7452 }
7453
7454 // Borders (for dock node host they will be rendered over after the tab bar)
7455 if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
7456 RenderWindowOuterBorders(window);
7457 }
7458 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7459 }
7460
7461 // When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
7462 // Render title text, collapse button, close button
7463 void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
7464 {
7465 ImGuiContext& g = *GImGui;
7466 ImGuiStyle& style = g.Style;
7467 ImGuiWindowFlags flags = window->Flags;
7468
7469 const bool has_close_button = (p_open != NULL);
7470 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
7471
7472 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
7473 // 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?
7474 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
7475 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
7476 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7477
7478 // Layout buttons
7479 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
7480 float pad_l = style.FramePadding.x;
7481 float pad_r = style.FramePadding.x;
7482 float button_sz = g.FontSize;
7483 ImVec2 close_button_pos;
7484 ImVec2 collapse_button_pos;
7485 if (has_close_button)
7486 {
7487 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7488 pad_r += button_sz + style.ItemInnerSpacing.x;
7489 }
7490 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
7491 {
7492 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7493 pad_r += button_sz + style.ItemInnerSpacing.x;
7494 }
7495 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
7496 {
7497 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
7498 pad_l += button_sz + style.ItemInnerSpacing.x;
7499 }
7500
7501 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
7502 if (has_collapse_button)
7503 if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
7504 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
7505
7506 // Close button
7507 if (has_close_button)
7508 {
7509 ImGuiItemFlags backup_item_flags = g.CurrentItemFlags;
7510 g.CurrentItemFlags |= ImGuiItemFlags_NoFocus;
7511 if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
7512 *p_open = false;
7513 g.CurrentItemFlags = backup_item_flags;
7514 }
7515
7516 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7517 g.CurrentItemFlags = item_flags_backup;
7518
7519 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
7520 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
7521 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
7522 const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
7523
7524 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
7525 // while uncentered title text will still reach edges correctly.
7526 if (pad_l > style.FramePadding.x)
7527 pad_l += g.Style.ItemInnerSpacing.x;
7528 if (pad_r > style.FramePadding.x)
7529 pad_r += g.Style.ItemInnerSpacing.x;
7530 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
7531 {
7532 float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
7533 float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
7534 pad_l = ImMax(pad_l, pad_extend * centerness);
7535 pad_r = ImMax(pad_r, pad_extend * centerness);
7536 }
7537
7538 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);
7539 ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
7540 if (flags & ImGuiWindowFlags_UnsavedDocument)
7541 {
7542 ImVec2 marker_pos;
7543 marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
7544 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
7545 if (marker_pos.x > layout_r.Min.x)
7546 {
7547 RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
7548 clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
7549 }
7550 }
7551 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7552 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7553 RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
7554 }
7555
7556 void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
7557 {
7558 window->ParentWindow = parent_window;
7559 window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
7560 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
7561 {
7562 window->RootWindowDockTree = parent_window->RootWindowDockTree;
7563 if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
7564 window->RootWindow = parent_window->RootWindow;
7565 }
7566 if (parent_window && (flags & ImGuiWindowFlags_Popup))
7567 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
7568 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
7569 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
7570 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
7571 {
7572 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
7573 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
7574 }
7575 }
7576
7577 // [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
7578 // This is designed as a toy/test-bed for
7579 void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
7580 {
7581 ImGuiContext& g = *GImGui;
7582 window->SkipRefresh = false;
7583 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
7584 return;
7585 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
7586 {
7587 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
7588 if (window->Appearing) // If currently appearing
7589 return;
7590 if (window->Hidden) // If was hidden (previous frame)
7591 return;
7592 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow)
7593 if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, window))
7594 return;
7595 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow)
7596 if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(g.NavWindow->RootWindow, window))
7597 return;
7598 window->DrawList = NULL;
7599 window->SkipRefresh = true;
7600 }
7601 }
7602
7603 static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
7604 {
7605 window->Active = true;
7606 for (ImGuiWindow* child : window->DC.ChildWindows)
7607 if (!child->Hidden)
7608 {
7609 child->Active = child->SkipRefresh = true;
7610 SetWindowActiveForSkipRefresh(child);
7611 }
7612 }
7613
7614 // Push a new Dear ImGui window to add widgets to.
7615 // - 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.
7616 // - Begin/End can be called multiple times during the frame with the same window name to append content.
7617 // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
7618 // 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.
7619 // - 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.
7620 // - 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.
7621 bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
7622 {
7623 ImGuiContext& g = *GImGui;
7624 const ImGuiStyle& style = g.Style;
7625 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
7626 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
7627 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
7628
7629 // Find or create
7630 ImGuiWindow* window = FindWindowByName(name);
7631 const bool window_just_created = (window == NULL);
7632 if (window_just_created)
7633 window = CreateNewWindow(name, flags);
7634
7635 // [DEBUG] Debug break requested by user
7636 if (g.DebugBreakInWindow == window->ID)
7637 IM_DEBUG_BREAK();
7638
7639 // Automatically disable manual moving/resizing when NoInputs is set
7640 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
7641 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
7642
7643 const int current_frame = g.FrameCount;
7644 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
7645 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
7646
7647 // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
7648 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
7649 if (flags & ImGuiWindowFlags_Popup)
7650 {
7651 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7652 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
7653 window_just_activated_by_user |= (window != popup_ref.Window);
7654 }
7655
7656 // Update Flags, LastFrameActive, BeginOrderXXX fields
7657 const bool window_was_appearing = window->Appearing;
7658 if (first_begin_of_the_frame)
7659 {
7660 UpdateWindowInFocusOrderList(window, window_just_created, flags);
7661 window->Appearing = window_just_activated_by_user;
7662 if (window->Appearing)
7663 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7664 window->FlagsPreviousFrame = window->Flags;
7665 window->Flags = (ImGuiWindowFlags)flags;
7666 window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7667 window->LastFrameActive = current_frame;
7668 window->LastTimeActive = (float)g.Time;
7669 window->BeginOrderWithinParent = 0;
7670 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7671 }
7672 else
7673 {
7674 flags = window->Flags;
7675 }
7676
7677 // Docking
7678 // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7679 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7680 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasDock)
7681 SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
7682 if (first_begin_of_the_frame)
7683 {
7684 bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7685 bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7686 bool dock_node_was_visible = window->DockNodeIsVisible;
7687 bool dock_tab_was_visible = window->DockTabIsVisible;
7688 if (has_dock_node || new_auto_dock_node)
7689 {
7690 BeginDocked(window, p_open);
7691 flags = window->Flags;
7692 if (window->DockIsActive)
7693 {
7694 IM_ASSERT(window->DockNode != NULL);
7695 g.NextWindowData.HasFlags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7696 }
7697
7698 // Amend the Appearing flag
7699 if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7700 {
7701 window->Appearing = true;
7702 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7703 }
7704 }
7705 else
7706 {
7707 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7708 }
7709 }
7710
7711 // 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
7712 ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7713 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7714 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7715
7716 // We allow window memory to be compacted so recreate the base stack when needed.
7717 if (window->IDStack.Size == 0)
7718 window->IDStack.push_back(window->ID);
7719
7720 // Add to stack
7721 g.CurrentWindow = window;
7722 g.CurrentWindowStack.resize(g.CurrentWindowStack.Size + 1);
7723 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7724 window_stack_data.Window = window;
7725 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7726 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7727 window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f;
7728 ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin);
7729 g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
7730 if (flags & ImGuiWindowFlags_ChildMenu)
7731 g.BeginMenuDepth++;
7732
7733 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7734 if (first_begin_of_the_frame)
7735 {
7736 UpdateWindowParentAndRootLinks(window, flags, parent_window);
7737 window->ParentWindowInBeginStack = parent_window_in_stack;
7738
7739 // Focus route
7740 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7741 // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7742 window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7743 if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7744 if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7745 window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7746
7747 // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7748 if (window->WindowClass.FocusRouteParentWindowId != 0)
7749 {
7750 window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7751 IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7752 }
7753
7754 // Inherit SetWindowFontScale() from parent until we fix this system...
7755 window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f;
7756 }
7757
7758 // Add to focus scope stack
7759 PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7760 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7761
7762 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7763 if (flags & ImGuiWindowFlags_Popup)
7764 {
7765 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7766 popup_ref.Window = window;
7767 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7768 g.BeginPopupStack.push_back(popup_ref);
7769 window->PopupId = popup_ref.PopupId;
7770 }
7771
7772 // Process SetNextWindow***() calls
7773 // (FIXME: Consider splitting the HasXXX flags into X/Y components)
7774 bool window_pos_set_by_api = false;
7775 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7776 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos)
7777 {
7778 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7779 if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7780 {
7781 // May be processed on the next frame if this is our first frame and we are measuring size
7782 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7783 window->SetWindowPosVal = g.NextWindowData.PosVal;
7784 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7785 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7786 }
7787 else
7788 {
7789 SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7790 }
7791 }
7792 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize)
7793 {
7794 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7795 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7796 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7797 g.NextWindowData.SizeVal.x = window->SizeFull.x;
7798 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7799 g.NextWindowData.SizeVal.y = window->SizeFull.y;
7800 SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7801 }
7802 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll)
7803 {
7804 if (g.NextWindowData.ScrollVal.x >= 0.0f)
7805 {
7806 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7807 window->ScrollTargetCenterRatio.x = 0.0f;
7808 }
7809 if (g.NextWindowData.ScrollVal.y >= 0.0f)
7810 {
7811 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7812 window->ScrollTargetCenterRatio.y = 0.0f;
7813 }
7814 }
7815 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize)
7816 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7817 else if (first_begin_of_the_frame)
7818 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7819 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowClass)
7820 window->WindowClass = g.NextWindowData.WindowClass;
7821 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed)
7822 SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7823 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus)
7824 FocusWindow(window);
7825 if (window->Appearing)
7826 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7827
7828 // [EXPERIMENTAL] Skip Refresh mode
7829 UpdateWindowSkipRefresh(window);
7830
7831 // Nested root windows (typically tooltips) override disabled state
7832 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7833 BeginDisabledOverrideReenable();
7834
7835 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7836 g.CurrentWindow = NULL;
7837
7838 // When reusing window again multiple times a frame, just append content (don't need to setup again)
7839 if (first_begin_of_the_frame && !window->SkipRefresh)
7840 {
7841 // Initialize
7842 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7843 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7844 window->Active = true;
7845 window->HasCloseButton = (p_open != NULL);
7846 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7847 window->IDStack.resize(1);
7848 window->DrawList->_ResetForNewFrame();
7849 window->DC.CurrentTableIdx = -1;
7850 if (flags & ImGuiWindowFlags_DockNodeHost)
7851 {
7852 window->DrawList->ChannelsSplit(2);
7853 window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7854 }
7855
7856 // Restore buffer capacity when woken from a compacted state, to avoid
7857 if (window->MemoryCompacted)
7858 GcAwakeTransientWindowBuffers(window);
7859
7860 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7861 // 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.
7862 bool window_title_visible_elsewhere = false;
7863 if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7864 window_title_visible_elsewhere = true;
7865 else if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
7866 window_title_visible_elsewhere = true;
7867 else if (flags & ImGuiWindowFlags_ChildMenu)
7868 window_title_visible_elsewhere = true;
7869 if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7870 {
7871 size_t buf_len = (size_t)window->NameBufLen;
7872 window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7873 window->NameBufLen = (int)buf_len;
7874 }
7875
7876 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7877
7878 // Update contents size from last frame for auto-fitting (or use explicit size)
7879 CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7880
7881 // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7882 // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7883 // it has a single usage before this code block and may be set below before it is finally checked.
7884 if (window->HiddenFramesCanSkipItems > 0)
7885 window->HiddenFramesCanSkipItems--;
7886 if (window->HiddenFramesCannotSkipItems > 0)
7887 window->HiddenFramesCannotSkipItems--;
7888 if (window->HiddenFramesForRenderOnly > 0)
7889 window->HiddenFramesForRenderOnly--;
7890
7891 // Hide new windows for one frame until they calculate their size
7892 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7893 window->HiddenFramesCannotSkipItems = 1;
7894
7895 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7896 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7897 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7898 {
7899 window->HiddenFramesCannotSkipItems = 1;
7900 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7901 {
7902 if (!window_size_x_set_by_api)
7903 window->Size.x = window->SizeFull.x = 0.f;
7904 if (!window_size_y_set_by_api)
7905 window->Size.y = window->SizeFull.y = 0.f;
7906 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7907 }
7908 }
7909
7910 // SELECT VIEWPORT
7911 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7912
7913 WindowSelectViewport(window);
7914 SetCurrentViewport(window, window->Viewport);
7915 SetCurrentWindow(window);
7916 flags = window->Flags;
7917
7918 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7919 // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7920
7921 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7922 window->WindowBorderSize = style.ChildBorderSize;
7923 else
7924 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7925 window->WindowPadding = style.WindowPadding;
7926 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7927 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7928
7929 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7930 window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7931 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7932 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7933 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7934 window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window.
7935
7936 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7937 // Those flags will be altered further down in the function depending on more conditions.
7938 bool use_current_size_for_scrollbar_x = window_just_created;
7939 bool use_current_size_for_scrollbar_y = window_just_created;
7940 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7941 use_current_size_for_scrollbar_x = true;
7942 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7943 use_current_size_for_scrollbar_y = true;
7944
7945 // Collapse window by double-clicking on title bar
7946 // 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
7947 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7948 {
7949 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
7950 // so verify that we don't have items over the title bar.
7951 ImRect title_bar_rect = window->TitleBarRect();
7952 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7953 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7954 window->WantCollapseToggle = true;
7955 if (window->WantCollapseToggle)
7956 {
7957 window->Collapsed = !window->Collapsed;
7958 if (!window->Collapsed)
7959 use_current_size_for_scrollbar_y = true;
7960 MarkIniSettingsDirty(window);
7961 }
7962 }
7963 else
7964 {
7965 window->Collapsed = false;
7966 }
7967 window->WantCollapseToggle = false;
7968
7969 // SIZE
7970
7971 // Outer Decoration Sizes
7972 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7973 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7974 window->DecoOuterSizeX1 = 0.0f;
7975 window->DecoOuterSizeX2 = 0.0f;
7976 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7977 window->DecoOuterSizeY2 = 0.0f;
7978 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7979
7980 // Calculate auto-fit size, handle automatic resize
7981 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7982 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7983 {
7984 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7985 if (!window_size_x_set_by_api)
7986 {
7987 window->SizeFull.x = size_auto_fit.x;
7988 use_current_size_for_scrollbar_x = true;
7989 }
7990 if (!window_size_y_set_by_api)
7991 {
7992 window->SizeFull.y = size_auto_fit.y;
7993 use_current_size_for_scrollbar_y = true;
7994 }
7995 }
7996 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7997 {
7998 // Auto-fit may only grow window during the first few frames
7999 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
8000 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
8001 {
8002 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
8003 use_current_size_for_scrollbar_x = true;
8004 }
8005 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
8006 {
8007 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
8008 use_current_size_for_scrollbar_y = true;
8009 }
8010 if (!window->Collapsed)
8011 MarkIniSettingsDirty(window);
8012 }
8013
8014 // Apply minimum/maximum window size constraints and final size
8015 window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
8016 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
8017
8018 // POSITION
8019
8020 // Popup latch its initial position, will position itself when it appears next frame
8021 if (window_just_activated_by_user)
8022 {
8023 window->AutoPosLastDirection = ImGuiDir_None;
8024 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
8025 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
8026 }
8027
8028 // Position child window
8029 if (flags & ImGuiWindowFlags_ChildWindow)
8030 {
8031 IM_ASSERT(parent_window && parent_window->Active);
8032 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
8033 parent_window->DC.ChildWindows.push_back(window);
8034 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
8035 window->Pos = parent_window->DC.CursorPos;
8036 }
8037
8038 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
8039 if (window_pos_with_pivot)
8040 SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
8041 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
8042 window->Pos = FindBestWindowPosForPopup(window);
8043 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
8044 window->Pos = FindBestWindowPosForPopup(window);
8045 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
8046 window->Pos = FindBestWindowPosForPopup(window);
8047
8048 // Late create viewport if we don't fit within our current host viewport.
8049 if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
8050 if (!window->Viewport->GetMainRect().Contains(window->Rect()))
8051 {
8052 // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
8053 //ImGuiViewport* old_viewport = window->Viewport;
8054 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
8055
8056 // FIXME-DPI
8057 //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
8058 SetCurrentViewport(window, window->Viewport);
8059 SetCurrentWindow(window);
8060 }
8061
8062 if (window->ViewportOwned)
8063 WindowSyncOwnedViewport(window, parent_window_in_stack);
8064
8065 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
8066 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
8067 ImRect viewport_rect(window->Viewport->GetMainRect());
8068 ImRect viewport_work_rect(window->Viewport->GetWorkRect());
8069 ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
8070 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
8071
8072 // Clamp position/size so window stays visible within its viewport or monitor
8073 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
8074 // FIXME: Similar to code in GetWindowAllowedExtentRect()
8075 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
8076 {
8077 if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
8078 {
8079 ClampWindowPos(window, visibility_rect);
8080 }
8081 else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
8082 {
8083 if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
8084 {
8085 // While moving windows we allow them to straddle monitors (#7299, #3071)
8086 visibility_rect = g.PlatformMonitorsFullWorkRect;
8087 }
8088 else
8089 {
8090 // When not moving ensure visible in its monitor
8091 // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
8092 const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
8093 visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
8094 }
8095 visibility_rect.Expand(-visibility_padding);
8096 ClampWindowPos(window, visibility_rect);
8097 }
8098 }
8099 window->Pos = ImTrunc(window->Pos);
8100
8101 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
8102 // Large values tend to lead to variety of artifacts and are not recommended.
8103 if (window->ViewportOwned || window->DockIsActive)
8104 window->WindowRounding = 0.0f;
8105 else
8106 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
8107
8108 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
8109 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
8110 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
8111
8112 // Apply window focus (new and reactivated windows are moved to front)
8113 bool want_focus = false;
8114 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
8115 {
8116 if (flags & ImGuiWindowFlags_Popup)
8117 want_focus = true;
8118 else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
8119 want_focus = true;
8120 }
8121
8122 // [Test Engine] Register whole window in the item system (before submitting further decorations)
8123 #ifdef IMGUI_ENABLE_TEST_ENGINE
8124 if (g.TestEngineHookItems)
8125 {
8126 IM_ASSERT(window->IDStack.Size == 1);
8127 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
8128 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8129 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
8130 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
8131 window->IDStack.Size = 1;
8132 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8133
8134 }
8135 #endif
8136
8137 // Decide if we are going to handle borders and resize grips
8138 // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815)
8139 // Whenever we add support for full decorated child windows we will likely make this logic more general.
8140 bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
8141 if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems)
8142 handle_borders_and_resize_grips = false;
8143
8144 // Handle manual resize: Resize Grips, Borders, Gamepad
8145 int border_hovered = -1, border_held = -1;
8146 ImU32 resize_grip_col[4] = {};
8147 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.
8148 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
8149 if (handle_borders_and_resize_grips && !window->Collapsed)
8150 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
8151 {
8152 if (auto_fit_mask & (1 << ImGuiAxis_X))
8153 use_current_size_for_scrollbar_x = true;
8154 if (auto_fit_mask & (1 << ImGuiAxis_Y))
8155 use_current_size_for_scrollbar_y = true;
8156 }
8157 window->ResizeBorderHovered = (signed char)border_hovered;
8158 window->ResizeBorderHeld = (signed char)border_held;
8159
8160 // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
8161 if (window->ViewportOwned)
8162 {
8163 if (!window->Viewport->PlatformRequestMove)
8164 window->Viewport->Pos = window->Pos;
8165 if (!window->Viewport->PlatformRequestResize)
8166 window->Viewport->Size = window->Size;
8167 window->Viewport->UpdateWorkRect();
8168 viewport_rect = window->Viewport->GetMainRect();
8169 }
8170
8171 // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
8172 window->ViewportPos = window->Viewport->Pos;
8173
8174 // SCROLLBAR VISIBILITY
8175
8176 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
8177 if (!window->Collapsed)
8178 {
8179 // When reading the current size we need to read it after size constraints have been applied.
8180 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
8181 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
8182 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
8183 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
8184 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
8185 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
8186 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
8187 bool scrollbar_x_prev = window->ScrollbarX;
8188 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
8189 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
8190 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));
8191
8192 // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
8193 // (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.
8194 // 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)
8195 window->ScrollbarXStabilizeToggledHistory <<= 1;
8196 window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00;
8197 const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history.
8198 if (scrollbar_x_stabilize)
8199 window->ScrollbarX = true;
8200 //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled)
8201 // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name);
8202 window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize;
8203
8204 if (window->ScrollbarX && !window->ScrollbarY)
8205 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
8206 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
8207
8208 // Amend the partially filled window->DecorationXXX values.
8209 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
8210 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
8211 }
8212
8213 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
8214 // Update various regions. Variables they depend on should be set above in this function.
8215 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
8216
8217 // Outer rectangle
8218 // Not affected by window border size. Used by:
8219 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
8220 // - Begin() initial clipping rect for drawing window background and borders.
8221 // - Begin() clipping whole child
8222 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
8223 const ImRect outer_rect = window->Rect();
8224 const ImRect title_bar_rect = window->TitleBarRect();
8225 window->OuterRectClipped = outer_rect;
8226 if (window->DockIsActive)
8227 window->OuterRectClipped.Min.y += window->TitleBarHeight;
8228 window->OuterRectClipped.ClipWith(host_rect);
8229
8230 // Inner rectangle
8231 // Not affected by window border size. Used by:
8232 // - InnerClipRect
8233 // - ScrollToRectEx()
8234 // - NavUpdatePageUpPageDown()
8235 // - Scrollbar()
8236 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
8237 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
8238 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
8239 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
8240
8241 // Inner clipping rectangle.
8242 // - Extend a outside of normal work region up to borders.
8243 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
8244 // - It also makes clipped items be more noticeable.
8245 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
8246 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
8247 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
8248 // Affected by window/frame border size. Used by:
8249 // - Begin() initial clip rect
8250 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
8251
8252 // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner.
8253 // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize,
8254 // 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).
8255 window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f);
8256 window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size * 0.5f);
8257 window->InnerClipRect.Max.x = ImFloor(window->InnerRect.Max.x - window->WindowBorderSize * 0.5f);
8258 window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
8259 window->InnerClipRect.ClipWithFull(host_rect);
8260
8261 // SCROLLING
8262
8263 // Lock down maximum scrolling
8264 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
8265 // for right/bottom aligned items without creating a scrollbar.
8266 window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
8267 window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
8268
8269 // Apply scrolling
8270 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
8271 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
8272 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
8273
8274 // DRAWING
8275
8276 // Setup draw list and outer clipping rectangle
8277 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
8278 window->DrawList->PushTexture(g.Font->ContainerAtlas->TexRef);
8279 PushClipRect(host_rect.Min, host_rect.Max, false);
8280
8281 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
8282 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
8283 // 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)
8284 const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
8285 if (is_undocked_or_docked_visible)
8286 {
8287 bool render_decorations_in_parent = false;
8288 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
8289 {
8290 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
8291 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
8292 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
8293 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
8294 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
8295 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
8296 render_decorations_in_parent = true;
8297 }
8298 if (render_decorations_in_parent)
8299 window->DrawList = parent_window->DrawList;
8300
8301 // Handle title bar, scrollbar, resize grips and resize borders
8302 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
8303 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)));
8304 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
8305
8306 if (render_decorations_in_parent)
8307 window->DrawList = &window->DrawListInst;
8308 }
8309
8310 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
8311
8312 // Work rectangle.
8313 // Affected by window padding and border size. Used by:
8314 // - Columns() for right-most edge
8315 // - TreeNode(), CollapsingHeader() for right-most edge
8316 // - BeginTabBar() for right-most edge
8317 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
8318 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
8319 const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
8320 const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
8321 window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
8322 window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
8323 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
8324 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
8325 window->ParentWorkRect = window->WorkRect;
8326
8327 // [LEGACY] Content Region
8328 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
8329 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
8330 // Used by:
8331 // - Mouse wheel scrolling + many other things
8332 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
8333 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
8334 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)));
8335 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)));
8336
8337 // Setup drawing context
8338 // (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.)
8339 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
8340 window->DC.GroupOffset.x = 0.0f;
8341 window->DC.ColumnsOffset.x = 0.0f;
8342
8343 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
8344 // 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.
8345 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
8346 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
8347 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
8348 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
8349 window->DC.CursorPos = window->DC.CursorStartPos;
8350 window->DC.CursorPosPrevLine = window->DC.CursorPos;
8351 window->DC.CursorMaxPos = window->DC.CursorStartPos;
8352 window->DC.IdealMaxPos = window->DC.CursorStartPos;
8353 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
8354 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
8355 window->DC.IsSameLine = window->DC.IsSetPos = false;
8356
8357 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8358 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
8359 window->DC.NavLayersActiveMaskNext = 0x00;
8360 window->DC.NavIsScrollPushableX = true;
8361 window->DC.NavHideHighlightOneFrame = false;
8362 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
8363
8364 window->DC.MenuBarAppending = false;
8365 window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
8366 window->DC.TreeDepth = 0;
8367 window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00;
8368 window->DC.ChildWindows.resize(0);
8369 window->DC.StateStorage = &window->StateStorage;
8370 window->DC.CurrentColumns = NULL;
8371 window->DC.LayoutType = ImGuiLayoutType_Vertical;
8372 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
8373
8374 // Default item width. Make it proportional to window size if window manually resizes
8375 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
8376 window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
8377 else
8378 window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
8379 window->DC.ItemWidth = window->ItemWidthDefault;
8380 window->DC.TextWrapPos = -1.0f; // disabled
8381 window->DC.ItemWidthStack.resize(0);
8382 window->DC.TextWrapPosStack.resize(0);
8383 if (flags & ImGuiWindowFlags_Modal)
8384 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
8385
8386 if (window->AutoFitFramesX > 0)
8387 window->AutoFitFramesX--;
8388 if (window->AutoFitFramesY > 0)
8389 window->AutoFitFramesY--;
8390
8391 // Clear SetNextWindowXXX data (can aim to move this higher in the function)
8392 g.NextWindowData.ClearFlags();
8393
8394 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
8395 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
8396 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
8397 // - Position window behind the modal that is not a begin-parent of this window.
8398 if (want_focus)
8399 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
8400 if (want_focus && window == g.NavWindow)
8401 NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
8402
8403 // Close requested by platform window (apply to all windows in this viewport)
8404 // FIXME: Investigate removing the 'window->Viewport != GetMainViewport()' test, which seems superfluous.
8405 if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
8406 if (window->DockNode == NULL || (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockSpace) == 0)
8407 {
8408 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
8409 *p_open = false;
8410 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.
8411 }
8412
8413 // Pressing CTRL+C copy window content into the clipboard
8414 // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
8415 // [EXPERIMENTAL] Text outputs has many issues.
8416 if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
8417 if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C))
8418 LogToClipboard(0);
8419
8420 // Title bar
8421 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
8422 RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
8423 else if (!(flags & ImGuiWindowFlags_NoTitleBar) && window->DockIsActive)
8424 LogText("%.*s\n", (int)(FindRenderedTextEnd(window->Name) - window->Name), window->Name);
8425
8426 // Clear hit test shape every frame
8427 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
8428
8429 if (flags & ImGuiWindowFlags_Tooltip)
8430 g.TooltipPreviousWindow = window;
8431
8432 if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
8433 {
8434 // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
8435 // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
8436 if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
8437 BeginDockableDragDropSource(window);
8438
8439 // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
8440 if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
8441 if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
8442 if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
8443 BeginDockableDragDropTarget(window);
8444 }
8445
8446 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
8447 // This is useful to allow creating context menus on title bar only, etc.
8448 window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None;
8449 window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
8450 SetLastItemDataForWindow(window, title_bar_rect);
8451
8452 // [DEBUG]
8453 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8454 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
8455 DebugLocateItemResolveWithLastItem();
8456 #endif
8457
8458 // [Test Engine] Register title bar / tab with MoveId.
8459 #ifdef IMGUI_ENABLE_TEST_ENGINE
8460 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
8461 {
8462 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8463 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
8464 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8465 }
8466 #endif
8467 }
8468 else
8469 {
8470 // Skip refresh always mark active
8471 if (window->SkipRefresh)
8472 SetWindowActiveForSkipRefresh(window);
8473
8474 // Append
8475 SetCurrentViewport(window, window->Viewport);
8476 SetCurrentWindow(window);
8477 g.NextWindowData.ClearFlags();
8478 SetLastItemDataForWindow(window, window->TitleBarRect());
8479 }
8480
8481 if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
8482 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
8483
8484 // 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)
8485 window->WriteAccessed = false;
8486 window->BeginCount++;
8487
8488 // Update visibility
8489 if (first_begin_of_the_frame && !window->SkipRefresh)
8490 {
8491 // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
8492 // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
8493 // This is analogous to regular windows being hidden from one frame.
8494 // 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.
8495 if (window->DockIsActive && !window->DockTabIsVisible)
8496 {
8497 if (window->LastFrameJustFocused == g.FrameCount)
8498 window->HiddenFramesCannotSkipItems = 1;
8499 else
8500 window->HiddenFramesCanSkipItems = 1;
8501 }
8502
8503 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
8504 {
8505 // Child window can be out of sight and have "negative" clip windows.
8506 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
8507 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
8508 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
8509 if (!g.LogEnabled && !nav_request)
8510 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
8511 {
8512 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
8513 window->HiddenFramesCannotSkipItems = 1;
8514 else
8515 window->HiddenFramesCanSkipItems = 1;
8516 }
8517
8518 // Hide along with parent or if parent is collapsed
8519 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
8520 window->HiddenFramesCanSkipItems = 1;
8521 if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0)
8522 window->HiddenFramesCannotSkipItems = 1;
8523 }
8524
8525 // 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)
8526 if (style.Alpha <= 0.0f)
8527 window->HiddenFramesCanSkipItems = 1;
8528
8529 // Update the Hidden flag
8530 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
8531 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
8532
8533 // Disable inputs for requested number of frames
8534 if (window->DisableInputsFrames > 0)
8535 {
8536 window->DisableInputsFrames--;
8537 window->Flags |= ImGuiWindowFlags_NoInputs;
8538 }
8539
8540 // Update the SkipItems flag, used to early out of all items functions (no layout required)
8541 bool skip_items = false;
8542 if (window->Collapsed || !window->Active || hidden_regular)
8543 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
8544 skip_items = true;
8545 window->SkipItems = skip_items;
8546
8547 // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
8548 if (window->SkipItems)
8549 window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
8550
8551 // Sanity check: there are two spots which can set Appearing = true
8552 // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
8553 // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
8554 if (window->SkipItems && !window->Appearing)
8555 IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
8556 }
8557 else if (first_begin_of_the_frame)
8558 {
8559 // Skip refresh mode
8560 window->SkipItems = true;
8561 }
8562
8563 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
8564 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
8565 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8566 if (!window->IsFallbackWindow)
8567 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
8568 {
8569 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
8570 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
8571 return false;
8572 }
8573 #endif
8574
8575 return !window->SkipItems;
8576 }
8577
8578 void ImGui::End()
8579 {
8580 ImGuiContext& g = *GImGui;
8581 ImGuiWindow* window = g.CurrentWindow;
8582
8583 // Error checking: verify that user hasn't called End() too many times!
8584 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
8585 {
8586 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
8587 return;
8588 }
8589 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
8590
8591 // Error checking: verify that user doesn't directly call End() on a child window.
8592 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
8593 IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!");
8594
8595 // Close anything that is open
8596 if (window->DC.CurrentColumns)
8597 EndColumns();
8598 if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) // Pop inner window clip rectangle
8599 PopClipRect();
8600 PopFocusScope();
8601 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
8602 EndDisabledOverrideReenable();
8603
8604 if (window->SkipRefresh)
8605 {
8606 IM_ASSERT(window->DrawList == NULL);
8607 window->DrawList = &window->DrawListInst;
8608 }
8609
8610 // Stop logging
8611 if (g.LogWindow == window) // FIXME: add more options for scope of logging
8612 LogFinish();
8613
8614 if (window->DC.IsSetPos)
8615 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
8616
8617 // Docking: report contents sizes to parent to allow for auto-resize
8618 if (window->DockNode && window->DockTabIsVisible)
8619 if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
8620 host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
8621
8622 // Pop from window stack
8623 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
8624 if (window->Flags & ImGuiWindowFlags_ChildMenu)
8625 g.BeginMenuDepth--;
8626 if (window->Flags & ImGuiWindowFlags_Popup)
8627 g.BeginPopupStack.pop_back();
8628
8629 // Error handling, state recovery
8630 if (g.IO.ConfigErrorRecovery)
8631 ErrorRecoveryTryToRecoverWindowState(&window_stack_data.StackSizesInBegin);
8632
8633 g.CurrentWindowStack.pop_back();
8634 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
8635 if (g.CurrentWindow)
8636 SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
8637 }
8638
8639 void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8640 {
8641 ImGuiContext& g = *GImGui;
8642 ImGuiItemFlags item_flags = g.CurrentItemFlags;
8643 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8644 if (enabled)
8645 item_flags |= option;
8646 else
8647 item_flags &= ~option;
8648 g.CurrentItemFlags = item_flags;
8649 g.ItemFlagsStack.push_back(item_flags);
8650 }
8651
8652 void ImGui::PopItemFlag()
8653 {
8654 ImGuiContext& g = *GImGui;
8655 if (g.ItemFlagsStack.Size <= 1)
8656 {
8657 IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!");
8658 return;
8659 }
8660 g.ItemFlagsStack.pop_back();
8661 g.CurrentItemFlags = g.ItemFlagsStack.back();
8662 }
8663
8664 // BeginDisabled()/EndDisabled()
8665 // - 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)
8666 // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8667 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8668 // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
8669 // (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)
8670 // - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
8671 void ImGui::BeginDisabled(bool disabled)
8672 {
8673 ImGuiContext& g = *GImGui;
8674 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8675 if (!was_disabled && disabled)
8676 {
8677 g.DisabledAlphaBackup = g.Style.Alpha;
8678 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8679 }
8680 if (was_disabled || disabled)
8681 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8682 g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8683 g.DisabledStackSize++;
8684 }
8685
8686 void ImGui::EndDisabled()
8687 {
8688 ImGuiContext& g = *GImGui;
8689 if (g.DisabledStackSize <= 0)
8690 {
8691 IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!");
8692 return;
8693 }
8694 g.DisabledStackSize--;
8695 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8696 //PopItemFlag();
8697 g.ItemFlagsStack.pop_back();
8698 g.CurrentItemFlags = g.ItemFlagsStack.back();
8699 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8700 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8701 }
8702
8703 // Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8704 // Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8705 // The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8706 void ImGui::BeginDisabledOverrideReenable()
8707 {
8708 ImGuiContext& g = *GImGui;
8709 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8710 g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha;
8711 g.Style.Alpha = g.DisabledAlphaBackup;
8712 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8713 g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8714 g.DisabledStackSize++;
8715 }
8716
8717 void ImGui::EndDisabledOverrideReenable()
8718 {
8719 ImGuiContext& g = *GImGui;
8720 g.DisabledStackSize--;
8721 IM_ASSERT(g.DisabledStackSize > 0);
8722 g.ItemFlagsStack.pop_back();
8723 g.CurrentItemFlags = g.ItemFlagsStack.back();
8724 g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup;
8725 }
8726
8727 void ImGui::PushTextWrapPos(float wrap_pos_x)
8728 {
8729 ImGuiContext& g = *GImGui;
8730 ImGuiWindow* window = g.CurrentWindow;
8731 window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8732 window->DC.TextWrapPos = wrap_pos_x;
8733 }
8734
8735 void ImGui::PopTextWrapPos()
8736 {
8737 ImGuiContext& g = *GImGui;
8738 ImGuiWindow* window = g.CurrentWindow;
8739 if (window->DC.TextWrapPosStack.Size <= 0)
8740 {
8741 IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
8742 return;
8743 }
8744 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8745 window->DC.TextWrapPosStack.pop_back();
8746 }
8747
8748 static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8749 {
8750 ImGuiWindow* last_window = NULL;
8751 while (last_window != window)
8752 {
8753 last_window = window;
8754 window = window->RootWindow;
8755 if (popup_hierarchy)
8756 window = window->RootWindowPopupTree;
8757 if (dock_hierarchy)
8758 window = window->RootWindowDockTree;
8759 }
8760 return window;
8761 }
8762
8763 bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8764 {
8765 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8766 if (window_root == potential_parent)
8767 return true;
8768 while (window != NULL)
8769 {
8770 if (window == potential_parent)
8771 return true;
8772 if (window == window_root) // end of chain
8773 return false;
8774 window = window->ParentWindow;
8775 }
8776 return false;
8777 }
8778
8779 bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8780 {
8781 if (window->RootWindow == potential_parent)
8782 return true;
8783 while (window != NULL)
8784 {
8785 if (window == potential_parent)
8786 return true;
8787 window = window->ParentWindowInBeginStack;
8788 }
8789 return false;
8790 }
8791
8792 bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8793 {
8794 ImGuiContext& g = *GImGui;
8795
8796 // 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
8797 const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8798 if (display_layer_delta != 0)
8799 return display_layer_delta > 0;
8800
8801 for (int i = g.Windows.Size - 1; i >= 0; i--)
8802 {
8803 ImGuiWindow* candidate_window = g.Windows[i];
8804 if (candidate_window == potential_above)
8805 return true;
8806 if (candidate_window == potential_below)
8807 return false;
8808 }
8809 return false;
8810 }
8811
8812 // Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8813 // IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8814 // you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8815 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8816 bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8817 {
8818 ImGuiContext& g = *GImGui;
8819 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
8820
8821 ImGuiWindow* ref_window = g.HoveredWindow;
8822 ImGuiWindow* cur_window = g.CurrentWindow;
8823 if (ref_window == NULL)
8824 return false;
8825
8826 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8827 {
8828 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8829 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8830 const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8831 if (flags & ImGuiHoveredFlags_RootWindow)
8832 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8833
8834 bool result;
8835 if (flags & ImGuiHoveredFlags_ChildWindows)
8836 result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8837 else
8838 result = (ref_window == cur_window);
8839 if (!result)
8840 return false;
8841 }
8842
8843 if (!IsWindowContentHoverable(ref_window, flags))
8844 return false;
8845 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8846 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8847 return false;
8848
8849 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8850 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8851 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8852 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8853 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8854 if (flags & ImGuiHoveredFlags_ForTooltip)
8855 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8856 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8857 return false;
8858
8859 return true;
8860 }
8861
8862 ImGuiID ImGui::GetWindowDockID()
8863 {
8864 ImGuiContext& g = *GImGui;
8865 return g.CurrentWindow->DockId;
8866 }
8867
8868 bool ImGui::IsWindowDocked()
8869 {
8870 ImGuiContext& g = *GImGui;
8871 return g.CurrentWindow->DockIsActive;
8872 }
8873
8874 float ImGui::GetWindowWidth()
8875 {
8876 ImGuiWindow* window = GImGui->CurrentWindow;
8877 return window->Size.x;
8878 }
8879
8880 float ImGui::GetWindowHeight()
8881 {
8882 ImGuiWindow* window = GImGui->CurrentWindow;
8883 return window->Size.y;
8884 }
8885
8886 ImVec2 ImGui::GetWindowPos()
8887 {
8888 ImGuiContext& g = *GImGui;
8889 ImGuiWindow* window = g.CurrentWindow;
8890 return window->Pos;
8891 }
8892
8893 void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8894 {
8895 // Test condition (NB: bit 0 is always true) and clear flags for next time
8896 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8897 return;
8898
8899 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8900 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8901 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8902
8903 // Set
8904 const ImVec2 old_pos = window->Pos;
8905 window->Pos = ImTrunc(pos);
8906 ImVec2 offset = window->Pos - old_pos;
8907 if (offset.x == 0.0f && offset.y == 0.0f)
8908 return;
8909 MarkIniSettingsDirty(window);
8910 // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8911 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
8912 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8913 window->DC.IdealMaxPos += offset;
8914 window->DC.CursorStartPos += offset;
8915 }
8916
8917 void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8918 {
8919 ImGuiWindow* window = GetCurrentWindowRead();
8920 SetWindowPos(window, pos, cond);
8921 }
8922
8923 void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8924 {
8925 if (ImGuiWindow* window = FindWindowByName(name))
8926 SetWindowPos(window, pos, cond);
8927 }
8928
8929 ImVec2 ImGui::GetWindowSize()
8930 {
8931 ImGuiWindow* window = GetCurrentWindowRead();
8932 return window->Size;
8933 }
8934
8935 void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8936 {
8937 // Test condition (NB: bit 0 is always true) and clear flags for next time
8938 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8939 return;
8940
8941 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8942 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8943
8944 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8945 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8946 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8947 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8948 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8949
8950 // Set
8951 ImVec2 old_size = window->SizeFull;
8952 if (size.x <= 0.0f)
8953 window->AutoFitOnlyGrows = false;
8954 else
8955 window->SizeFull.x = IM_TRUNC(size.x);
8956 if (size.y <= 0.0f)
8957 window->AutoFitOnlyGrows = false;
8958 else
8959 window->SizeFull.y = IM_TRUNC(size.y);
8960 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8961 MarkIniSettingsDirty(window);
8962 }
8963
8964 void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8965 {
8966 SetWindowSize(GImGui->CurrentWindow, size, cond);
8967 }
8968
8969 void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8970 {
8971 if (ImGuiWindow* window = FindWindowByName(name))
8972 SetWindowSize(window, size, cond);
8973 }
8974
8975 void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8976 {
8977 // Test condition (NB: bit 0 is always true) and clear flags for next time
8978 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8979 return;
8980 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8981
8982 // Queue applying in Begin()
8983 if (window->WantCollapseToggle)
8984 window->Collapsed ^= 1;
8985 window->WantCollapseToggle = (window->Collapsed != collapsed);
8986 }
8987
8988 void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8989 {
8990 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8991 window->HitTestHoleSize = ImVec2ih(size);
8992 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8993 }
8994
8995 void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8996 {
8997 window->Hidden = window->SkipItems = true;
8998 window->HiddenFramesCanSkipItems = 1;
8999 }
9000
9001 void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
9002 {
9003 SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
9004 }
9005
9006 bool ImGui::IsWindowCollapsed()
9007 {
9008 ImGuiWindow* window = GetCurrentWindowRead();
9009 return window->Collapsed;
9010 }
9011
9012 bool ImGui::IsWindowAppearing()
9013 {
9014 ImGuiWindow* window = GetCurrentWindowRead();
9015 return window->Appearing;
9016 }
9017
9018 void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
9019 {
9020 if (ImGuiWindow* window = FindWindowByName(name))
9021 SetWindowCollapsed(window, collapsed, cond);
9022 }
9023
9024 void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
9025 {
9026 ImGuiContext& g = *GImGui;
9027 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9028 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos;
9029 g.NextWindowData.PosVal = pos;
9030 g.NextWindowData.PosPivotVal = pivot;
9031 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
9032 g.NextWindowData.PosUndock = true;
9033 }
9034
9035 void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
9036 {
9037 ImGuiContext& g = *GImGui;
9038 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9039 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize;
9040 g.NextWindowData.SizeVal = size;
9041 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
9042 }
9043
9044 // For each axis:
9045 // - 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.
9046 // - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
9047 // - See "Demo->Examples->Constrained-resizing window" for examples.
9048 void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
9049 {
9050 ImGuiContext& g = *GImGui;
9051 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
9052 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
9053 g.NextWindowData.SizeCallback = custom_callback;
9054 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
9055 }
9056
9057 // Content size = inner scrollable rectangle, padded with WindowPadding.
9058 // SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
9059 void ImGui::SetNextWindowContentSize(const ImVec2& size)
9060 {
9061 ImGuiContext& g = *GImGui;
9062 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize;
9063 g.NextWindowData.ContentSizeVal = ImTrunc(size);
9064 }
9065
9066 void ImGui::SetNextWindowScroll(const ImVec2& scroll)
9067 {
9068 ImGuiContext& g = *GImGui;
9069 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll;
9070 g.NextWindowData.ScrollVal = scroll;
9071 }
9072
9073 void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
9074 {
9075 ImGuiContext& g = *GImGui;
9076 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9077 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed;
9078 g.NextWindowData.CollapsedVal = collapsed;
9079 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
9080 }
9081
9082 void ImGui::SetNextWindowBgAlpha(float alpha)
9083 {
9084 ImGuiContext& g = *GImGui;
9085 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha;
9086 g.NextWindowData.BgAlphaVal = alpha;
9087 }
9088
9089 void ImGui::SetNextWindowViewport(ImGuiID id)
9090 {
9091 ImGuiContext& g = *GImGui;
9092 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasViewport;
9093 g.NextWindowData.ViewportId = id;
9094 }
9095
9096 void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
9097 {
9098 ImGuiContext& g = *GImGui;
9099 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasDock;
9100 g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
9101 g.NextWindowData.DockId = id;
9102 }
9103
9104 void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
9105 {
9106 ImGuiContext& g = *GImGui;
9107 IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
9108 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasWindowClass;
9109 g.NextWindowData.WindowClass = *window_class;
9110 }
9111
9112 // This is experimental and meant to be a toy for exploring a future/wider range of features.
9113 void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
9114 {
9115 ImGuiContext& g = *GImGui;
9116 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
9117 g.NextWindowData.RefreshFlagsVal = flags;
9118 }
9119
9120 ImDrawList* ImGui::GetWindowDrawList()
9121 {
9122 ImGuiWindow* window = GetCurrentWindow();
9123 return window->DrawList;
9124 }
9125
9126 float ImGui::GetWindowDpiScale()
9127 {
9128 ImGuiContext& g = *GImGui;
9129 return g.CurrentDpiScale;
9130 }
9131
9132 ImGuiViewport* ImGui::GetWindowViewport()
9133 {
9134 ImGuiContext& g = *GImGui;
9135 IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
9136 return g.CurrentViewport;
9137 }
9138
9139 ImFont* ImGui::GetFont()
9140 {
9141 return GImGui->Font;
9142 }
9143
9144 ImFontBaked* ImGui::GetFontBaked()
9145 {
9146 return GImGui->FontBaked;
9147 }
9148
9149 // Get current font size (= height in pixels) of current font, with global scale factors applied.
9150 // - Use style.FontSizeBase to get value before global scale factors.
9151 // - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors)
9152 float ImGui::GetFontSize()
9153 {
9154 return GImGui->FontSize;
9155 }
9156
9157 ImVec2 ImGui::GetFontTexUvWhitePixel()
9158 {
9159 return GImGui->DrawListSharedData.TexUvWhitePixel;
9160 }
9161
9162 // Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows.
9163 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9164 void ImGui::SetWindowFontScale(float scale)
9165 {
9166 IM_ASSERT(scale > 0.0f);
9167 ImGuiWindow* window = GetCurrentWindow();
9168 window->FontWindowScale = scale;
9169 UpdateCurrentFontSize(0.0f);
9170 }
9171 #endif
9172
9173 void ImGui::PushFocusScope(ImGuiID id)
9174 {
9175 ImGuiContext& g = *GImGui;
9176 ImGuiFocusScopeData data;
9177 data.ID = id;
9178 data.WindowID = g.CurrentWindow->ID;
9179 g.FocusScopeStack.push_back(data);
9180 g.CurrentFocusScopeId = id;
9181 }
9182
9183 void ImGui::PopFocusScope()
9184 {
9185 ImGuiContext& g = *GImGui;
9186 if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack)
9187 {
9188 IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
9189 return;
9190 }
9191 g.FocusScopeStack.pop_back();
9192 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
9193 }
9194
9195 void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
9196 {
9197 ImGuiContext& g = *GImGui;
9198 g.NavFocusScopeId = focus_scope_id;
9199 g.NavFocusRoute.resize(0); // Invalidate
9200 if (focus_scope_id == 0)
9201 return;
9202 IM_ASSERT(g.NavWindow != NULL);
9203
9204 // Store current path (in reverse order)
9205 if (focus_scope_id == g.CurrentFocusScopeId)
9206 {
9207 // Top of focus stack contains local focus scopes inside current window
9208 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
9209 g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
9210 }
9211 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
9212 g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
9213 else
9214 return;
9215
9216 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
9217 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
9218 g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
9219 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
9220 }
9221
9222 // Focus = move navigation cursor, set scrolling, set focus window.
9223 void ImGui::FocusItem()
9224 {
9225 ImGuiContext& g = *GImGui;
9226 ImGuiWindow* window = g.CurrentWindow;
9227 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
9228 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
9229 {
9230 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
9231 return;
9232 }
9233
9234 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
9235 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9236 SetNavWindow(window);
9237 NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
9238 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
9239 }
9240
9241 void ImGui::ActivateItemByID(ImGuiID id)
9242 {
9243 ImGuiContext& g = *GImGui;
9244 g.NavNextActivateId = id;
9245 g.NavNextActivateFlags = ImGuiActivateFlags_None;
9246 }
9247
9248 // Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
9249 // But ActivateItem() should function without altering scroll/focus?
9250 void ImGui::SetKeyboardFocusHere(int offset)
9251 {
9252 ImGuiContext& g = *GImGui;
9253 ImGuiWindow* window = g.CurrentWindow;
9254 IM_ASSERT(offset >= -1); // -1 is allowed but not below
9255 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
9256
9257 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
9258 // When we refactor this function into ActivateItem() we may want to make this an option.
9259 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
9260 // is also automatically dropped in the event g.ActiveId is stolen.
9261 if (g.DragDropActive || g.MovingWindow != NULL)
9262 {
9263 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
9264 return;
9265 }
9266
9267 SetNavWindow(window);
9268
9269 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
9270 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9271 NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
9272 if (offset == -1)
9273 {
9274 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
9275 }
9276 else
9277 {
9278 g.NavTabbingDir = 1;
9279 g.NavTabbingCounter = offset + 1;
9280 }
9281 }
9282
9283 void ImGui::SetItemDefaultFocus()
9284 {
9285 ImGuiContext& g = *GImGui;
9286 ImGuiWindow* window = g.CurrentWindow;
9287 if (!window->Appearing)
9288 return;
9289 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
9290 return;
9291
9292 g.NavInitRequest = false;
9293 NavApplyItemToResult(&g.NavInitResult);
9294 NavUpdateAnyRequestFlag();
9295
9296 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
9297 if (!window->ClipRect.Contains(g.LastItemData.Rect))
9298 ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
9299 }
9300
9301 void ImGui::SetStateStorage(ImGuiStorage* tree)
9302 {
9303 ImGuiWindow* window = GImGui->CurrentWindow;
9304 window->DC.StateStorage = tree ? tree : &window->StateStorage;
9305 }
9306
9307 ImGuiStorage* ImGui::GetStateStorage()
9308 {
9309 ImGuiWindow* window = GImGui->CurrentWindow;
9310 return window->DC.StateStorage;
9311 }
9312
9313 bool ImGui::IsRectVisible(const ImVec2& size)
9314 {
9315 ImGuiWindow* window = GImGui->CurrentWindow;
9316 return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
9317 }
9318
9319 bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
9320 {
9321 ImGuiWindow* window = GImGui->CurrentWindow;
9322 return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
9323 }
9324
9325 //-----------------------------------------------------------------------------
9326 // [SECTION] FONTS, TEXTURES
9327 //-----------------------------------------------------------------------------
9328 // Most of the relevant font logic is in imgui_draw.cpp.
9329 // Those are high-level support functions.
9330 //-----------------------------------------------------------------------------
9331 // - UpdateTexturesNewFrame() [Internal]
9332 // - UpdateTexturesEndFrame() [Internal]
9333 // - UpdateFontsNewFrame() [Internal]
9334 // - UpdateFontsEndFrame() [Internal]
9335 // - GetDefaultFont() [Internal]
9336 // - RegisterUserTexture() [Internal]
9337 // - UnregisterUserTexture() [Internal]
9338 // - RegisterFontAtlas() [Internal]
9339 // - UnregisterFontAtlas() [Internal]
9340 // - SetCurrentFont() [Internal]
9341 // - UpdateCurrentFontSize() [Internal]
9342 // - SetFontRasterizerDensity() [Internal]
9343 // - PushFont()
9344 // - PopFont()
9345 //-----------------------------------------------------------------------------
9346
9347 static void ImGui::UpdateTexturesNewFrame()
9348 {
9349 // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count.
9350 ImGuiContext& g = *GImGui;
9351 const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
9352 for (ImFontAtlas* atlas : g.FontAtlases)
9353 {
9354 if (atlas->OwnerContext == &g)
9355 {
9356 ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures);
9357 }
9358 else
9359 {
9360 // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it.
9361 // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context.
9362 // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that.
9363 // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures.
9364 IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1);
9365 IM_ASSERT(atlas->RendererHasTextures == has_textures);
9366 }
9367 }
9368 }
9369
9370 // Build a single texture list
9371 static void ImGui::UpdateTexturesEndFrame()
9372 {
9373 ImGuiContext& g = *GImGui;
9374 g.PlatformIO.Textures.resize(0);
9375 for (ImFontAtlas* atlas : g.FontAtlases)
9376 for (ImTextureData* tex : atlas->TexList)
9377 {
9378 // We provide this information so backends can decide whether to destroy textures.
9379 // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized.
9380 tex->RefCount = (unsigned short)atlas->RefCount;
9381 g.PlatformIO.Textures.push_back(tex);
9382 }
9383 for (ImTextureData* tex : g.UserTextures)
9384 g.PlatformIO.Textures.push_back(tex);
9385 }
9386
9387 void ImGui::UpdateFontsNewFrame()
9388 {
9389 ImGuiContext& g = *GImGui;
9390 if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
9391 for (ImFontAtlas* atlas : g.FontAtlases)
9392 atlas->Locked = true;
9393
9394 if (g.Style._NextFrameFontSizeBase != 0.0f)
9395 {
9396 g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase;
9397 g.Style._NextFrameFontSizeBase = 0.0f;
9398 }
9399
9400 // Apply default font size the first time
9401 ImFont* font = ImGui::GetDefaultFont();
9402 if (g.Style.FontSizeBase <= 0.0f)
9403 g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE);
9404
9405 // Set initial font
9406 g.Font = font;
9407 g.FontSizeBase = g.Style.FontSizeBase;
9408 g.FontSize = 0.0f;
9409 ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize
9410 SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale
9411 g.FontStack.push_back(font_stack_data);
9412 IM_ASSERT(g.Font->IsLoaded());
9413 }
9414
9415 void ImGui::UpdateFontsEndFrame()
9416 {
9417 PopFont();
9418 }
9419
9420 ImFont* ImGui::GetDefaultFont()
9421 {
9422 ImGuiContext& g = *GImGui;
9423 ImFontAtlas* atlas = g.IO.Fonts;
9424 if (atlas->Builder == NULL || atlas->Fonts.Size == 0)
9425 ImFontAtlasBuildMain(atlas);
9426 return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0];
9427 }
9428
9429 // EXPERIMENTAL: DO NOT USE YET.
9430 void ImGui::RegisterUserTexture(ImTextureData* tex)
9431 {
9432 ImGuiContext& g = *GImGui;
9433 tex->RefCount++;
9434 g.UserTextures.push_back(tex);
9435 }
9436
9437 void ImGui::UnregisterUserTexture(ImTextureData* tex)
9438 {
9439 ImGuiContext& g = *GImGui;
9440 IM_ASSERT(tex->RefCount > 0);
9441 tex->RefCount--;
9442 g.UserTextures.find_erase(tex);
9443 }
9444
9445 void ImGui::RegisterFontAtlas(ImFontAtlas* atlas)
9446 {
9447 ImGuiContext& g = *GImGui;
9448 if (g.FontAtlases.Size == 0)
9449 IM_ASSERT(atlas == g.IO.Fonts);
9450 atlas->RefCount++;
9451 g.FontAtlases.push_back(atlas);
9452 ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData);
9453 }
9454
9455 void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas)
9456 {
9457 ImGuiContext& g = *GImGui;
9458 IM_ASSERT(atlas->RefCount > 0);
9459 ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData);
9460 g.FontAtlases.find_erase(atlas);
9461 atlas->RefCount--;
9462 }
9463
9464 // Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList.
9465 // - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls.
9466 // - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
9467 // - Some code paths never really fully worked with multiple atlas textures.
9468 // - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture()
9469 // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
9470 // because we have a concrete need and a test bed for multiple atlas textures.
9471 // FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ?
9472 void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling)
9473 {
9474 ImGuiContext& g = *GImGui;
9475 g.Font = font;
9476 g.FontSizeBase = font_size_before_scaling;
9477 UpdateCurrentFontSize(font_size_after_scaling);
9478
9479 if (font != NULL)
9480 {
9481 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
9482 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9483 IM_ASSERT(font->Scale > 0.0f);
9484 #endif
9485 ImFontAtlas* atlas = font->ContainerAtlas;
9486 g.DrawListSharedData.FontAtlas = atlas;
9487 g.DrawListSharedData.Font = font;
9488 ImFontAtlasUpdateDrawListsSharedData(atlas);
9489 if (g.CurrentWindow != NULL)
9490 g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef);
9491 }
9492 }
9493
9494 void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling)
9495 {
9496 ImGuiContext& g = *GImGui;
9497 ImGuiWindow* window = g.CurrentWindow;
9498
9499 g.Style.FontSizeBase = g.FontSizeBase;
9500
9501 // Early out to avoid hidden window keeping bakes referenced and out of GC reach.
9502 // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching.
9503 // FIXME: perhaps g.FontSize should be updated?
9504 if (window != NULL && window->SkipItems)
9505 {
9506 ImGuiTable* table = g.CurrentTable;
9507 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.
9508 return;
9509 }
9510
9511 // Restoring is pretty much only used by PopFont()
9512 float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f;
9513 if (final_size == 0.0f)
9514 {
9515 final_size = g.FontSizeBase;
9516
9517 // Global scale factors
9518 final_size *= g.Style.FontScaleMain; // Main global scale factor
9519 final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled.
9520
9521 // Window scale (mostly obsolete now)
9522 if (window != NULL)
9523 final_size *= window->FontWindowScale;
9524
9525 // Legacy scale factors
9526 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9527 final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead!
9528 if (g.Font != NULL)
9529 final_size *= g.Font->Scale; // Was never really useful.
9530 #endif
9531 }
9532
9533 // Round font size
9534 // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
9535 // - We may support it better later and remove this rounding.
9536 final_size = GetRoundedFontSize(final_size);
9537 final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX);
9538 if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures))
9539 g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity;
9540 g.FontSize = final_size;
9541 g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL;
9542 g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f;
9543 g.DrawListSharedData.FontSize = g.FontSize;
9544 g.DrawListSharedData.FontScale = g.FontBakedScale;
9545 }
9546
9547 // Exposed in case user may want to override setting density.
9548 // IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it.
9549 void ImGui::SetFontRasterizerDensity(float rasterizer_density)
9550 {
9551 ImGuiContext& g = *GImGui;
9552 IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures);
9553 if (g.FontRasterizerDensity == rasterizer_density)
9554 return;
9555 g.FontRasterizerDensity = rasterizer_density;
9556 UpdateCurrentFontSize(0.0f);
9557 }
9558
9559 // If you want to scale an existing font size! Read comments in imgui.h!
9560 void ImGui::PushFont(ImFont* font, float font_size_base)
9561 {
9562 ImGuiContext& g = *GImGui;
9563 if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont())
9564 font = g.Font;
9565 IM_ASSERT(font != NULL);
9566 IM_ASSERT(font_size_base >= 0.0f);
9567
9568 g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize });
9569 if (font_size_base == 0.0f)
9570 font_size_base = g.FontSizeBase; // Keep current font size
9571 SetCurrentFont(font, font_size_base, 0.0f);
9572 }
9573
9574 void ImGui::PopFont()
9575 {
9576 ImGuiContext& g = *GImGui;
9577 if (g.FontStack.Size <= 0)
9578 {
9579 IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
9580 return;
9581 }
9582 ImFontStackData* font_stack_data = &g.FontStack.back();
9583 SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling);
9584 g.FontStack.pop_back();
9585 }
9586
9587 //-----------------------------------------------------------------------------
9588 // [SECTION] ID STACK
9589 //-----------------------------------------------------------------------------
9590
9591 // This is one of the very rare legacy case where we use ImGuiWindow methods,
9592 // it should ideally be flattened at some point but it's been used a lots by widgets.
9593 IM_MSVC_RUNTIME_CHECKS_OFF
9594 ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
9595 {
9596 ImGuiID seed = IDStack.back();
9597 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
9598 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9599 ImGuiContext& g = *Ctx;
9600 if (g.DebugHookIdInfoId == id)
9601 ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
9602 #endif
9603 return id;
9604 }
9605
9606 ImGuiID ImGuiWindow::GetID(const void* ptr)
9607 {
9608 ImGuiID seed = IDStack.back();
9609 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
9610 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9611 ImGuiContext& g = *Ctx;
9612 if (g.DebugHookIdInfoId == id)
9613 ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
9614 #endif
9615 return id;
9616 }
9617
9618 ImGuiID ImGuiWindow::GetID(int n)
9619 {
9620 ImGuiID seed = IDStack.back();
9621 ImGuiID id = ImHashData(&n, sizeof(n), seed);
9622 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9623 ImGuiContext& g = *Ctx;
9624 if (g.DebugHookIdInfoId == id)
9625 ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
9626 #endif
9627 return id;
9628 }
9629
9630 // This is only used in rare/specific situations to manufacture an ID out of nowhere.
9631 // FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
9632 ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs)
9633 {
9634 ImGuiID seed = IDStack.back();
9635 ImVec2 p_rel = ImGui::WindowPosAbsToRel(this, p_abs);
9636 ImGuiID id = ImHashData(&p_rel, sizeof(p_rel), seed);
9637 return id;
9638 }
9639
9640 // "
9641 ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
9642 {
9643 ImGuiID seed = IDStack.back();
9644 ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
9645 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
9646 return id;
9647 }
9648
9649 void ImGui::PushID(const char* str_id)
9650 {
9651 ImGuiContext& g = *GImGui;
9652 ImGuiWindow* window = g.CurrentWindow;
9653 ImGuiID id = window->GetID(str_id);
9654 window->IDStack.push_back(id);
9655 }
9656
9657 void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
9658 {
9659 ImGuiContext& g = *GImGui;
9660 ImGuiWindow* window = g.CurrentWindow;
9661 ImGuiID id = window->GetID(str_id_begin, str_id_end);
9662 window->IDStack.push_back(id);
9663 }
9664
9665 void ImGui::PushID(const void* ptr_id)
9666 {
9667 ImGuiContext& g = *GImGui;
9668 ImGuiWindow* window = g.CurrentWindow;
9669 ImGuiID id = window->GetID(ptr_id);
9670 window->IDStack.push_back(id);
9671 }
9672
9673 void ImGui::PushID(int int_id)
9674 {
9675 ImGuiContext& g = *GImGui;
9676 ImGuiWindow* window = g.CurrentWindow;
9677 ImGuiID id = window->GetID(int_id);
9678 window->IDStack.push_back(id);
9679 }
9680
9681 // Push a given id value ignoring the ID stack as a seed.
9682 void ImGui::PushOverrideID(ImGuiID id)
9683 {
9684 ImGuiContext& g = *GImGui;
9685 ImGuiWindow* window = g.CurrentWindow;
9686 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9687 if (g.DebugHookIdInfoId == id)
9688 DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
9689 #endif
9690 window->IDStack.push_back(id);
9691 }
9692
9693 // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
9694 // (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
9695 // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
9696 ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
9697 {
9698 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
9699 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9700 ImGuiContext& g = *GImGui;
9701 if (g.DebugHookIdInfoId == id)
9702 DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
9703 #endif
9704 return id;
9705 }
9706
9707 ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
9708 {
9709 ImGuiID id = ImHashData(&n, sizeof(n), seed);
9710 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9711 ImGuiContext& g = *GImGui;
9712 if (g.DebugHookIdInfoId == id)
9713 DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
9714 #endif
9715 return id;
9716 }
9717
9718 void ImGui::PopID()
9719 {
9720 ImGuiWindow* window = GImGui->CurrentWindow;
9721 if (window->IDStack.Size <= 1)
9722 {
9723 IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!");
9724 return;
9725 }
9726 window->IDStack.pop_back();
9727 }
9728
9729 ImGuiID ImGui::GetID(const char* str_id)
9730 {
9731 ImGuiWindow* window = GImGui->CurrentWindow;
9732 return window->GetID(str_id);
9733 }
9734
9735 ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9736 {
9737 ImGuiWindow* window = GImGui->CurrentWindow;
9738 return window->GetID(str_id_begin, str_id_end);
9739 }
9740
9741 ImGuiID ImGui::GetID(const void* ptr_id)
9742 {
9743 ImGuiWindow* window = GImGui->CurrentWindow;
9744 return window->GetID(ptr_id);
9745 }
9746
9747 ImGuiID ImGui::GetID(int int_id)
9748 {
9749 ImGuiWindow* window = GImGui->CurrentWindow;
9750 return window->GetID(int_id);
9751 }
9752 IM_MSVC_RUNTIME_CHECKS_RESTORE
9753
9754 //-----------------------------------------------------------------------------
9755 // [SECTION] INPUTS
9756 //-----------------------------------------------------------------------------
9757 // - GetModForLRModKey() [Internal]
9758 // - FixupKeyChord() [Internal]
9759 // - GetKeyData() [Internal]
9760 // - GetKeyIndex() [Internal]
9761 // - GetKeyName()
9762 // - GetKeyChordName() [Internal]
9763 // - CalcTypematicRepeatAmount() [Internal]
9764 // - GetTypematicRepeatRate() [Internal]
9765 // - GetKeyPressedAmount() [Internal]
9766 // - GetKeyMagnitude2d() [Internal]
9767 //-----------------------------------------------------------------------------
9768 // - UpdateKeyRoutingTable() [Internal]
9769 // - GetRoutingIdFromOwnerId() [Internal]
9770 // - GetShortcutRoutingData() [Internal]
9771 // - CalcRoutingScore() [Internal]
9772 // - SetShortcutRouting() [Internal]
9773 // - TestShortcutRouting() [Internal]
9774 //-----------------------------------------------------------------------------
9775 // - IsKeyDown()
9776 // - IsKeyPressed()
9777 // - IsKeyReleased()
9778 //-----------------------------------------------------------------------------
9779 // - IsMouseDown()
9780 // - IsMouseClicked()
9781 // - IsMouseReleased()
9782 // - IsMouseDoubleClicked()
9783 // - GetMouseClickedCount()
9784 // - IsMouseHoveringRect() [Internal]
9785 // - IsMouseDragPastThreshold() [Internal]
9786 // - IsMouseDragging()
9787 // - GetMousePos()
9788 // - SetMousePos() [Internal]
9789 // - GetMousePosOnOpeningCurrentPopup()
9790 // - IsMousePosValid()
9791 // - IsAnyMouseDown()
9792 // - GetMouseDragDelta()
9793 // - ResetMouseDragDelta()
9794 // - GetMouseCursor()
9795 // - SetMouseCursor()
9796 //-----------------------------------------------------------------------------
9797 // - UpdateAliasKey()
9798 // - GetMergedModsFromKeys()
9799 // - UpdateKeyboardInputs()
9800 // - UpdateMouseInputs()
9801 //-----------------------------------------------------------------------------
9802 // - LockWheelingWindow [Internal]
9803 // - FindBestWheelingWindow [Internal]
9804 // - UpdateMouseWheel() [Internal]
9805 //-----------------------------------------------------------------------------
9806 // - SetNextFrameWantCaptureKeyboard()
9807 // - SetNextFrameWantCaptureMouse()
9808 //-----------------------------------------------------------------------------
9809 // - GetInputSourceName() [Internal]
9810 // - DebugPrintInputEvent() [Internal]
9811 // - UpdateInputEvents() [Internal]
9812 //-----------------------------------------------------------------------------
9813 // - GetKeyOwner() [Internal]
9814 // - TestKeyOwner() [Internal]
9815 // - SetKeyOwner() [Internal]
9816 // - SetItemKeyOwner() [Internal]
9817 // - Shortcut() [Internal]
9818 //-----------------------------------------------------------------------------
9819
9820 static ImGuiKeyChord GetModForLRModKey(ImGuiKey key)
9821 {
9822 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9823 return ImGuiMod_Ctrl;
9824 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9825 return ImGuiMod_Shift;
9826 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9827 return ImGuiMod_Alt;
9828 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9829 return ImGuiMod_Super;
9830 return ImGuiMod_None;
9831 }
9832
9833 ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9834 {
9835 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9836 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9837 if (IsLRModKey(key))
9838 key_chord |= GetModForLRModKey(key);
9839 return key_chord;
9840 }
9841
9842 ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9843 {
9844 ImGuiContext& g = *ctx;
9845
9846 // Special storage location for mods
9847 if (key & ImGuiMod_Mask_)
9848 key = ConvertSingleModFlagToKey(key);
9849
9850 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9851 return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
9852 }
9853
9854 // Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
9855 static const char* const GKeyNames[] =
9856 {
9857 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9858 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9859 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9860 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9861 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9862 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9863 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9864 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9865 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9866 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9867 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9868 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9869 "AppBack", "AppForward", "Oem102",
9870 "GamepadStart", "GamepadBack",
9871 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9872 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9873 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9874 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9875 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9876 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9877 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9878 };
9879 IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9880
9881 const char* ImGui::GetKeyName(ImGuiKey key)
9882 {
9883 if (key == ImGuiKey_None)
9884 return "None";
9885 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9886 if (key & ImGuiMod_Mask_)
9887 key = ConvertSingleModFlagToKey(key);
9888 if (!IsNamedKey(key))
9889 return "Unknown";
9890
9891 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9892 }
9893
9894 // Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9895 // Lifetime of return value: valid until next call to same function.
9896 const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9897 {
9898 ImGuiContext& g = *GImGui;
9899
9900 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9901 if (IsLRModKey(key))
9902 key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9903 ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9904 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9905 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9906 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9907 (key_chord & ImGuiMod_Super) ? "Super+" : "",
9908 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9909 size_t len;
9910 if (key == ImGuiKey_None && key_chord != 0)
9911 if ((len = ImStrlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9912 g.TempKeychordName[len - 1] = 0;
9913 return g.TempKeychordName;
9914 }
9915
9916 // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9917 // t1 = current time (e.g.: g.Time)
9918 // An event is triggered at:
9919 // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
9920 int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9921 {
9922 if (t1 == 0.0f)
9923 return 1;
9924 if (t0 >= t1)
9925 return 0;
9926 if (repeat_rate <= 0.0f)
9927 return (t0 < repeat_delay) && (t1 >= repeat_delay);
9928 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9929 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9930 const int count = count_t1 - count_t0;
9931 return count;
9932 }
9933
9934 void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9935 {
9936 ImGuiContext& g = *GImGui;
9937 switch (flags & ImGuiInputFlags_RepeatRateMask_)
9938 {
9939 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9940 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9941 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9942 }
9943 }
9944
9945 // Return value representing the number of presses in the last time period, for the given repeat rate
9946 // (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9947 int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9948 {
9949 ImGuiContext& g = *GImGui;
9950 const ImGuiKeyData* key_data = GetKeyData(key);
9951 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)
9952 return 0;
9953 const float t = key_data->DownDuration;
9954 return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9955 }
9956
9957 // Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9958 ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9959 {
9960 return ImVec2(
9961 GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9962 GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9963 }
9964
9965 // Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9966 // Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
9967 // Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
9968 // See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9969 static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9970 {
9971 ImGuiContext& g = *GImGui;
9972 rt->EntriesNext.resize(0);
9973 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9974 {
9975 const int new_routing_start_idx = rt->EntriesNext.Size;
9976 ImGuiKeyRoutingData* routing_entry;
9977 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9978 {
9979 routing_entry = &rt->Entries[old_routing_idx];
9980 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9981 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9982 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9983 routing_entry->RoutingNextScore = 255;
9984 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9985 continue;
9986 rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9987
9988 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9989 // This is the result of previous frame's SetShortcutRouting() call.
9990 if (routing_entry->Mods == g.IO.KeyMods)
9991 {
9992 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9993 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9994 {
9995 owner_data->OwnerCurr = routing_entry->RoutingCurr;
9996 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9997 }
9998 }
9999 }
10000
10001 // Rewrite linked-list
10002 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
10003 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
10004 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
10005 }
10006 rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
10007 }
10008
10009 // owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
10010 static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
10011 {
10012 ImGuiContext& g = *GImGui;
10013 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
10014 }
10015
10016 ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
10017 {
10018 // Majority of shortcuts will be Key + any number of Mods
10019 // We accept _Single_ mod with ImGuiKey_None.
10020 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
10021 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
10022 // - Shortcut(ImGuiMod_Ctrl); // Legal
10023 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
10024 ImGuiContext& g = *GImGui;
10025 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
10026 ImGuiKeyRoutingData* routing_data;
10027 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10028 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10029 if (key == ImGuiKey_None)
10030 key = ConvertSingleModFlagToKey(mods);
10031 IM_ASSERT(IsNamedKey(key));
10032
10033 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
10034 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
10035 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
10036 {
10037 routing_data = &rt->Entries[idx];
10038 if (routing_data->Mods == mods)
10039 return routing_data;
10040 }
10041
10042 // Add to linked-list
10043 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
10044 rt->Entries.push_back(ImGuiKeyRoutingData());
10045 routing_data = &rt->Entries[routing_data_idx];
10046 routing_data->Mods = (ImU16)mods;
10047 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
10048 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
10049 return routing_data;
10050 }
10051
10052 // Current score encoding (lower is highest priority):
10053 // - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
10054 // - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
10055 // - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
10056 // - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
10057 // - 254: ImGuiInputFlags_RouteGlobal
10058 // - 255: never route
10059 // 'flags' should include an explicit routing policy
10060 static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
10061 {
10062 ImGuiContext& g = *GImGui;
10063 if (flags & ImGuiInputFlags_RouteFocused)
10064 {
10065 // ActiveID gets top priority
10066 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
10067 if (owner_id != 0 && g.ActiveId == owner_id)
10068 return 1;
10069
10070 // Score based on distance to focused window (lower is better)
10071 // Assuming both windows are submitting a routing request,
10072 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
10073 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
10074 // Assuming only WindowA is submitting a routing request,
10075 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
10076 // This essentially follow the window->ParentWindowForFocusRoute chain.
10077 if (focus_scope_id == 0)
10078 return 255;
10079 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
10080 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
10081 return 3 + index_in_focus_path;
10082 return 255;
10083 }
10084 else if (flags & ImGuiInputFlags_RouteActive)
10085 {
10086 if (owner_id != 0 && g.ActiveId == owner_id)
10087 return 1;
10088 return 255;
10089 }
10090 else if (flags & ImGuiInputFlags_RouteGlobal)
10091 {
10092 if (flags & ImGuiInputFlags_RouteOverActive)
10093 return 0;
10094 if (flags & ImGuiInputFlags_RouteOverFocused)
10095 return 2;
10096 return 254;
10097 }
10098 IM_ASSERT(0);
10099 return 0;
10100 }
10101
10102 // - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
10103 // e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
10104 // - 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.
10105 static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
10106 {
10107 // Mimic 'ignore_char_inputs' logic in InputText()
10108 ImGuiContext& g = *GImGui;
10109
10110 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
10111 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10112 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
10113 if (ignore_char_inputs)
10114 return false;
10115
10116 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
10117 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10118 if (key == ImGuiKey_None)
10119 return false;
10120 return g.KeysMayBeCharInput.TestBit(key);
10121 }
10122
10123 // Request a desired route for an input chord (key + mods).
10124 // Return true if the route is available this frame.
10125 // - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
10126 // (Conceptually this does a "Submit for next frame" + "Test for current frame".
10127 // As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
10128 bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10129 {
10130 ImGuiContext& g = *GImGui;
10131 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10132 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
10133 else
10134 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
10135 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
10136 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
10137 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
10138
10139 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
10140 key_chord = FixupKeyChord(key_chord);
10141
10142 // [DEBUG] Debug break requested by user
10143 if (g.DebugBreakInShortcutRouting == key_chord)
10144 IM_DEBUG_BREAK();
10145
10146 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
10147 if (g.NavWindow == NULL)
10148 return false;
10149
10150 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
10151 if (flags & ImGuiInputFlags_RouteAlways)
10152 {
10153 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
10154 return true;
10155 }
10156
10157 // Specific culling when there's an active item.
10158 if (g.ActiveId != 0 && g.ActiveId != owner_id)
10159 {
10160 if (flags & ImGuiInputFlags_RouteActive)
10161 return false;
10162
10163 // Cull shortcuts with no modifiers when it could generate a character.
10164 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
10165 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
10166 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
10167 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
10168 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
10169 {
10170 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
10171 return false;
10172 }
10173
10174 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
10175 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
10176 {
10177 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10178 if (key == ImGuiKey_None)
10179 key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
10180 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10181 return false;
10182 }
10183 }
10184
10185 // Where do we evaluate route for?
10186 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
10187 if (flags & ImGuiInputFlags_RouteFromRootWindow)
10188 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
10189
10190 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
10191 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
10192 if (score == 255)
10193 return false;
10194
10195 // Submit routing for NEXT frame (assuming score is sufficient)
10196 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
10197 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
10198 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
10199 if (score < routing_data->RoutingNextScore)
10200 {
10201 routing_data->RoutingNext = owner_id;
10202 routing_data->RoutingNextScore = (ImU8)score;
10203 }
10204
10205 // Return routing state for CURRENT frame
10206 if (routing_data->RoutingCurr == owner_id)
10207 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
10208 return routing_data->RoutingCurr == owner_id;
10209 }
10210
10211 // Currently unused by core (but used by tests)
10212 // Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
10213 bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
10214 {
10215 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
10216 key_chord = FixupKeyChord(key_chord);
10217 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
10218 return routing_data->RoutingCurr == routing_id;
10219 }
10220
10221 // Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
10222 // Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
10223 bool ImGui::IsKeyDown(ImGuiKey key)
10224 {
10225 return IsKeyDown(key, ImGuiKeyOwner_Any);
10226 }
10227
10228 bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
10229 {
10230 const ImGuiKeyData* key_data = GetKeyData(key);
10231 if (!key_data->Down)
10232 return false;
10233 if (!TestKeyOwner(key, owner_id))
10234 return false;
10235 return true;
10236 }
10237
10238 bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
10239 {
10240 return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10241 }
10242
10243 // Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
10244 bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
10245 {
10246 const ImGuiKeyData* key_data = GetKeyData(key);
10247 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)
10248 return false;
10249 const float t = key_data->DownDuration;
10250 if (t < 0.0f)
10251 return false;
10252 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
10253 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
10254 flags |= ImGuiInputFlags_Repeat;
10255
10256 bool pressed = (t == 0.0f);
10257 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
10258 {
10259 float repeat_delay, repeat_rate;
10260 GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
10261 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
10262 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
10263 {
10264 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
10265 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
10266 ImGuiContext& g = *GImGui;
10267 double key_pressed_time = g.Time - t + 0.00001f;
10268 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
10269 pressed = false;
10270 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
10271 pressed = false;
10272 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
10273 pressed = false;
10274 }
10275 }
10276 if (!pressed)
10277 return false;
10278 if (!TestKeyOwner(key, owner_id))
10279 return false;
10280 return true;
10281 }
10282
10283 bool ImGui::IsKeyReleased(ImGuiKey key)
10284 {
10285 return IsKeyReleased(key, ImGuiKeyOwner_Any);
10286 }
10287
10288 bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
10289 {
10290 const ImGuiKeyData* key_data = GetKeyData(key);
10291 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
10292 return false;
10293 if (!TestKeyOwner(key, owner_id))
10294 return false;
10295 return true;
10296 }
10297
10298 bool ImGui::IsMouseDown(ImGuiMouseButton button)
10299 {
10300 ImGuiContext& g = *GImGui;
10301 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10302 return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
10303 }
10304
10305 bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
10306 {
10307 ImGuiContext& g = *GImGui;
10308 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10309 return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
10310 }
10311
10312 bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
10313 {
10314 return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10315 }
10316
10317 bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
10318 {
10319 ImGuiContext& g = *GImGui;
10320 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10321 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)
10322 return false;
10323 const float t = g.IO.MouseDownDuration[button];
10324 if (t < 0.0f)
10325 return false;
10326 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
10327
10328 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
10329 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
10330 if (!pressed)
10331 return false;
10332
10333 if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
10334 return false;
10335
10336 return true;
10337 }
10338
10339 bool ImGui::IsMouseReleased(ImGuiMouseButton button)
10340 {
10341 ImGuiContext& g = *GImGui;
10342 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10343 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
10344 }
10345
10346 bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
10347 {
10348 ImGuiContext& g = *GImGui;
10349 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10350 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
10351 }
10352
10353 // Use if you absolutely need to distinguish single-click from double-click by introducing a delay.
10354 // Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test.
10355 // This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
10356 bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay)
10357 {
10358 ImGuiContext& g = *GImGui;
10359 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10360 const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]);
10361 return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay);
10362 }
10363
10364 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
10365 {
10366 ImGuiContext& g = *GImGui;
10367 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10368 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
10369 }
10370
10371 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
10372 {
10373 ImGuiContext& g = *GImGui;
10374 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10375 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
10376 }
10377
10378 int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
10379 {
10380 ImGuiContext& g = *GImGui;
10381 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10382 return g.IO.MouseClickedCount[button];
10383 }
10384
10385 // Test if mouse cursor is hovering given rectangle
10386 // NB- Rectangle is clipped by our current clip setting
10387 // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
10388 bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
10389 {
10390 ImGuiContext& g = *GImGui;
10391
10392 // Clip
10393 ImRect rect_clipped(r_min, r_max);
10394 if (clip)
10395 rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
10396
10397 // Hit testing, expanded for touch input
10398 if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
10399 return false;
10400 if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
10401 return false;
10402 return true;
10403 }
10404
10405 // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
10406 // [Internal] This doesn't test if the button is pressed
10407 bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
10408 {
10409 ImGuiContext& g = *GImGui;
10410 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10411 if (lock_threshold < 0.0f)
10412 lock_threshold = g.IO.MouseDragThreshold;
10413 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
10414 }
10415
10416 bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
10417 {
10418 ImGuiContext& g = *GImGui;
10419 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10420 if (!g.IO.MouseDown[button])
10421 return false;
10422 return IsMouseDragPastThreshold(button, lock_threshold);
10423 }
10424
10425 ImVec2 ImGui::GetMousePos()
10426 {
10427 ImGuiContext& g = *GImGui;
10428 return g.IO.MousePos;
10429 }
10430
10431 // This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
10432 // It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
10433 void ImGui::TeleportMousePos(const ImVec2& pos)
10434 {
10435 ImGuiContext& g = *GImGui;
10436 g.IO.MousePos = g.IO.MousePosPrev = pos;
10437 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
10438 g.IO.WantSetMousePos = true;
10439 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
10440 }
10441
10442 // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
10443 ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
10444 {
10445 ImGuiContext& g = *GImGui;
10446 if (g.BeginPopupStack.Size > 0)
10447 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
10448 return g.IO.MousePos;
10449 }
10450
10451 // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
10452 bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
10453 {
10454 // The assert is only to silence a false-positive in XCode Static Analysis.
10455 // 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).
10456 IM_ASSERT(GImGui != NULL);
10457 const float MOUSE_INVALID = -256000.0f;
10458 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
10459 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
10460 }
10461
10462 // [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.
10463 bool ImGui::IsAnyMouseDown()
10464 {
10465 ImGuiContext& g = *GImGui;
10466 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
10467 if (g.IO.MouseDown[n])
10468 return true;
10469 return false;
10470 }
10471
10472 // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
10473 // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
10474 // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
10475 ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
10476 {
10477 ImGuiContext& g = *GImGui;
10478 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10479 if (lock_threshold < 0.0f)
10480 lock_threshold = g.IO.MouseDragThreshold;
10481 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
10482 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
10483 if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
10484 return g.IO.MousePos - g.IO.MouseClickedPos[button];
10485 return ImVec2(0.0f, 0.0f);
10486 }
10487
10488 void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
10489 {
10490 ImGuiContext& g = *GImGui;
10491 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10492 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
10493 g.IO.MouseClickedPos[button] = g.IO.MousePos;
10494 }
10495
10496 // Get desired mouse cursor shape.
10497 // Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
10498 // updated during the frame, and locked in EndFrame()/Render().
10499 // If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
10500 ImGuiMouseCursor ImGui::GetMouseCursor()
10501 {
10502 ImGuiContext& g = *GImGui;
10503 return g.MouseCursor;
10504 }
10505
10506 // We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
10507 // 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
10508 // handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
10509 void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
10510 {
10511 ImGuiContext& g = *GImGui;
10512 g.MouseCursor = cursor_type;
10513 }
10514
10515 static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
10516 {
10517 IM_ASSERT(ImGui::IsAliasKey(key));
10518 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
10519 key_data->Down = v;
10520 key_data->AnalogValue = analog_value;
10521 }
10522
10523 // [Internal] Do not use directly
10524 static ImGuiKeyChord GetMergedModsFromKeys()
10525 {
10526 ImGuiKeyChord mods = 0;
10527 if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
10528 if (ImGui::IsKeyDown(ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
10529 if (ImGui::IsKeyDown(ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
10530 if (ImGui::IsKeyDown(ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
10531 return mods;
10532 }
10533
10534 static void ImGui::UpdateKeyboardInputs()
10535 {
10536 ImGuiContext& g = *GImGui;
10537 ImGuiIO& io = g.IO;
10538
10539 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10540 io.ClearInputKeys();
10541
10542 // Update aliases
10543 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
10544 UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
10545 UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
10546 UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
10547
10548 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
10549 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10550 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10551 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
10552 const ImGuiKeyChord prev_key_mods = io.KeyMods;
10553 io.KeyMods = GetMergedModsFromKeys();
10554 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
10555 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
10556 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
10557 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
10558 if (prev_key_mods != io.KeyMods)
10559 g.LastKeyModsChangeTime = g.Time;
10560 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
10561 g.LastKeyModsChangeFromNoneTime = g.Time;
10562
10563 // Clear gamepad data if disabled
10564 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
10565 for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
10566 {
10567 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
10568 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
10569 }
10570
10571 // Update keys
10572 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
10573 {
10574 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10575 key_data->DownDurationPrev = key_data->DownDuration;
10576 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
10577 if (key_data->DownDuration == 0.0f)
10578 {
10579 if (IsKeyboardKey((ImGuiKey)key))
10580 g.LastKeyboardKeyPressTime = g.Time;
10581 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
10582 g.LastKeyboardKeyPressTime = g.Time;
10583 }
10584 }
10585
10586 // Update keys/input owner (named keys only): one entry per key
10587 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
10588 {
10589 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10590 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
10591 owner_data->OwnerCurr = owner_data->OwnerNext;
10592 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.
10593 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
10594 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
10595 }
10596
10597 // Update key routing (for e.g. shortcuts)
10598 UpdateKeyRoutingTable(&g.KeysRoutingTable);
10599 }
10600
10601 static void ImGui::UpdateMouseInputs()
10602 {
10603 ImGuiContext& g = *GImGui;
10604 ImGuiIO& io = g.IO;
10605
10606 // Mouse Wheel swapping flag
10607 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
10608 // - We avoid doing it on OSX as it the OS input layer handles this already.
10609 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
10610 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
10611 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
10612
10613 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
10614 if (IsMousePosValid(&io.MousePos))
10615 io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
10616
10617 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
10618 if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
10619 io.MouseDelta = io.MousePos - io.MousePosPrev;
10620 else
10621 io.MouseDelta = ImVec2(0.0f, 0.0f);
10622
10623 // Update stationary timer.
10624 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
10625 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
10626 const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
10627 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
10628 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
10629
10630 // 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.
10631 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
10632 g.NavHighlightItemUnderNav = false;
10633
10634 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
10635 {
10636 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
10637 io.MouseClickedCount[i] = 0; // Will be filled below
10638 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
10639 if (io.MouseReleased[i])
10640 io.MouseReleasedTime[i] = g.Time;
10641 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
10642 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
10643 if (io.MouseClicked[i])
10644 {
10645 bool is_repeated_click = false;
10646 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
10647 {
10648 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10649 if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
10650 is_repeated_click = true;
10651 }
10652 if (is_repeated_click)
10653 io.MouseClickedLastCount[i]++;
10654 else
10655 io.MouseClickedLastCount[i] = 1;
10656 io.MouseClickedTime[i] = g.Time;
10657 io.MouseClickedPos[i] = io.MousePos;
10658 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10659 io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10660 io.MouseDragMaxDistanceSqr[i] = 0.0f;
10661 }
10662 else if (io.MouseDown[i])
10663 {
10664 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10665 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10666 io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
10667 io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
10668 io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
10669 }
10670
10671 // We provide io.MouseDoubleClicked[] as a legacy service
10672 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10673
10674 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
10675 if (io.MouseClicked[i])
10676 g.NavHighlightItemUnderNav = false;
10677 }
10678 }
10679
10680 static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10681 {
10682 ImGuiContext& g = *GImGui;
10683 if (window)
10684 g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10685 else
10686 g.WheelingWindowReleaseTimer = 0.0f;
10687 if (g.WheelingWindow == window)
10688 return;
10689 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10690 g.WheelingWindow = window;
10691 g.WheelingWindowRefMousePos = g.IO.MousePos;
10692 if (window == NULL)
10693 {
10694 g.WheelingWindowStartFrame = -1;
10695 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10696 }
10697 }
10698
10699 static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10700 {
10701 // For each axis, find window in the hierarchy that may want to use scrolling
10702 ImGuiContext& g = *GImGui;
10703 ImGuiWindow* windows[2] = { NULL, NULL };
10704 for (int axis = 0; axis < 2; axis++)
10705 if (wheel[axis] != 0.0f)
10706 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10707 {
10708 // Bubble up into parent window if:
10709 // - a child window doesn't allow any scrolling.
10710 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10711 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10712 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10713 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10714 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10715 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10716 break; // select this window
10717 }
10718 if (windows[0] == NULL && windows[1] == NULL)
10719 return NULL;
10720
10721 // If there's only one window or only one axis then there's no ambiguity
10722 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10723 return windows[1] ? windows[1] : windows[0];
10724
10725 // If candidate are different windows we need to decide which one to prioritize
10726 // - First frame: only find a winner if one axis is zero.
10727 // - Subsequent frames: only find a winner when one is more than the other.
10728 if (g.WheelingWindowStartFrame == -1)
10729 g.WheelingWindowStartFrame = g.FrameCount;
10730 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10731 {
10732 g.WheelingWindowWheelRemainder = wheel;
10733 return NULL;
10734 }
10735 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10736 }
10737
10738 // Called by NewFrame()
10739 void ImGui::UpdateMouseWheel()
10740 {
10741 // Reset the locked window if we move the mouse or after the timer elapses.
10742 // 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)
10743 ImGuiContext& g = *GImGui;
10744 if (g.WheelingWindow != NULL)
10745 {
10746 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10747 if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10748 g.WheelingWindowReleaseTimer = 0.0f;
10749 if (g.WheelingWindowReleaseTimer <= 0.0f)
10750 LockWheelingWindow(NULL, 0.0f);
10751 }
10752
10753 ImVec2 wheel;
10754 wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10755 wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10756
10757 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10758 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10759 if (!mouse_window || mouse_window->Collapsed)
10760 return;
10761
10762 // Zoom / Scale window
10763 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10764 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10765 {
10766 LockWheelingWindow(mouse_window, wheel.y);
10767 ImGuiWindow* window = mouse_window;
10768 const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10769 const float scale = new_font_scale / window->FontWindowScale;
10770 window->FontWindowScale = new_font_scale;
10771 if (window == window->RootWindow)
10772 {
10773 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10774 SetWindowPos(window, window->Pos + offset, 0);
10775 window->Size = ImTrunc(window->Size * scale);
10776 window->SizeFull = ImTrunc(window->SizeFull * scale);
10777 }
10778 return;
10779 }
10780 if (g.IO.KeyCtrl)
10781 return;
10782
10783 // Mouse wheel scrolling
10784 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10785 if (g.IO.MouseWheelRequestAxisSwap)
10786 wheel = ImVec2(wheel.y, 0.0f);
10787
10788 // Maintain a rough average of moving magnitude on both axes
10789 // FIXME: should by based on wall clock time rather than frame-counter
10790 g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10791 g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10792
10793 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10794 wheel += g.WheelingWindowWheelRemainder;
10795 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10796 if (wheel.x == 0.0f && wheel.y == 0.0f)
10797 return;
10798
10799 // Mouse wheel scrolling: find target and apply
10800 // - don't renew lock if axis doesn't apply on the window.
10801 // - select a main axis when both axes are being moved.
10802 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10803 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10804 {
10805 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10806 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10807 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10808 if (do_scroll[ImGuiAxis_X])
10809 {
10810 LockWheelingWindow(window, wheel.x);
10811 float max_step = window->InnerRect.GetWidth() * 0.67f;
10812 float scroll_step = ImTrunc(ImMin(2 * window->FontRefSize, max_step));
10813 SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10814 g.WheelingWindowScrolledFrame = g.FrameCount;
10815 }
10816 if (do_scroll[ImGuiAxis_Y])
10817 {
10818 LockWheelingWindow(window, wheel.y);
10819 float max_step = window->InnerRect.GetHeight() * 0.67f;
10820 float scroll_step = ImTrunc(ImMin(5 * window->FontRefSize, max_step));
10821 SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10822 g.WheelingWindowScrolledFrame = g.FrameCount;
10823 }
10824 }
10825 }
10826
10827 void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10828 {
10829 ImGuiContext& g = *GImGui;
10830 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10831 }
10832
10833 void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10834 {
10835 ImGuiContext& g = *GImGui;
10836 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10837 }
10838
10839 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
10840 static const char* GetInputSourceName(ImGuiInputSource source)
10841 {
10842 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10843 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
10844 if (source < 0 || source >= ImGuiInputSource_COUNT)
10845 return "Unknown";
10846 return input_source_names[source];
10847 }
10848 static const char* GetMouseSourceName(ImGuiMouseSource source)
10849 {
10850 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10851 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT);
10852 if (source < 0 || source >= ImGuiMouseSource_COUNT)
10853 return "Unknown";
10854 return mouse_source_names[source];
10855 }
10856 static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10857 {
10858 ImGuiContext& g = *GImGui;
10859 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; }
10860 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; }
10861 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; }
10862 if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10863 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; }
10864 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10865 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10866 }
10867 #endif
10868
10869 // Process input queue
10870 // We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10871 // - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10872 // - 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)
10873 void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10874 {
10875 ImGuiContext& g = *GImGui;
10876 ImGuiIO& io = g.IO;
10877
10878 // Only trickle chars<>key when working with InputText()
10879 // FIXME: InputText() could parse event trail?
10880 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10881 const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10882
10883 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
10884 int mouse_button_changed = 0x00;
10885 ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
10886
10887 int event_n = 0;
10888 for (; event_n < g.InputEventsQueue.Size; event_n++)
10889 {
10890 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10891 if (e->Type == ImGuiInputEventType_MousePos)
10892 {
10893 if (g.IO.WantSetMousePos)
10894 continue;
10895 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10896 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10897 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10898 break;
10899 io.MousePos = event_pos;
10900 io.MouseSource = e->MousePos.MouseSource;
10901 mouse_moved = true;
10902 }
10903 else if (e->Type == ImGuiInputEventType_MouseButton)
10904 {
10905 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10906 const ImGuiMouseButton button = e->MouseButton.Button;
10907 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10908 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10909 break;
10910 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10911 break;
10912 io.MouseDown[button] = e->MouseButton.Down;
10913 io.MouseSource = e->MouseButton.MouseSource;
10914 mouse_button_changed |= (1 << button);
10915 }
10916 else if (e->Type == ImGuiInputEventType_MouseWheel)
10917 {
10918 // Trickling Rule: Stop processing queued events if we got multiple action on the event
10919 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10920 break;
10921 io.MouseWheelH += e->MouseWheel.WheelX;
10922 io.MouseWheel += e->MouseWheel.WheelY;
10923 io.MouseSource = e->MouseWheel.MouseSource;
10924 mouse_wheeled = true;
10925 }
10926 else if (e->Type == ImGuiInputEventType_MouseViewport)
10927 {
10928 io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10929 }
10930 else if (e->Type == ImGuiInputEventType_Key)
10931 {
10932 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10933 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10934 continue;
10935 ImGuiKey key = e->Key.Key;
10936 IM_ASSERT(key != ImGuiKey_None);
10937 ImGuiKeyData* key_data = GetKeyData(key);
10938 const int key_data_index = (int)(key_data - g.IO.KeysData);
10939 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || mouse_button_changed != 0))
10940 break;
10941
10942 const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(GetMergedModsFromKeys() | key);
10943 if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
10944 break;
10945
10946 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.
10947 {
10948 key_changed = true;
10949 key_changed_mask.SetBit(key_data_index);
10950 if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
10951 key_changed_nonchar = true;
10952 }
10953
10954 key_data->Down = e->Key.Down;
10955 key_data->AnalogValue = e->Key.AnalogValue;
10956 }
10957 else if (e->Type == ImGuiInputEventType_Text)
10958 {
10959 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10960 continue;
10961 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10962 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10963 break;
10964 if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar)
10965 break;
10966 unsigned int c = e->Text.Char;
10967 io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10968 if (trickle_interleaved_nonchar_keys_and_text)
10969 text_inputted = true;
10970 }
10971 else if (e->Type == ImGuiInputEventType_Focus)
10972 {
10973 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10974 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10975 const bool focus_lost = !e->AppFocused.Focused;
10976 io.AppFocusLost = focus_lost;
10977 }
10978 else
10979 {
10980 IM_ASSERT(0 && "Unknown event!");
10981 }
10982 }
10983
10984 // Record trail (for domain-specific applications wanting to access a precise trail)
10985 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10986 for (int n = 0; n < event_n; n++)
10987 g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10988
10989 // [DEBUG]
10990 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
10991 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10992 for (int n = 0; n < g.InputEventsQueue.Size; n++)
10993 DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10994 #endif
10995
10996 // Remaining events will be processed on the next frame
10997 if (event_n == g.InputEventsQueue.Size)
10998 g.InputEventsQueue.resize(0);
10999 else
11000 g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
11001
11002 // Clear buttons state when focus is lost
11003 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
11004 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
11005 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
11006 if (g.IO.AppFocusLost)
11007 {
11008 g.IO.ClearInputKeys();
11009 g.IO.ClearInputMouse();
11010 }
11011 }
11012
11013 ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
11014 {
11015 if (!IsNamedKeyOrMod(key))
11016 return ImGuiKeyOwner_NoOwner;
11017
11018 ImGuiContext& g = *GImGui;
11019 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
11020 ImGuiID owner_id = owner_data->OwnerCurr;
11021
11022 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
11023 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
11024 return ImGuiKeyOwner_NoOwner;
11025
11026 return owner_id;
11027 }
11028
11029 // TestKeyOwner(..., ID) : (owner == None || owner == ID)
11030 // TestKeyOwner(..., None) : (owner == None)
11031 // TestKeyOwner(..., Any) : no owner test
11032 // All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
11033 bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
11034 {
11035 if (!IsNamedKeyOrMod(key))
11036 return true;
11037
11038 ImGuiContext& g = *GImGui;
11039 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
11040 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
11041 return false;
11042
11043 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
11044 if (owner_id == ImGuiKeyOwner_Any)
11045 return (owner_data->LockThisFrame == false);
11046
11047 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
11048 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
11049 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
11050 if (owner_data->OwnerCurr != owner_id)
11051 {
11052 if (owner_data->LockThisFrame)
11053 return false;
11054 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
11055 return false;
11056 }
11057
11058 return true;
11059 }
11060
11061 // _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
11062 // When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
11063 // - SetKeyOwner(..., None) : clears owner
11064 // - SetKeyOwner(..., Any, !Lock) : illegal (assert)
11065 // - SetKeyOwner(..., Any or None, Lock) : set lock
11066 void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
11067 {
11068 ImGuiContext& g = *GImGui;
11069 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)
11070 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
11071 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
11072
11073 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
11074 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
11075
11076 // We cannot lock by default as it would likely break lots of legacy code.
11077 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
11078 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
11079 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
11080 }
11081
11082 // Rarely used helper
11083 void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
11084 {
11085 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
11086 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
11087 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
11088 if (key_chord & ImGuiMod_Super) { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
11089 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
11090 }
11091
11092 // This is more or less equivalent to:
11093 // if (IsItemHovered() || IsItemActive())
11094 // SetKeyOwner(key, GetItemID());
11095 // 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.
11096 // More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
11097 // 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.
11098 void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
11099 {
11100 ImGuiContext& g = *GImGui;
11101 ImGuiID id = g.LastItemData.ID;
11102 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
11103 return;
11104 if ((flags & ImGuiInputFlags_CondMask_) == 0)
11105 flags |= ImGuiInputFlags_CondDefault_;
11106 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
11107 {
11108 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
11109 SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
11110 }
11111 }
11112
11113 void ImGui::SetItemKeyOwner(ImGuiKey key)
11114 {
11115 SetItemKeyOwner(key, ImGuiInputFlags_None);
11116 }
11117
11118 // This is the only public API until we expose owner_id versions of the API as replacements.
11119 bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
11120 {
11121 return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
11122 }
11123
11124 // This is equivalent to comparing KeyMods + doing a IsKeyPressed()
11125 bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11126 {
11127 ImGuiContext& g = *GImGui;
11128 key_chord = FixupKeyChord(key_chord);
11129 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
11130 if (g.IO.KeyMods != mods)
11131 return false;
11132
11133 // Special storage location for mods
11134 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
11135 if (key == ImGuiKey_None)
11136 key = ConvertSingleModFlagToKey(mods);
11137 if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
11138 return false;
11139 return true;
11140 }
11141
11142 void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11143 {
11144 ImGuiContext& g = *GImGui;
11145 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
11146 g.NextItemData.Shortcut = key_chord;
11147 g.NextItemData.ShortcutFlags = flags;
11148 }
11149
11150 // Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
11151 void ImGui::ItemHandleShortcut(ImGuiID id)
11152 {
11153 ImGuiContext& g = *GImGui;
11154 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
11155 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
11156
11157 if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
11158 return;
11159 if (flags & ImGuiInputFlags_Tooltip)
11160 {
11161 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
11162 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
11163 }
11164 if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
11165 return;
11166
11167 // FIXME: Generalize Activation queue?
11168 g.NavActivateId = id; // Will effectively disable clipping.
11169 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
11170 //if (g.ActiveId == 0 || g.ActiveId == id)
11171 g.NavActivateDownId = g.NavActivatePressedId = id;
11172 NavHighlightActivated(id);
11173 }
11174
11175 bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11176 {
11177 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
11178 }
11179
11180 bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11181 {
11182 ImGuiContext& g = *GImGui;
11183 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
11184
11185 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
11186 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
11187 flags |= ImGuiInputFlags_RouteFocused;
11188
11189 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
11190 // Effectively makes Shortcut() always input-owner aware.
11191 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
11192 owner_id = GetRoutingIdFromOwnerId(owner_id);
11193
11194 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11195 return false;
11196
11197 // Submit route
11198 if (!SetShortcutRouting(key_chord, flags, owner_id))
11199 return false;
11200
11201 // Default repeat behavior for Shortcut()
11202 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
11203 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
11204 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
11205
11206 if (!IsKeyChordPressed(key_chord, flags, owner_id))
11207 return false;
11208
11209 // Claim mods during the press
11210 SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
11211
11212 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
11213 return true;
11214 }
11215
11216 //-----------------------------------------------------------------------------
11217 // [SECTION] ERROR CHECKING, STATE RECOVERY
11218 //-----------------------------------------------------------------------------
11219 // - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
11220 // - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11221 // - ErrorCheckNewFrameSanityChecks()
11222 // - ErrorCheckEndFrameSanityChecks()
11223 // - ErrorRecoveryStoreState()
11224 // - ErrorRecoveryTryToRecoverState()
11225 // - ErrorRecoveryTryToRecoverWindowState()
11226 // - ErrorLog()
11227 //-----------------------------------------------------------------------------
11228
11229 // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
11230 // Called by IMGUI_CHECKVERSION().
11231 // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
11232 // If this triggers you have mismatched headers and compiled code versions.
11233 // - It could be because of a build issue (using new headers with old compiled code)
11234 // - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
11235 // THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
11236 // Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
11237 // Otherwise it is possible that different compilation units would see different structure layout.
11238 // If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
11239 bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
11240 {
11241 bool error = false;
11242 if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
11243 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
11244 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
11245 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
11246 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
11247 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
11248 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
11249 return !error;
11250 }
11251
11252 // Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos()
11253 // to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing
11254 // windows, table column contents size used for auto-resizing columns, group size).
11255 // This was causing issues and ambiguities and we needed to retire that.
11256 // From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED.
11257 //
11258 // Previously this would make the window content size ~200x200:
11259 // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE
11260 // Instead, please submit an item:
11261 // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
11262 // Alternative:
11263 // Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
11264 //
11265 // The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item,
11266 // and with a position that would grow the parent contents size.
11267 //
11268 // Advanced:
11269 // - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos())
11270 // had a side-effect on layout! In particular this caused problem to compute group boundaries.
11271 // e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the
11272 // group to be taller because auto-sizing generally adds padding on bottom and right side.
11273 // - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect.
11274 // Using vertical alignment patterns would frequently trigger this sorts of issue.
11275 // - See https://github.com/ocornut/imgui/issues/5548 for more details.
11276 void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11277 {
11278 ImGuiContext& g = *GImGui;
11279 ImGuiWindow* window = g.CurrentWindow;
11280 IM_ASSERT(window->DC.IsSetPos);
11281 window->DC.IsSetPos = false;
11282 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
11283 return;
11284 if (window->SkipItems)
11285 return;
11286 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.");
11287
11288 // For reference, the old behavior was essentially:
11289 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11290 }
11291
11292 static void ImGui::ErrorCheckNewFrameSanityChecks()
11293 {
11294 ImGuiContext& g = *GImGui;
11295
11296 // Check user IM_ASSERT macro
11297 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
11298 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
11299 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
11300 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
11301 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
11302 if (true) IM_ASSERT(1); else IM_ASSERT(0);
11303
11304 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
11305 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
11306 #ifdef __EMSCRIPTEN__
11307 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
11308 g.IO.DeltaTime = 0.00001f;
11309 #endif
11310
11311 // Check user data
11312 // (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)
11313 IM_ASSERT(g.Initialized);
11314 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
11315 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
11316 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
11317 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
11318 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
11319 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
11320 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!");
11321 IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders.
11322 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
11323 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
11324 IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes);
11325
11326 // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
11327 if (g.IO.ConfigErrorRecovery)
11328 IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
11329
11330 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11331 if (g.IO.FontGlobalScale > 1.0f)
11332 IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!");
11333
11334 // Remap legacy names
11335 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
11336 {
11337 g.IO.ConfigNavMoveSetMousePos = true;
11338 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
11339 }
11340 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
11341 {
11342 g.IO.ConfigNavCaptureKeyboard = false;
11343 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
11344 }
11345 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts)
11346 {
11347 g.IO.ConfigDpiScaleFonts = true;
11348 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts;
11349 }
11350 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
11351 {
11352 g.IO.ConfigDpiScaleViewports = true;
11353 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports;
11354 }
11355
11356 // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
11357 if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
11358 g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
11359 if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
11360 g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); };
11361 #endif
11362
11363 // 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.
11364 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
11365 IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11366 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
11367 IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11368
11369 // Perform simple checks: multi-viewport and platform windows support
11370 if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
11371 {
11372 if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
11373 {
11374 IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
11375 IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
11376 IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
11377 IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
11378 IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
11379 IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
11380 IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
11381 IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
11382 IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
11383 if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
11384 IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
11385 }
11386 else
11387 {
11388 // Disable feature, our backends do not support it
11389 g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
11390 }
11391
11392 // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
11393 for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
11394 {
11395 IM_UNUSED(mon);
11396 IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
11397 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.");
11398 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
11399 }
11400 }
11401 }
11402
11403 static void ImGui::ErrorCheckEndFrameSanityChecks()
11404 {
11405 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
11406 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
11407 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
11408 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
11409 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
11410 // while still correctly asserting on mid-frame key press events.
11411 ImGuiContext& g = *GImGui;
11412 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
11413 IM_UNUSED(g);
11414 IM_UNUSED(key_mods);
11415 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
11416 IM_UNUSED(key_mods);
11417
11418 IM_ASSERT(g.CurrentWindowStack.Size == 1);
11419 IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
11420 }
11421
11422 // Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
11423 void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
11424 {
11425 ImGuiContext& g = *GImGui;
11426 state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
11427 state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
11428 state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
11429 state_out->SizeOfColorStack = (short)g.ColorStack.Size;
11430 state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
11431 state_out->SizeOfFontStack = (short)g.FontStack.Size;
11432 state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
11433 state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
11434 state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
11435 state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
11436 state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
11437 }
11438
11439 // Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
11440 // Called by e.g. EndFrame() but may be called for manual recovery.
11441 // Attempt to recover full window stack.
11442 void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
11443 {
11444 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
11445 ImGuiContext& g = *GImGui;
11446 while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
11447 {
11448 // Recap:
11449 // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
11450 // - Always call a matching End() for each Begin() call, regardless of its return value!
11451 // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
11452 // - We will fix that in a future major update.
11453 ImGuiWindow* window = g.CurrentWindow;
11454 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11455 {
11456 if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
11457 {
11458 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11459 EndTable();
11460 }
11461 else
11462 {
11463 IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
11464 EndChild();
11465 }
11466 }
11467 else
11468 {
11469 IM_ASSERT_USER_ERROR(0, "Missing End()");
11470 End();
11471 }
11472 }
11473 if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
11474 ErrorRecoveryTryToRecoverWindowState(state_in);
11475 }
11476
11477 // Called by e.g. End() but may be called for manual recovery.
11478 // Read '// Error Handling [BETA]' block in imgui_internal.h for details.
11479 // Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
11480 void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
11481 {
11482 ImGuiContext& g = *GImGui;
11483
11484 while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
11485 {
11486 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11487 EndTable();
11488 }
11489
11490 ImGuiWindow* window = g.CurrentWindow;
11491
11492 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
11493 while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
11494 {
11495 IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
11496 EndTabBar();
11497 }
11498 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
11499 {
11500 IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
11501 EndMultiSelect();
11502 }
11503 if (window->DC.MenuBarAppending) //-V1044
11504 {
11505 IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()");
11506 EndMenuBar();
11507 }
11508 while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
11509 {
11510 IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
11511 TreePop();
11512 }
11513 while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
11514 {
11515 IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
11516 EndGroup();
11517 }
11518 IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
11519 while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
11520 {
11521 IM_ASSERT_USER_ERROR(0, "Missing PopID()");
11522 PopID();
11523 }
11524 while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
11525 {
11526 IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
11527 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11528 EndDisabled();
11529 else
11530 {
11531 EndDisabledOverrideReenable();
11532 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
11533 }
11534 }
11535 IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
11536 while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
11537 {
11538 IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
11539 PopStyleColor();
11540 }
11541 while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
11542 {
11543 IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
11544 PopItemFlag();
11545 }
11546 while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
11547 {
11548 IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
11549 PopStyleVar();
11550 }
11551 while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
11552 {
11553 IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
11554 PopFont();
11555 }
11556 while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
11557 {
11558 IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
11559 PopFocusScope();
11560 }
11561 //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
11562 }
11563
11564 bool ImGui::ErrorLog(const char* msg)
11565 {
11566 ImGuiContext& g = *GImGui;
11567
11568 // Output to debug log
11569 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11570 ImGuiWindow* window = g.CurrentWindow;
11571
11572 if (g.IO.ConfigErrorRecoveryEnableDebugLog)
11573 {
11574 if (g.ErrorFirst)
11575 IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
11576 g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
11577 IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
11578 }
11579 g.ErrorFirst = false;
11580
11581 // Output to tooltip
11582 if (g.IO.ConfigErrorRecoveryEnableTooltip)
11583 {
11584 if (g.WithinFrameScope && BeginErrorTooltip())
11585 {
11586 if (g.ErrorCountCurrentFrame < 20)
11587 {
11588 Text("In window '%s': %s", window ? window->Name : "NULL", msg);
11589 if (window && (!window->IsFallbackWindow || window->WasActive))
11590 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
11591 }
11592 if (g.ErrorCountCurrentFrame == 20)
11593 Text("(and more errors)");
11594 // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
11595 EndErrorTooltip();
11596 }
11597 g.ErrorCountCurrentFrame++;
11598 }
11599 #endif
11600
11601 // Output to callback
11602 if (g.ErrorCallback != NULL)
11603 g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
11604
11605 // Return whether we should assert
11606 return g.IO.ConfigErrorRecoveryEnableAssert;
11607 }
11608
11609 void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
11610 {
11611 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11612 ImGuiContext& g = *GImGui;
11613 if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false)
11614 g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
11615 if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
11616 {
11617 Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
11618 BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
11619 BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
11620 //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.
11621 BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
11622 Separator();
11623 if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker)
11624 {
11625 Text("(Hold CTRL to: use ");
11626 SameLine(0.0f, 0.0f);
11627 if (SmallButton("Item Picker"))
11628 DebugStartItemPicker();
11629 SameLine(0.0f, 0.0f);
11630 Text(" to break in item call-stack, or ");
11631 }
11632 else
11633 {
11634 Text("(Hold CTRL to ");
11635 }
11636 SameLine(0.0f, 0.0f);
11637 if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
11638 g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
11639 SameLine(0.0f, 0.0f);
11640 Text(")");
11641 EndErrorTooltip();
11642 }
11643
11644 if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
11645 {
11646 Separator();
11647 Text("(Hold CTRL to:");
11648 SameLine();
11649 if (SmallButton("Enable Asserts"))
11650 g.IO.ConfigErrorRecoveryEnableAssert = true;
11651 //SameLine();
11652 //if (SmallButton("Hide Error Tooltips"))
11653 // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
11654 SameLine(0, 0);
11655 Text(")");
11656 EndErrorTooltip();
11657 }
11658 #endif
11659 }
11660
11661 // Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it.
11662 bool ImGui::BeginErrorTooltip()
11663 {
11664 ImGuiContext& g = *GImGui;
11665 ImGuiWindow* window = FindWindowByName("##Tooltip_Error");
11666 const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
11667 PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.15f));
11668 if (use_locked_pos)
11669 SetNextWindowPos(g.ErrorTooltipLockedPos);
11670 bool is_visible = Begin("##Tooltip_Error", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
11671 PopStyleColor();
11672 if (is_visible && g.CurrentWindow->BeginCount == 1)
11673 {
11674 SeparatorText("MESSAGE FROM DEAR IMGUI");
11675 BringWindowToDisplayFront(g.CurrentWindow);
11676 BringWindowToFocusFront(g.CurrentWindow);
11677 g.ErrorTooltipLockedPos = GetWindowPos();
11678 }
11679 else if (!is_visible)
11680 {
11681 End();
11682 }
11683 return is_visible;
11684 }
11685
11686 void ImGui::EndErrorTooltip()
11687 {
11688 End();
11689 }
11690
11691 //-----------------------------------------------------------------------------
11692 // [SECTION] ITEM SUBMISSION
11693 //-----------------------------------------------------------------------------
11694 // - KeepAliveID()
11695 // - ItemAdd()
11696 //-----------------------------------------------------------------------------
11697
11698 // 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().
11699 void ImGui::KeepAliveID(ImGuiID id)
11700 {
11701 ImGuiContext& g = *GImGui;
11702 if (g.ActiveId == id)
11703 g.ActiveIdIsAlive = id;
11704 if (g.DeactivatedItemData.ID == id)
11705 g.DeactivatedItemData.IsAlive = true;
11706 }
11707
11708 // Declare item bounding box for clipping and interaction.
11709 // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
11710 // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
11711 // THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
11712 IM_MSVC_RUNTIME_CHECKS_OFF
11713 bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
11714 {
11715 ImGuiContext& g = *GImGui;
11716 ImGuiWindow* window = g.CurrentWindow;
11717
11718 // Set item data
11719 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
11720 g.LastItemData.ID = id;
11721 g.LastItemData.Rect = bb;
11722 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
11723 g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
11724 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
11725 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
11726
11727 if (id != 0)
11728 {
11729 KeepAliveID(id);
11730
11731 // Directional navigation processing
11732 // Runs prior to clipping early-out
11733 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
11734 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
11735 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
11736 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
11737 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
11738 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
11739 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
11740 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
11741 if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
11742 {
11743 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
11744 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
11745 if (g.NavId == id || g.NavAnyRequest)
11746 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
11747 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
11748 NavProcessItem();
11749 }
11750
11751 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
11752 ItemHandleShortcut(id);
11753 }
11754
11755 // Lightweight clear of SetNextItemXXX data.
11756 g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
11757 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
11758
11759 #ifdef IMGUI_ENABLE_TEST_ENGINE
11760 if (id != 0)
11761 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
11762 #endif
11763
11764 // Clipping test
11765 // (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')
11766 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
11767 const bool is_rect_visible = bb.Overlaps(window->ClipRect);
11768 if (!is_rect_visible)
11769 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
11770 if (!g.ItemUnclipByLog)
11771 return false;
11772
11773 // [DEBUG]
11774 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11775 if (id != 0)
11776 {
11777 if (id == g.DebugLocateId)
11778 DebugLocateItemResolveWithLastItem();
11779
11780 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
11781 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
11782 // READ THE FAQ: https://dearimgui.com/faq
11783 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!");
11784
11785 // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED.
11786 // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd().
11787 #ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
11788 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0)
11789 {
11790 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.
11791 int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1);
11792 if (*p_alive == g.FrameCount)
11793 *p_highlight = g.FrameCount;
11794 *p_alive = g.FrameCount;
11795 if (*p_highlight >= g.FrameCount - 1)
11796 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);
11797 }
11798 #endif
11799 }
11800 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
11801 //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
11802 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
11803 #endif
11804
11805 if (id != 0 && g.DeactivatedItemData.ID == id)
11806 g.DeactivatedItemData.ElapseFrame = g.FrameCount;
11807
11808 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
11809 if (is_rect_visible)
11810 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
11811 if (IsMouseHoveringRect(bb.Min, bb.Max))
11812 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
11813 return true;
11814 }
11815 IM_MSVC_RUNTIME_CHECKS_RESTORE
11816
11817 //-----------------------------------------------------------------------------
11818 // [SECTION] LAYOUT
11819 //-----------------------------------------------------------------------------
11820 // - ItemSize()
11821 // - SameLine()
11822 // - GetCursorScreenPos()
11823 // - SetCursorScreenPos()
11824 // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
11825 // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
11826 // - GetCursorStartPos()
11827 // - Indent()
11828 // - Unindent()
11829 // - SetNextItemWidth()
11830 // - PushItemWidth()
11831 // - PushMultiItemsWidths()
11832 // - PopItemWidth()
11833 // - CalcItemWidth()
11834 // - CalcItemSize()
11835 // - GetTextLineHeight()
11836 // - GetTextLineHeightWithSpacing()
11837 // - GetFrameHeight()
11838 // - GetFrameHeightWithSpacing()
11839 // - GetContentRegionMax()
11840 // - GetContentRegionAvail(),
11841 // - BeginGroup()
11842 // - EndGroup()
11843 // Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11844 //-----------------------------------------------------------------------------
11845
11846 // Advance cursor given item size for layout.
11847 // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11848 // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11849 // THIS IS IN THE PERFORMANCE CRITICAL PATH.
11850 IM_MSVC_RUNTIME_CHECKS_OFF
11851 void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11852 {
11853 ImGuiContext& g = *GImGui;
11854 ImGuiWindow* window = g.CurrentWindow;
11855 if (window->SkipItems)
11856 return;
11857
11858 // We increase the height in this function to accommodate for baseline offset.
11859 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11860 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11861 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11862
11863 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11864 const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
11865
11866 // Always align ourselves on pixel boundaries
11867 //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]
11868 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11869 window->DC.CursorPosPrevLine.y = line_y1;
11870 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
11871 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
11872 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
11873 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11874 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11875
11876 window->DC.PrevLineSize.y = line_height;
11877 window->DC.CurrLineSize.y = 0.0f;
11878 window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
11879 window->DC.CurrLineTextBaseOffset = 0.0f;
11880 window->DC.IsSameLine = window->DC.IsSetPos = false;
11881
11882 // Horizontal layout mode
11883 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11884 SameLine();
11885 }
11886 IM_MSVC_RUNTIME_CHECKS_RESTORE
11887
11888 // Gets back to previous line and continue with horizontal layout
11889 // offset_from_start_x == 0 : follow right after previous item
11890 // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11891 // spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11892 // spacing_w >= 0 : enforce spacing amount
11893 void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11894 {
11895 ImGuiContext& g = *GImGui;
11896 ImGuiWindow* window = g.CurrentWindow;
11897 if (window->SkipItems)
11898 return;
11899
11900 if (offset_from_start_x != 0.0f)
11901 {
11902 if (spacing_w < 0.0f)
11903 spacing_w = 0.0f;
11904 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11905 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11906 }
11907 else
11908 {
11909 if (spacing_w < 0.0f)
11910 spacing_w = g.Style.ItemSpacing.x;
11911 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11912 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11913 }
11914 window->DC.CurrLineSize = window->DC.PrevLineSize;
11915 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11916 window->DC.IsSameLine = true;
11917 }
11918
11919 ImVec2 ImGui::GetCursorScreenPos()
11920 {
11921 ImGuiWindow* window = GetCurrentWindowRead();
11922 return window->DC.CursorPos;
11923 }
11924
11925 void ImGui::SetCursorScreenPos(const ImVec2& pos)
11926 {
11927 ImGuiWindow* window = GetCurrentWindow();
11928 window->DC.CursorPos = pos;
11929 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11930 window->DC.IsSetPos = true;
11931 }
11932
11933 // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11934 // 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'.
11935 ImVec2 ImGui::GetCursorPos()
11936 {
11937 ImGuiWindow* window = GetCurrentWindowRead();
11938 return window->DC.CursorPos - window->Pos + window->Scroll;
11939 }
11940
11941 float ImGui::GetCursorPosX()
11942 {
11943 ImGuiWindow* window = GetCurrentWindowRead();
11944 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11945 }
11946
11947 float ImGui::GetCursorPosY()
11948 {
11949 ImGuiWindow* window = GetCurrentWindowRead();
11950 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11951 }
11952
11953 void ImGui::SetCursorPos(const ImVec2& local_pos)
11954 {
11955 ImGuiWindow* window = GetCurrentWindow();
11956 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11957 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11958 window->DC.IsSetPos = true;
11959 }
11960
11961 void ImGui::SetCursorPosX(float x)
11962 {
11963 ImGuiWindow* window = GetCurrentWindow();
11964 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11965 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11966 window->DC.IsSetPos = true;
11967 }
11968
11969 void ImGui::SetCursorPosY(float y)
11970 {
11971 ImGuiWindow* window = GetCurrentWindow();
11972 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11973 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11974 window->DC.IsSetPos = true;
11975 }
11976
11977 ImVec2 ImGui::GetCursorStartPos()
11978 {
11979 ImGuiWindow* window = GetCurrentWindowRead();
11980 return window->DC.CursorStartPos - window->Pos;
11981 }
11982
11983 void ImGui::Indent(float indent_w)
11984 {
11985 ImGuiContext& g = *GImGui;
11986 ImGuiWindow* window = GetCurrentWindow();
11987 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11988 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11989 }
11990
11991 void ImGui::Unindent(float indent_w)
11992 {
11993 ImGuiContext& g = *GImGui;
11994 ImGuiWindow* window = GetCurrentWindow();
11995 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11996 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11997 }
11998
11999 // Affect large frame+labels widgets only.
12000 void ImGui::SetNextItemWidth(float item_width)
12001 {
12002 ImGuiContext& g = *GImGui;
12003 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
12004 g.NextItemData.Width = item_width;
12005 }
12006
12007 // FIXME: Remove the == 0.0f behavior?
12008 void ImGui::PushItemWidth(float item_width)
12009 {
12010 ImGuiContext& g = *GImGui;
12011 ImGuiWindow* window = g.CurrentWindow;
12012 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
12013 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
12014 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
12015 }
12016
12017 void ImGui::PushMultiItemsWidths(int components, float w_full)
12018 {
12019 ImGuiContext& g = *GImGui;
12020 ImGuiWindow* window = g.CurrentWindow;
12021 IM_ASSERT(components > 0);
12022 const ImGuiStyle& style = g.Style;
12023 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
12024 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
12025 float prev_split = w_items;
12026 for (int i = components - 1; i > 0; i--)
12027 {
12028 float next_split = IM_TRUNC(w_items * i / components);
12029 window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
12030 prev_split = next_split;
12031 }
12032 window->DC.ItemWidth = ImMax(prev_split, 1.0f);
12033 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
12034 }
12035
12036 void ImGui::PopItemWidth()
12037 {
12038 ImGuiContext& g = *GImGui;
12039 ImGuiWindow* window = g.CurrentWindow;
12040 if (window->DC.ItemWidthStack.Size <= 0)
12041 {
12042 IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
12043 return;
12044 }
12045 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
12046 window->DC.ItemWidthStack.pop_back();
12047 }
12048
12049 // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
12050 // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
12051 float ImGui::CalcItemWidth()
12052 {
12053 ImGuiContext& g = *GImGui;
12054 ImGuiWindow* window = g.CurrentWindow;
12055 float w;
12056 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
12057 w = g.NextItemData.Width;
12058 else
12059 w = window->DC.ItemWidth;
12060 if (w < 0.0f)
12061 {
12062 float region_avail_x = GetContentRegionAvail().x;
12063 w = ImMax(1.0f, region_avail_x + w);
12064 }
12065 w = IM_TRUNC(w);
12066 return w;
12067 }
12068
12069 // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
12070 // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
12071 // Note that only CalcItemWidth() is publicly exposed.
12072 // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
12073 ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
12074 {
12075 ImVec2 avail;
12076 if (size.x < 0.0f || size.y < 0.0f)
12077 avail = GetContentRegionAvail();
12078
12079 if (size.x == 0.0f)
12080 size.x = default_w;
12081 else if (size.x < 0.0f)
12082 size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting
12083
12084 if (size.y == 0.0f)
12085 size.y = default_h;
12086 else if (size.y < 0.0f)
12087 size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting
12088
12089 return size;
12090 }
12091
12092 float ImGui::GetTextLineHeight()
12093 {
12094 ImGuiContext& g = *GImGui;
12095 return g.FontSize;
12096 }
12097
12098 float ImGui::GetTextLineHeightWithSpacing()
12099 {
12100 ImGuiContext& g = *GImGui;
12101 return g.FontSize + g.Style.ItemSpacing.y;
12102 }
12103
12104 float ImGui::GetFrameHeight()
12105 {
12106 ImGuiContext& g = *GImGui;
12107 return g.FontSize + g.Style.FramePadding.y * 2.0f;
12108 }
12109
12110 float ImGui::GetFrameHeightWithSpacing()
12111 {
12112 ImGuiContext& g = *GImGui;
12113 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
12114 }
12115
12116 ImVec2 ImGui::GetContentRegionAvail()
12117 {
12118 ImGuiContext& g = *GImGui;
12119 ImGuiWindow* window = g.CurrentWindow;
12120 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
12121 return mx - window->DC.CursorPos;
12122 }
12123
12124 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
12125
12126 // You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
12127 // They are bizarre local-coordinates which don't play well with scrolling.
12128 ImVec2 ImGui::GetContentRegionMax()
12129 {
12130 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
12131 }
12132
12133 ImVec2 ImGui::GetWindowContentRegionMin()
12134 {
12135 ImGuiWindow* window = GImGui->CurrentWindow;
12136 return window->ContentRegionRect.Min - window->Pos;
12137 }
12138
12139 ImVec2 ImGui::GetWindowContentRegionMax()
12140 {
12141 ImGuiWindow* window = GImGui->CurrentWindow;
12142 return window->ContentRegionRect.Max - window->Pos;
12143 }
12144 #endif
12145
12146 // 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.)
12147 // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
12148 // FIXME-OPT: Could we safely early out on ->SkipItems?
12149 void ImGui::BeginGroup()
12150 {
12151 ImGuiContext& g = *GImGui;
12152 ImGuiWindow* window = g.CurrentWindow;
12153
12154 g.GroupStack.resize(g.GroupStack.Size + 1);
12155 ImGuiGroupData& group_data = g.GroupStack.back();
12156 group_data.WindowID = window->ID;
12157 group_data.BackupCursorPos = window->DC.CursorPos;
12158 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
12159 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
12160 group_data.BackupIndent = window->DC.Indent;
12161 group_data.BackupGroupOffset = window->DC.GroupOffset;
12162 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
12163 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
12164 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
12165 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
12166 group_data.BackupIsSameLine = window->DC.IsSameLine;
12167 group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive;
12168 group_data.EmitItem = true;
12169
12170 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
12171 window->DC.Indent = window->DC.GroupOffset;
12172 window->DC.CursorMaxPos = window->DC.CursorPos;
12173 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
12174 if (g.LogEnabled)
12175 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12176 }
12177
12178 void ImGui::EndGroup()
12179 {
12180 ImGuiContext& g = *GImGui;
12181 ImGuiWindow* window = g.CurrentWindow;
12182 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
12183
12184 ImGuiGroupData& group_data = g.GroupStack.back();
12185 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
12186
12187 if (window->DC.IsSetPos)
12188 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
12189
12190 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
12191 ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos));
12192 window->DC.CursorPos = group_data.BackupCursorPos;
12193 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
12194 window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max);
12195 window->DC.Indent = group_data.BackupIndent;
12196 window->DC.GroupOffset = group_data.BackupGroupOffset;
12197 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
12198 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
12199 window->DC.IsSameLine = group_data.BackupIsSameLine;
12200 if (g.LogEnabled)
12201 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12202
12203 if (!group_data.EmitItem)
12204 {
12205 g.GroupStack.pop_back();
12206 return;
12207 }
12208
12209 window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
12210 ItemSize(group_bb.GetSize());
12211 ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
12212
12213 // 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.
12214 // 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.
12215 // Also if you grep for LastItemId you'll notice it is only used in that context.
12216 // (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.)
12217 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
12218 const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true);
12219 if (group_contains_curr_active_id)
12220 g.LastItemData.ID = g.ActiveId;
12221 else if (group_contains_deactivated_id)
12222 g.LastItemData.ID = g.DeactivatedItemData.ID;
12223 g.LastItemData.Rect = group_bb;
12224
12225 // Forward Hovered flag
12226 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
12227 if (group_contains_curr_hovered_id)
12228 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
12229
12230 // Forward Edited flag
12231 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
12232 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
12233
12234 // Forward Deactivated flag
12235 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
12236 if (group_contains_deactivated_id)
12237 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
12238
12239 g.GroupStack.pop_back();
12240 if (g.DebugShowGroupRects)
12241 window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
12242 }
12243
12244
12245 //-----------------------------------------------------------------------------
12246 // [SECTION] SCROLLING
12247 //-----------------------------------------------------------------------------
12248
12249 // Helper to snap on edges when aiming at an item very close to the edge,
12250 // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
12251 // When we refactor the scrolling API this may be configurable with a flag?
12252 // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
12253 static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
12254 {
12255 if (target <= snap_min + snap_threshold)
12256 return ImLerp(snap_min, target, center_ratio);
12257 if (target >= snap_max - snap_threshold)
12258 return ImLerp(target, snap_max, center_ratio);
12259 return target;
12260 }
12261
12262 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
12263 {
12264 ImVec2 scroll = window->Scroll;
12265 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
12266 for (int axis = 0; axis < 2; axis++)
12267 {
12268 if (window->ScrollTarget[axis] < FLT_MAX)
12269 {
12270 float center_ratio = window->ScrollTargetCenterRatio[axis];
12271 float scroll_target = window->ScrollTarget[axis];
12272 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
12273 {
12274 float snap_min = 0.0f;
12275 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
12276 scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
12277 }
12278 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
12279 }
12280 scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f));
12281 if (!window->Collapsed && !window->SkipItems)
12282 scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
12283 }
12284 return scroll;
12285 }
12286
12287 void ImGui::ScrollToItem(ImGuiScrollFlags flags)
12288 {
12289 ImGuiContext& g = *GImGui;
12290 ImGuiWindow* window = g.CurrentWindow;
12291 ScrollToRectEx(window, g.LastItemData.NavRect, flags);
12292 }
12293
12294 void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12295 {
12296 ScrollToRectEx(window, item_rect, flags);
12297 }
12298
12299 // Scroll to keep newly navigated item fully into view
12300 ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12301 {
12302 ImGuiContext& g = *GImGui;
12303 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
12304 scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
12305 scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
12306 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
12307 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
12308
12309 // Check that only one behavior is selected per axis
12310 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
12311 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
12312
12313 // Defaults
12314 ImGuiScrollFlags in_flags = flags;
12315 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
12316 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
12317 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
12318 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
12319
12320 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
12321 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
12322 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;
12323 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;
12324
12325 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
12326 {
12327 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
12328 SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
12329 else if (item_rect.Max.x >= scroll_rect.Max.x)
12330 SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
12331 }
12332 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
12333 {
12334 if (can_be_fully_visible_x)
12335 SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
12336 else
12337 SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
12338 }
12339
12340 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
12341 {
12342 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
12343 SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
12344 else if (item_rect.Max.y >= scroll_rect.Max.y)
12345 SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
12346 }
12347 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
12348 {
12349 if (can_be_fully_visible_y)
12350 SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
12351 else
12352 SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
12353 }
12354
12355 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12356 ImVec2 delta_scroll = next_scroll - window->Scroll;
12357
12358 // Also scroll parent window to keep us into view if necessary
12359 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
12360 {
12361 // FIXME-SCROLL: May be an option?
12362 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
12363 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
12364 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
12365 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
12366 delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
12367 }
12368
12369 return delta_scroll;
12370 }
12371
12372 float ImGui::GetScrollX()
12373 {
12374 ImGuiWindow* window = GImGui->CurrentWindow;
12375 return window->Scroll.x;
12376 }
12377
12378 float ImGui::GetScrollY()
12379 {
12380 ImGuiWindow* window = GImGui->CurrentWindow;
12381 return window->Scroll.y;
12382 }
12383
12384 float ImGui::GetScrollMaxX()
12385 {
12386 ImGuiWindow* window = GImGui->CurrentWindow;
12387 return window->ScrollMax.x;
12388 }
12389
12390 float ImGui::GetScrollMaxY()
12391 {
12392 ImGuiWindow* window = GImGui->CurrentWindow;
12393 return window->ScrollMax.y;
12394 }
12395
12396 void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
12397 {
12398 window->ScrollTarget.x = scroll_x;
12399 window->ScrollTargetCenterRatio.x = 0.0f;
12400 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12401 }
12402
12403 void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
12404 {
12405 window->ScrollTarget.y = scroll_y;
12406 window->ScrollTargetCenterRatio.y = 0.0f;
12407 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12408 }
12409
12410 void ImGui::SetScrollX(float scroll_x)
12411 {
12412 ImGuiContext& g = *GImGui;
12413 SetScrollX(g.CurrentWindow, scroll_x);
12414 }
12415
12416 void ImGui::SetScrollY(float scroll_y)
12417 {
12418 ImGuiContext& g = *GImGui;
12419 SetScrollY(g.CurrentWindow, scroll_y);
12420 }
12421
12422 // Note that a local position will vary depending on initial scroll value,
12423 // This is a little bit confusing so bear with us:
12424 // - local_pos = (absolution_pos - window->Pos)
12425 // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
12426 // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
12427 // - They mostly exist because of legacy API.
12428 // Following the rules above, when trying to work with scrolling code, consider that:
12429 // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
12430 // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
12431 // 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
12432 void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
12433 {
12434 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
12435 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
12436 window->ScrollTargetCenterRatio.x = center_x_ratio;
12437 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12438 }
12439
12440 void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
12441 {
12442 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
12443 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
12444 window->ScrollTargetCenterRatio.y = center_y_ratio;
12445 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12446 }
12447
12448 void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
12449 {
12450 ImGuiContext& g = *GImGui;
12451 SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
12452 }
12453
12454 void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
12455 {
12456 ImGuiContext& g = *GImGui;
12457 SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
12458 }
12459
12460 // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
12461 void ImGui::SetScrollHereX(float center_x_ratio)
12462 {
12463 ImGuiContext& g = *GImGui;
12464 ImGuiWindow* window = g.CurrentWindow;
12465 float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
12466 float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
12467 SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
12468
12469 // Tweak: snap on edges when aiming at an item very close to the edge
12470 window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
12471 }
12472
12473 // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
12474 void ImGui::SetScrollHereY(float center_y_ratio)
12475 {
12476 ImGuiContext& g = *GImGui;
12477 ImGuiWindow* window = g.CurrentWindow;
12478 float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
12479 float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
12480 SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
12481
12482 // Tweak: snap on edges when aiming at an item very close to the edge
12483 window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
12484 }
12485
12486 //-----------------------------------------------------------------------------
12487 // [SECTION] TOOLTIPS
12488 //-----------------------------------------------------------------------------
12489
12490 bool ImGui::BeginTooltip()
12491 {
12492 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
12493 }
12494
12495 bool ImGui::BeginItemTooltip()
12496 {
12497 if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12498 return false;
12499 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
12500 }
12501
12502 bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
12503 {
12504 ImGuiContext& g = *GImGui;
12505
12506 const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
12507 if (is_dragdrop_tooltip)
12508 {
12509 // Drag and Drop tooltips are positioning differently than other tooltips:
12510 // - offset visibility to increase visibility around mouse.
12511 // - never clamp within outer viewport boundary.
12512 // We call SetNextWindowPos() to enforce position and disable clamping.
12513 // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones).
12514 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
12515 const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
12516 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12517 {
12518 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);
12519 ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
12520 SetNextWindowPos(tooltip_pos, ImGuiCond_None, tooltip_pivot);
12521 }
12522
12523 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
12524 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
12525 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
12526 }
12527
12528 const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
12529 char window_name[32];
12530 ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, g.TooltipOverrideCount);
12531 if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active)
12532 {
12533 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
12534 //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
12535 SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
12536 ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, ++g.TooltipOverrideCount);
12537 }
12538
12539 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
12540 Begin(window_name, NULL, flags | extra_window_flags);
12541 // 2023-03-09: Added bool return value to the API, but currently always returning true.
12542 // If this ever returns false we need to update BeginDragDropSource() accordingly.
12543 //if (!ret)
12544 // End();
12545 //return ret;
12546 return true;
12547 }
12548
12549 void ImGui::EndTooltip()
12550 {
12551 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
12552 End();
12553 }
12554
12555 void ImGui::SetTooltip(const char* fmt, ...)
12556 {
12557 va_list args;
12558 va_start(args, fmt);
12559 SetTooltipV(fmt, args);
12560 va_end(args);
12561 }
12562
12563 void ImGui::SetTooltipV(const char* fmt, va_list args)
12564 {
12565 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
12566 return;
12567 TextV(fmt, args);
12568 EndTooltip();
12569 }
12570
12571 // Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
12572 // Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
12573 void ImGui::SetItemTooltip(const char* fmt, ...)
12574 {
12575 va_list args;
12576 va_start(args, fmt);
12577 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12578 SetTooltipV(fmt, args);
12579 va_end(args);
12580 }
12581
12582 void ImGui::SetItemTooltipV(const char* fmt, va_list args)
12583 {
12584 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12585 SetTooltipV(fmt, args);
12586 }
12587
12588
12589 //-----------------------------------------------------------------------------
12590 // [SECTION] POPUPS
12591 //-----------------------------------------------------------------------------
12592
12593 // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
12594 bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
12595 {
12596 ImGuiContext& g = *GImGui;
12597 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
12598 {
12599 // Return true if any popup is open at the current BeginPopup() level of the popup stack
12600 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
12601 IM_ASSERT(id == 0);
12602 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12603 return g.OpenPopupStack.Size > 0;
12604 else
12605 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
12606 }
12607 else
12608 {
12609 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12610 {
12611 // Return true if the popup is open anywhere in the popup stack
12612 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12613 if (popup_data.PopupId == id)
12614 return true;
12615 return false;
12616 }
12617 else
12618 {
12619 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
12620 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
12621 }
12622 }
12623 }
12624
12625 bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
12626 {
12627 ImGuiContext& g = *GImGui;
12628 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
12629 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
12630 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
12631 return IsPopupOpen(id, popup_flags);
12632 }
12633
12634 // Also see FindBlockingModal(NULL)
12635 ImGuiWindow* ImGui::GetTopMostPopupModal()
12636 {
12637 ImGuiContext& g = *GImGui;
12638 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12639 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12640 if (popup->Flags & ImGuiWindowFlags_Modal)
12641 return popup;
12642 return NULL;
12643 }
12644
12645 // See Demo->Stacked Modal to confirm what this is for.
12646 ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
12647 {
12648 ImGuiContext& g = *GImGui;
12649 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12650 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12651 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
12652 return popup;
12653 return NULL;
12654 }
12655
12656
12657 // When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
12658 // should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
12659 // In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
12660 // - WindowA // FindBlockingModal() returns Modal1
12661 // - WindowB // .. returns Modal1
12662 // - Modal1 // .. returns Modal2
12663 // - WindowC // .. returns Modal2
12664 // - WindowD // .. returns Modal2
12665 // - Modal2 // .. returns Modal2
12666 // - WindowE // .. returns NULL
12667 // Notes:
12668 // - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
12669 // Only difference is here we check for ->Active/WasActive but it may be unnecessary.
12670 ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
12671 {
12672 ImGuiContext& g = *GImGui;
12673 if (g.OpenPopupStack.Size <= 0)
12674 return NULL;
12675
12676 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
12677 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12678 {
12679 ImGuiWindow* popup_window = popup_data.Window;
12680 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
12681 continue;
12682 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.
12683 continue;
12684 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
12685 return popup_window;
12686 if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
12687 continue;
12688 return popup_window; // Place window right below first block modal
12689 }
12690 return NULL;
12691 }
12692
12693 void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
12694 {
12695 ImGuiContext& g = *GImGui;
12696 ImGuiID id = g.CurrentWindow->GetID(str_id);
12697 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
12698 OpenPopupEx(id, popup_flags);
12699 }
12700
12701 void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
12702 {
12703 OpenPopupEx(id, popup_flags);
12704 }
12705
12706 // Mark popup as open (toggle toward open state).
12707 // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
12708 // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
12709 // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
12710 void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
12711 {
12712 ImGuiContext& g = *GImGui;
12713 ImGuiWindow* parent_window = g.CurrentWindow;
12714 const int current_stack_size = g.BeginPopupStack.Size;
12715
12716 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
12717 if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
12718 return;
12719
12720 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
12721 popup_ref.PopupId = id;
12722 popup_ref.Window = NULL;
12723 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
12724 popup_ref.OpenFrameCount = g.FrameCount;
12725 popup_ref.OpenParentId = parent_window->IDStack.back();
12726 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
12727 popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
12728
12729 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
12730 if (g.OpenPopupStack.Size < current_stack_size + 1)
12731 {
12732 g.OpenPopupStack.push_back(popup_ref);
12733 }
12734 else
12735 {
12736 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
12737 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
12738 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
12739 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
12740 bool keep_existing = false;
12741 if (g.OpenPopupStack[current_stack_size].PopupId == id)
12742 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
12743 keep_existing = true;
12744 if (keep_existing)
12745 {
12746 // No reopen
12747 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
12748 }
12749 else
12750 {
12751 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
12752 ClosePopupToLevel(current_stack_size, true);
12753 g.OpenPopupStack.push_back(popup_ref);
12754 }
12755
12756 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
12757 // This is equivalent to what ClosePopupToLevel() does.
12758 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
12759 // FocusWindow(parent_window);
12760 }
12761 }
12762
12763 // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
12764 // This function closes any popups that are over 'ref_window'.
12765 void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
12766 {
12767 ImGuiContext& g = *GImGui;
12768 if (g.OpenPopupStack.Size == 0)
12769 return;
12770
12771 // Don't close our own child popup windows.
12772 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
12773 int popup_count_to_keep = 0;
12774 if (ref_window)
12775 {
12776 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
12777 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
12778 {
12779 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
12780 if (!popup.Window)
12781 continue;
12782 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
12783
12784 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
12785 // - Clicking/Focusing Window2 won't close Popup1:
12786 // Window -> Popup1 -> Window2(Ref)
12787 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
12788 // Window -> Popup1(Ref) -> Popup2 -> Popup3
12789 // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
12790 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
12791 // We step through every popup from bottom to top to validate their position relative to reference window.
12792 bool ref_window_is_descendent_of_popup = false;
12793 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
12794 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
12795 //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
12796 if (IsWindowWithinBeginStackOf(ref_window, popup_window))
12797 {
12798 ref_window_is_descendent_of_popup = true;
12799 break;
12800 }
12801 if (!ref_window_is_descendent_of_popup)
12802 break;
12803 }
12804 }
12805 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
12806 {
12807 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
12808 ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
12809 }
12810 }
12811
12812 void ImGui::ClosePopupsExceptModals()
12813 {
12814 ImGuiContext& g = *GImGui;
12815
12816 int popup_count_to_keep;
12817 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
12818 {
12819 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
12820 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
12821 break;
12822 }
12823 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
12824 ClosePopupToLevel(popup_count_to_keep, true);
12825 }
12826
12827 void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
12828 {
12829 ImGuiContext& g = *GImGui;
12830 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
12831 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
12832 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)
12833 for (int n = remaining; n < g.OpenPopupStack.Size; n++)
12834 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);
12835
12836 // Trim open popup stack
12837 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
12838 g.OpenPopupStack.resize(remaining);
12839
12840 // 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)
12841 if (restore_focus_to_window_under_popup && prev_popup.Window)
12842 {
12843 ImGuiWindow* popup_window = prev_popup.Window;
12844 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
12845 if (focus_window && !focus_window->WasActive)
12846 FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
12847 else
12848 FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
12849 }
12850 }
12851
12852 // Close the popup we have begin-ed into.
12853 void ImGui::CloseCurrentPopup()
12854 {
12855 ImGuiContext& g = *GImGui;
12856 int popup_idx = g.BeginPopupStack.Size - 1;
12857 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
12858 return;
12859
12860 // Closing a menu closes its top-most parent popup (unless a modal)
12861 while (popup_idx > 0)
12862 {
12863 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
12864 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
12865 bool close_parent = false;
12866 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
12867 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
12868 close_parent = true;
12869 if (!close_parent)
12870 break;
12871 popup_idx--;
12872 }
12873 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
12874 ClosePopupToLevel(popup_idx, true);
12875
12876 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
12877 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
12878 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
12879 if (ImGuiWindow* window = g.NavWindow)
12880 window->DC.NavHideHighlightOneFrame = true;
12881 }
12882
12883 // Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
12884 bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
12885 {
12886 ImGuiContext& g = *GImGui;
12887 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12888 {
12889 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12890 return false;
12891 }
12892
12893 char name[20];
12894 IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx()
12895 ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame
12896
12897 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
12898 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12899 EndPopup();
12900 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12901 return is_open;
12902 }
12903
12904 bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags)
12905 {
12906 ImGuiContext& g = *GImGui;
12907 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12908 {
12909 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12910 return false;
12911 }
12912
12913 char name[128];
12914 IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu);
12915 ImFormatString(name, IM_ARRAYSIZE(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth
12916 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup);
12917 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12918 EndPopup();
12919 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12920 return is_open;
12921 }
12922
12923 bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12924 {
12925 ImGuiContext& g = *GImGui;
12926 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12927 {
12928 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12929 return false;
12930 }
12931 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12932 ImGuiID id = g.CurrentWindow->GetID(str_id);
12933 return BeginPopupEx(id, flags);
12934 }
12935
12936 // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12937 // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12938 // - *p_open set back to false in BeginPopupModal() when popup is not open.
12939 // - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12940 bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12941 {
12942 ImGuiContext& g = *GImGui;
12943 ImGuiWindow* window = g.CurrentWindow;
12944 const ImGuiID id = window->GetID(name);
12945 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12946 {
12947 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12948 if (p_open && *p_open)
12949 *p_open = false;
12950 return false;
12951 }
12952
12953 // Center modal windows by default for increased visibility
12954 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12955 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12956 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12957 {
12958 const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12959 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12960 }
12961
12962 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12963 const bool is_open = Begin(name, p_open, flags);
12964 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12965 {
12966 EndPopup();
12967 if (is_open)
12968 ClosePopupToLevel(g.BeginPopupStack.Size, true);
12969 return false;
12970 }
12971 return is_open;
12972 }
12973
12974 void ImGui::EndPopup()
12975 {
12976 ImGuiContext& g = *GImGui;
12977 ImGuiWindow* window = g.CurrentWindow;
12978 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0)
12979 {
12980 IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!");
12981 return;
12982 }
12983
12984 // 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)
12985 if (g.NavWindow == window)
12986 NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12987
12988 // Child-popups don't need to be laid out
12989 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
12990 if (window->Flags & ImGuiWindowFlags_ChildWindow)
12991 g.WithinEndChildID = window->ID;
12992 End();
12993 g.WithinEndChildID = backup_within_end_child_id;
12994 }
12995
12996 // Helper to open a popup if mouse button is released over the item
12997 // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12998 void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12999 {
13000 ImGuiContext& g = *GImGui;
13001 ImGuiWindow* window = g.CurrentWindow;
13002 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13003 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13004 {
13005 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
13006 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
13007 OpenPopupEx(id, popup_flags);
13008 }
13009 }
13010
13011 // This is a helper to handle the simplest case of associating one named popup to one given widget.
13012 // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
13013 // - To create a popup with a specific identifier, pass it in str_id.
13014 // - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
13015 // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
13016 // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
13017 // This is essentially the same as:
13018 // id = str_id ? GetID(str_id) : GetItemID();
13019 // OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
13020 // return BeginPopup(id);
13021 // Which is essentially the same as:
13022 // id = str_id ? GetID(str_id) : GetItemID();
13023 // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
13024 // OpenPopup(id);
13025 // return BeginPopup(id);
13026 // The main difference being that this is tweaked to avoid computing the ID twice.
13027 bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
13028 {
13029 ImGuiContext& g = *GImGui;
13030 ImGuiWindow* window = g.CurrentWindow;
13031 if (window->SkipItems)
13032 return false;
13033 ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
13034 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
13035 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13036 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13037 OpenPopupEx(id, popup_flags);
13038 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13039 }
13040
13041 bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
13042 {
13043 ImGuiContext& g = *GImGui;
13044 ImGuiWindow* window = g.CurrentWindow;
13045 if (!str_id)
13046 str_id = "window_context";
13047 ImGuiID id = window->GetID(str_id);
13048 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13049 if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13050 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
13051 OpenPopupEx(id, popup_flags);
13052 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13053 }
13054
13055 bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
13056 {
13057 ImGuiContext& g = *GImGui;
13058 ImGuiWindow* window = g.CurrentWindow;
13059 if (!str_id)
13060 str_id = "void_context";
13061 ImGuiID id = window->GetID(str_id);
13062 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13063 if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
13064 if (GetTopMostPopupModal() == NULL)
13065 OpenPopupEx(id, popup_flags);
13066 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13067 }
13068
13069 // 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.)
13070 // 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.
13071 // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
13072 // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
13073 // this allows us to have tooltips/popups displayed out of the parent viewport.)
13074 ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
13075 {
13076 ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
13077 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
13078 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
13079
13080 // Combo Box policy (we want a connecting edge)
13081 if (policy == ImGuiPopupPositionPolicy_ComboBox)
13082 {
13083 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
13084 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13085 {
13086 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13087 if (n != -1 && dir == *last_dir) // Already tried this direction?
13088 continue;
13089 ImVec2 pos;
13090 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
13091 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
13092 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
13093 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
13094 if (!r_outer.Contains(ImRect(pos, pos + size)))
13095 continue;
13096 *last_dir = dir;
13097 return pos;
13098 }
13099 }
13100
13101 // Tooltip and Default popup policy
13102 // (Always first try the direction we used on the last frame, if any)
13103 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
13104 {
13105 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
13106 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13107 {
13108 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13109 if (n != -1 && dir == *last_dir) // Already tried this direction?
13110 continue;
13111
13112 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);
13113 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);
13114
13115 // 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)
13116 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
13117 continue;
13118 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
13119 continue;
13120
13121 ImVec2 pos;
13122 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
13123 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
13124
13125 // Clamp top-left corner of popup
13126 pos.x = ImMax(pos.x, r_outer.Min.x);
13127 pos.y = ImMax(pos.y, r_outer.Min.y);
13128
13129 *last_dir = dir;
13130 return pos;
13131 }
13132 }
13133
13134 // Fallback when not enough room:
13135 *last_dir = ImGuiDir_None;
13136
13137 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
13138 if (policy == ImGuiPopupPositionPolicy_Tooltip)
13139 return ref_pos + ImVec2(2, 2);
13140
13141 // Otherwise try to keep within display
13142 ImVec2 pos = ref_pos;
13143 pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
13144 pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
13145 return pos;
13146 }
13147
13148 // Note that this is used for popups, which can overlap the non work-area of individual viewports.
13149 ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
13150 {
13151 ImGuiContext& g = *GImGui;
13152 ImRect r_screen;
13153 if (window->ViewportAllowPlatformMonitorExtend >= 0)
13154 {
13155 // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
13156 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
13157 r_screen.Min = monitor.WorkPos;
13158 r_screen.Max = monitor.WorkPos + monitor.WorkSize;
13159 }
13160 else
13161 {
13162 // Use the full viewport area (not work area) for popups
13163 r_screen = window->Viewport->GetMainRect();
13164 }
13165 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
13166 r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
13167 return r_screen;
13168 }
13169
13170 ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
13171 {
13172 ImGuiContext& g = *GImGui;
13173
13174 ImRect r_outer = GetPopupAllowedExtentRect(window);
13175 if (window->Flags & ImGuiWindowFlags_ChildMenu)
13176 {
13177 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
13178 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
13179 ImGuiWindow* parent_window = window->ParentWindow;
13180 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).
13181 ImRect r_avoid;
13182 if (parent_window->DC.MenuBarAppending)
13183 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
13184 else
13185 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);
13186 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
13187 }
13188 if (window->Flags & ImGuiWindowFlags_Popup)
13189 {
13190 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
13191 }
13192 if (window->Flags & ImGuiWindowFlags_Tooltip)
13193 {
13194 // Position tooltip (always follows mouse + clamp within outer boundaries)
13195 // FIXME:
13196 // - 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).
13197 // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
13198 // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
13199 // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
13200 IM_ASSERT(g.CurrentWindow == window);
13201 const float scale = g.Style.MouseCursorScale;
13202 const ImVec2 ref_pos = NavCalcPreferredRefPos();
13203
13204 if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
13205 {
13206 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
13207 if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
13208 return tooltip_pos;
13209 }
13210
13211 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
13212 ImRect r_avoid;
13213 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
13214 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
13215 else
13216 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.
13217 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
13218
13219 return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
13220 }
13221 IM_ASSERT(0);
13222 return window->Pos;
13223 }
13224
13225 //-----------------------------------------------------------------------------
13226 // [SECTION] WINDOW FOCUS
13227 //----------------------------------------------------------------------------
13228 // - SetWindowFocus()
13229 // - SetNextWindowFocus()
13230 // - IsWindowFocused()
13231 // - UpdateWindowInFocusOrderList() [Internal]
13232 // - BringWindowToFocusFront() [Internal]
13233 // - BringWindowToDisplayFront() [Internal]
13234 // - BringWindowToDisplayBack() [Internal]
13235 // - BringWindowToDisplayBehind() [Internal]
13236 // - FindWindowDisplayIndex() [Internal]
13237 // - FocusWindow() [Internal]
13238 // - FocusTopMostWindowUnderOne() [Internal]
13239 //-----------------------------------------------------------------------------
13240
13241 void ImGui::SetWindowFocus()
13242 {
13243 FocusWindow(GImGui->CurrentWindow);
13244 }
13245
13246 void ImGui::SetWindowFocus(const char* name)
13247 {
13248 if (name)
13249 {
13250 if (ImGuiWindow* window = FindWindowByName(name))
13251 FocusWindow(window);
13252 }
13253 else
13254 {
13255 FocusWindow(NULL);
13256 }
13257 }
13258
13259 void ImGui::SetNextWindowFocus()
13260 {
13261 ImGuiContext& g = *GImGui;
13262 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus;
13263 }
13264
13265 // Similar to IsWindowHovered()
13266 bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
13267 {
13268 ImGuiContext& g = *GImGui;
13269 ImGuiWindow* ref_window = g.NavWindow;
13270 ImGuiWindow* cur_window = g.CurrentWindow;
13271
13272 if (ref_window == NULL)
13273 return false;
13274 if (flags & ImGuiFocusedFlags_AnyWindow)
13275 return true;
13276
13277 IM_ASSERT(cur_window); // Not inside a Begin()/End()
13278 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
13279 const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
13280 if (flags & ImGuiFocusedFlags_RootWindow)
13281 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
13282
13283 if (flags & ImGuiFocusedFlags_ChildWindows)
13284 return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
13285 else
13286 return (ref_window == cur_window);
13287 }
13288
13289 static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13290 {
13291 ImGuiContext& g = *GImGui;
13292 IM_UNUSED(g);
13293 int order = window->FocusOrder;
13294 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13295 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13296 return order;
13297 }
13298
13299 static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
13300 {
13301 ImGuiContext& g = *GImGui;
13302
13303 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
13304 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
13305 if ((just_created || child_flag_changed) && !new_is_explicit_child)
13306 {
13307 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
13308 g.WindowsFocusOrder.push_back(window);
13309 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
13310 }
13311 else if (!just_created && child_flag_changed && new_is_explicit_child)
13312 {
13313 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
13314 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
13315 g.WindowsFocusOrder[n]->FocusOrder--;
13316 g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
13317 window->FocusOrder = -1;
13318 }
13319 window->IsExplicitChild = new_is_explicit_child;
13320 }
13321
13322 void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
13323 {
13324 ImGuiContext& g = *GImGui;
13325 IM_ASSERT(window == window->RootWindow);
13326
13327 const int cur_order = window->FocusOrder;
13328 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
13329 if (g.WindowsFocusOrder.back() == window)
13330 return;
13331
13332 const int new_order = g.WindowsFocusOrder.Size - 1;
13333 for (int n = cur_order; n < new_order; n++)
13334 {
13335 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
13336 g.WindowsFocusOrder[n]->FocusOrder--;
13337 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
13338 }
13339 g.WindowsFocusOrder[new_order] = window;
13340 window->FocusOrder = (short)new_order;
13341 }
13342
13343 // Note technically focus related but rather adjacent and close to BringWindowToFocusFront()
13344 void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
13345 {
13346 ImGuiContext& g = *GImGui;
13347 ImGuiWindow* current_front_window = g.Windows.back();
13348 if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
13349 return;
13350 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
13351 if (g.Windows[i] == window)
13352 {
13353 memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
13354 g.Windows[g.Windows.Size - 1] = window;
13355 break;
13356 }
13357 }
13358
13359 void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
13360 {
13361 ImGuiContext& g = *GImGui;
13362 if (g.Windows[0] == window)
13363 return;
13364 for (int i = 0; i < g.Windows.Size; i++)
13365 if (g.Windows[i] == window)
13366 {
13367 memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
13368 g.Windows[0] = window;
13369 break;
13370 }
13371 }
13372
13373 void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
13374 {
13375 IM_ASSERT(window != NULL && behind_window != NULL);
13376 ImGuiContext& g = *GImGui;
13377 window = window->RootWindow;
13378 behind_window = behind_window->RootWindow;
13379 int pos_wnd = FindWindowDisplayIndex(window);
13380 int pos_beh = FindWindowDisplayIndex(behind_window);
13381 if (pos_wnd < pos_beh)
13382 {
13383 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
13384 memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
13385 g.Windows[pos_beh - 1] = window;
13386 }
13387 else
13388 {
13389 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
13390 memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
13391 g.Windows[pos_beh] = window;
13392 }
13393 }
13394
13395 int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
13396 {
13397 ImGuiContext& g = *GImGui;
13398 return g.Windows.index_from_ptr(g.Windows.find(window));
13399 }
13400
13401 // Moving window to front of display and set focus (which happens to be back of our sorted list)
13402 void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
13403 {
13404 ImGuiContext& g = *GImGui;
13405
13406 // Modal check?
13407 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
13408 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
13409 {
13410 // This block would typically be reached in two situations:
13411 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
13412 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
13413 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
13414 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13415 BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
13416 ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
13417 return;
13418 }
13419
13420 // Find last focused child (if any) and focus it instead.
13421 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
13422 window = NavRestoreLastChildNavWindow(window);
13423
13424 // Apply focus
13425 if (g.NavWindow != window)
13426 {
13427 SetNavWindow(window);
13428 if (window && g.NavHighlightItemUnderNav)
13429 g.NavMousePosDirty = true;
13430 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
13431 g.NavLayer = ImGuiNavLayer_Main;
13432 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
13433 g.NavIdIsAlive = false;
13434 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13435
13436 // Close popups if any
13437 ClosePopupsOverWindow(window, false);
13438 }
13439
13440 // Move the root window to the top of the pile
13441 IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
13442 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
13443 ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
13444 ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
13445 bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
13446
13447 // Steal active widgets. Some of the cases it triggers includes:
13448 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
13449 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
13450 // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
13451 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
13452 if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
13453 ClearActiveID();
13454
13455 // Passing NULL allow to disable keyboard focus
13456 if (!window)
13457 return;
13458 window->LastFrameJustFocused = g.FrameCount;
13459
13460 // Select in dock node
13461 // For #2304 we avoid applying focus immediately before the tabbar is visible.
13462 //if (dock_node && dock_node->TabBar)
13463 // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
13464
13465 // Bring to front
13466 BringWindowToFocusFront(focus_front_window);
13467 if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13468 BringWindowToDisplayFront(display_front_window);
13469 }
13470
13471 void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
13472 {
13473 ImGuiContext& g = *GImGui;
13474 int start_idx = g.WindowsFocusOrder.Size - 1;
13475 if (under_this_window != NULL)
13476 {
13477 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
13478 int offset = -1;
13479 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
13480 {
13481 under_this_window = under_this_window->ParentWindow;
13482 offset = 0;
13483 }
13484 start_idx = FindWindowFocusIndex(under_this_window) + offset;
13485 }
13486 for (int i = start_idx; i >= 0; i--)
13487 {
13488 // 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.
13489 ImGuiWindow* window = g.WindowsFocusOrder[i];
13490 if (window == ignore_window || !window->WasActive)
13491 continue;
13492 if (filter_viewport != NULL && window->Viewport != filter_viewport)
13493 continue;
13494 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
13495 {
13496 // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
13497 // This is failing (lagging by one frame) for docked windows.
13498 // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
13499 // 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)
13500 // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
13501 FocusWindow(window, flags);
13502 return;
13503 }
13504 }
13505 FocusWindow(NULL, flags);
13506 }
13507
13508 //-----------------------------------------------------------------------------
13509 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
13510 //-----------------------------------------------------------------------------
13511
13512 // FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
13513 // In our terminology those should be interchangeable, yet right now this is super confusing.
13514 // Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
13515
13516 void ImGui::SetNavCursorVisible(bool visible)
13517 {
13518 ImGuiContext& g = *GImGui;
13519 if (g.IO.ConfigNavCursorVisibleAlways)
13520 visible = true;
13521 g.NavCursorVisible = visible;
13522 }
13523
13524 // (was called NavRestoreHighlightAfterMove() before 1.91.4)
13525 void ImGui::SetNavCursorVisibleAfterMove()
13526 {
13527 ImGuiContext& g = *GImGui;
13528 if (g.IO.ConfigNavCursorVisibleAuto)
13529 g.NavCursorVisible = true;
13530 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
13531 }
13532
13533 void ImGui::SetNavWindow(ImGuiWindow* window)
13534 {
13535 ImGuiContext& g = *GImGui;
13536 if (g.NavWindow != window)
13537 {
13538 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
13539 g.NavWindow = window;
13540 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13541 }
13542 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13543 NavUpdateAnyRequestFlag();
13544 }
13545
13546 void ImGui::NavHighlightActivated(ImGuiID id)
13547 {
13548 ImGuiContext& g = *GImGui;
13549 g.NavHighlightActivatedId = id;
13550 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
13551 }
13552
13553 void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
13554 {
13555 ImGuiContext& g = *GImGui;
13556 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
13557 }
13558
13559 void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
13560 {
13561 ImGuiContext& g = *GImGui;
13562 IM_ASSERT(g.NavWindow != NULL);
13563 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
13564 g.NavId = id;
13565 g.NavLayer = nav_layer;
13566 SetNavFocusScope(focus_scope_id);
13567 g.NavWindow->NavLastIds[nav_layer] = id;
13568 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
13569
13570 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13571 NavClearPreferredPosForAxis(ImGuiAxis_X);
13572 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13573 }
13574
13575 void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
13576 {
13577 ImGuiContext& g = *GImGui;
13578 IM_ASSERT(id != 0);
13579
13580 if (g.NavWindow != window)
13581 SetNavWindow(window);
13582
13583 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
13584 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
13585 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
13586 g.NavId = id;
13587 g.NavLayer = nav_layer;
13588 SetNavFocusScope(g.CurrentFocusScopeId);
13589 window->NavLastIds[nav_layer] = id;
13590 if (g.LastItemData.ID == id)
13591 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
13592
13593 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
13594 g.NavHighlightItemUnderNav = true;
13595 else if (g.IO.ConfigNavCursorVisibleAuto)
13596 g.NavCursorVisible = false;
13597
13598 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13599 NavClearPreferredPosForAxis(ImGuiAxis_X);
13600 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13601 }
13602
13603 static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
13604 {
13605 if (ImFabs(dx) > ImFabs(dy))
13606 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
13607 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
13608 }
13609
13610 static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
13611 {
13612 if (cand_max < curr_min)
13613 return cand_max - curr_min;
13614 if (curr_max < cand_min)
13615 return cand_min - curr_max;
13616 return 0.0f;
13617 }
13618
13619 // Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
13620 static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb)
13621 {
13622 ImGuiContext& g = *GImGui;
13623 ImGuiWindow* window = g.CurrentWindow;
13624 if (g.NavLayer != window->DC.NavLayerCurrent)
13625 return false;
13626
13627 // FIXME: Those are not good variables names
13628 ImRect cand = nav_bb; // Current item nav rectangle
13629 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)
13630 g.NavScoringDebugCount++;
13631
13632 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
13633 if (window->ParentWindow == g.NavWindow)
13634 {
13635 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
13636 if (!window->ClipRect.Overlaps(cand))
13637 return false;
13638 cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
13639 }
13640
13641 // Compute distance between boxes
13642 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
13643 float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
13644 float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
13645 if (dby != 0.0f && dbx != 0.0f)
13646 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
13647 float dist_box = ImFabs(dbx) + ImFabs(dby);
13648
13649 // 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)
13650 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
13651 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
13652 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
13653
13654 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
13655 ImGuiDir quadrant;
13656 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
13657 if (dbx != 0.0f || dby != 0.0f)
13658 {
13659 // For non-overlapping boxes, use distance between boxes
13660 // 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
13661 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
13662 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
13663 dax = dbx;
13664 day = dby;
13665 dist_axial = dist_box;
13666 quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
13667 }
13668 else if (dcx != 0.0f || dcy != 0.0f)
13669 {
13670 // For overlapping boxes with different centers, use distance between centers
13671 dax = dcx;
13672 day = dcy;
13673 dist_axial = dist_center;
13674 quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
13675 }
13676 else
13677 {
13678 // 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)
13679 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
13680 }
13681
13682 const ImGuiDir move_dir = g.NavMoveDir;
13683 #if IMGUI_DEBUG_NAV_SCORING
13684 char buf[200];
13685 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
13686 {
13687 if (quadrant == move_dir)
13688 {
13689 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
13690 ImDrawList* draw_list = GetForegroundDrawList(window);
13691 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
13692 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
13693 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
13694 }
13695 }
13696 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
13697 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
13698 if (debug_hovering || debug_tty)
13699 {
13700 ImFormatString(buf, IM_ARRAYSIZE(buf),
13701 "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",
13702 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
13703 if (debug_hovering)
13704 {
13705 ImDrawList* draw_list = GetForegroundDrawList(window);
13706 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
13707 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
13708 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
13709 draw_list->AddText(cand.Max, ~0U, buf);
13710 }
13711 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
13712 }
13713 #endif
13714
13715 // Is it in the quadrant we're interested in moving to?
13716 bool new_best = false;
13717 if (quadrant == move_dir)
13718 {
13719 // Does it beat the current best candidate?
13720 if (dist_box < result->DistBox)
13721 {
13722 result->DistBox = dist_box;
13723 result->DistCenter = dist_center;
13724 return true;
13725 }
13726 if (dist_box == result->DistBox)
13727 {
13728 // Try using distance between center points to break ties
13729 if (dist_center < result->DistCenter)
13730 {
13731 result->DistCenter = dist_center;
13732 new_best = true;
13733 }
13734 else if (dist_center == result->DistCenter)
13735 {
13736 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
13737 // (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),
13738 // 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.
13739 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
13740 new_best = true;
13741 }
13742 }
13743 }
13744
13745 // 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
13746 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
13747 // 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.
13748 // 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.
13749 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
13750 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
13751 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
13752 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))
13753 {
13754 result->DistAxial = dist_axial;
13755 new_best = true;
13756 }
13757
13758 return new_best;
13759 }
13760
13761 static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
13762 {
13763 ImGuiContext& g = *GImGui;
13764 ImGuiWindow* window = g.CurrentWindow;
13765 result->Window = window;
13766 result->ID = g.LastItemData.ID;
13767 result->FocusScopeId = g.CurrentFocusScopeId;
13768 result->ItemFlags = g.LastItemData.ItemFlags;
13769 result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
13770 if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13771 {
13772 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13773 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13774 }
13775 }
13776
13777 // True when current work location may be scrolled horizontally when moving left / right.
13778 // This is generally always true UNLESS within a column. We don't have a vertical equivalent.
13779 void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
13780 {
13781 ImGuiContext& g = *GImGui;
13782 ImGuiWindow* window = g.CurrentWindow;
13783 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
13784 }
13785
13786 // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
13787 // This is called after LastItemData is set, but NextItemData is also still valid.
13788 static void ImGui::NavProcessItem()
13789 {
13790 ImGuiContext& g = *GImGui;
13791 ImGuiWindow* window = g.CurrentWindow;
13792 const ImGuiID id = g.LastItemData.ID;
13793 const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
13794
13795 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816)
13796 ImRect nav_bb = g.LastItemData.NavRect;
13797 if (window->DC.NavIsScrollPushableX == false)
13798 {
13799 nav_bb.Min.x = ImClamp(nav_bb.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
13800 nav_bb.Max.x = ImClamp(nav_bb.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
13801 }
13802
13803 // Process Init Request
13804 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
13805 {
13806 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
13807 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
13808 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
13809 {
13810 NavApplyItemToResult(&g.NavInitResult);
13811 }
13812 if (candidate_for_nav_default_focus)
13813 {
13814 g.NavInitRequest = false; // Found a match, clear request
13815 NavUpdateAnyRequestFlag();
13816 }
13817 }
13818
13819 // Process Move Request (scoring for navigation)
13820 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
13821 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
13822 {
13823 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
13824 {
13825 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13826 if (is_tabbing)
13827 {
13828 NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
13829 }
13830 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
13831 {
13832 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
13833 if (NavScoreItem(result, nav_bb))
13834 NavApplyItemToResult(result);
13835
13836 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
13837 const float VISIBLE_RATIO = 0.70f;
13838 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
13839 if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
13840 if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb))
13841 NavApplyItemToResult(&g.NavMoveResultLocalVisible);
13842 }
13843 }
13844 }
13845
13846 // Update information for currently focused/navigated item
13847 if (g.NavId == id)
13848 {
13849 if (g.NavWindow != window)
13850 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
13851 g.NavLayer = window->DC.NavLayerCurrent;
13852 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
13853 g.NavFocusScopeId = g.CurrentFocusScopeId;
13854 g.NavIdIsAlive = true;
13855 if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13856 {
13857 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13858 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13859 }
13860 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
13861 }
13862 }
13863
13864 // Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
13865 // Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
13866 // - Case 1: no nav/active id: set result to first eligible item, stop storing.
13867 // - Case 2: tab forward: on ref id set counter, on counter elapse store result
13868 // - 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
13869 // - Case 4: tab backward: store all results, on ref id pick prev, stop storing
13870 // - 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
13871 void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
13872 {
13873 ImGuiContext& g = *GImGui;
13874
13875 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
13876 {
13877 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
13878 return;
13879 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
13880 return;
13881 }
13882
13883 // - Can always land on an item when using API call.
13884 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
13885 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
13886 bool can_stop;
13887 if (move_flags & ImGuiNavMoveFlags_FocusApi)
13888 can_stop = true;
13889 else
13890 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
13891
13892 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
13893 ImGuiNavItemData* result = &g.NavMoveResultLocal;
13894 if (g.NavTabbingDir == +1)
13895 {
13896 // Tab Forward or SetKeyboardFocusHere() with >= 0
13897 if (can_stop && g.NavTabbingResultFirst.ID == 0)
13898 NavApplyItemToResult(&g.NavTabbingResultFirst);
13899 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
13900 NavMoveRequestResolveWithLastItem(result);
13901 else if (g.NavId == id)
13902 g.NavTabbingCounter = 1;
13903 }
13904 else if (g.NavTabbingDir == -1)
13905 {
13906 // Tab Backward
13907 if (g.NavId == id)
13908 {
13909 if (result->ID)
13910 {
13911 g.NavMoveScoringItems = false;
13912 NavUpdateAnyRequestFlag();
13913 }
13914 }
13915 else if (can_stop)
13916 {
13917 // Keep applying until reaching NavId
13918 NavApplyItemToResult(result);
13919 }
13920 }
13921 else if (g.NavTabbingDir == 0)
13922 {
13923 if (can_stop && g.NavId == id)
13924 NavMoveRequestResolveWithLastItem(result);
13925 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
13926 NavApplyItemToResult(&g.NavTabbingResultFirst);
13927 }
13928 }
13929
13930 bool ImGui::NavMoveRequestButNoResultYet()
13931 {
13932 ImGuiContext& g = *GImGui;
13933 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
13934 }
13935
13936 // FIXME: ScoringRect is not set
13937 void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13938 {
13939 ImGuiContext& g = *GImGui;
13940 IM_ASSERT(g.NavWindow != NULL);
13941 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
13942
13943 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
13944 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
13945
13946 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
13947 g.NavMoveDir = move_dir;
13948 g.NavMoveDirForDebug = move_dir;
13949 g.NavMoveClipDir = clip_dir;
13950 g.NavMoveFlags = move_flags;
13951 g.NavMoveScrollFlags = scroll_flags;
13952 g.NavMoveForwardToNextFrame = false;
13953 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
13954 g.NavMoveResultLocal.Clear();
13955 g.NavMoveResultLocalVisible.Clear();
13956 g.NavMoveResultOther.Clear();
13957 g.NavTabbingCounter = 0;
13958 g.NavTabbingResultFirst.Clear();
13959 NavUpdateAnyRequestFlag();
13960 }
13961
13962 void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
13963 {
13964 ImGuiContext& g = *GImGui;
13965 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
13966 NavApplyItemToResult(result);
13967 NavUpdateAnyRequestFlag();
13968 }
13969
13970 // Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent
13971 void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data)
13972 {
13973 ImGuiContext& g = *GImGui;
13974 g.NavMoveScoringItems = false;
13975 g.LastItemData.ID = tree_node_data->ID;
13976 g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
13977 g.LastItemData.NavRect = tree_node_data->NavRect;
13978 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
13979 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13980 NavUpdateAnyRequestFlag();
13981 }
13982
13983 void ImGui::NavMoveRequestCancel()
13984 {
13985 ImGuiContext& g = *GImGui;
13986 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13987 NavUpdateAnyRequestFlag();
13988 }
13989
13990 // Forward will reuse the move request again on the next frame (generally with modifications done to it)
13991 void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13992 {
13993 ImGuiContext& g = *GImGui;
13994 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
13995 NavMoveRequestCancel();
13996 g.NavMoveForwardToNextFrame = true;
13997 g.NavMoveDir = move_dir;
13998 g.NavMoveClipDir = clip_dir;
13999 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
14000 g.NavMoveScrollFlags = scroll_flags;
14001 }
14002
14003 // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
14004 // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
14005 void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
14006 {
14007 ImGuiContext& g = *GImGui;
14008 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
14009
14010 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
14011 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
14012 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
14013 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
14014 }
14015
14016 // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
14017 // This way we could find the last focused window among our children. It would be much less confusing this way?
14018 static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
14019 {
14020 ImGuiWindow* parent = nav_window;
14021 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
14022 parent = parent->ParentWindow;
14023 if (parent && parent != nav_window)
14024 parent->NavLastChildNavWindow = nav_window;
14025 }
14026
14027 // Restore the last focused child.
14028 // Call when we are expected to land on the Main Layer (0) after FocusWindow()
14029 static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
14030 {
14031 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
14032 return window->NavLastChildNavWindow;
14033 if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
14034 if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
14035 return tab->Window;
14036 return window;
14037 }
14038
14039 void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
14040 {
14041 ImGuiContext& g = *GImGui;
14042 if (layer == ImGuiNavLayer_Main)
14043 {
14044 ImGuiWindow* prev_nav_window = g.NavWindow;
14045 g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
14046 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14047 if (prev_nav_window)
14048 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
14049 }
14050 ImGuiWindow* window = g.NavWindow;
14051 if (window->NavLastIds[layer] != 0)
14052 {
14053 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
14054 }
14055 else
14056 {
14057 g.NavLayer = layer;
14058 NavInitWindow(window, true);
14059 }
14060 }
14061
14062 static inline void ImGui::NavUpdateAnyRequestFlag()
14063 {
14064 ImGuiContext& g = *GImGui;
14065 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
14066 if (g.NavAnyRequest)
14067 IM_ASSERT(g.NavWindow != NULL);
14068 }
14069
14070 // This needs to be called before we submit any widget (aka in or before Begin)
14071 void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
14072 {
14073 // FIXME: ChildWindow test here is wrong for docking
14074 ImGuiContext& g = *GImGui;
14075 IM_ASSERT(window == g.NavWindow);
14076
14077 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
14078 {
14079 g.NavId = 0;
14080 SetNavFocusScope(window->NavRootFocusScopeId);
14081 return;
14082 }
14083
14084 bool init_for_nav = false;
14085 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
14086 init_for_nav = true;
14087 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
14088 if (init_for_nav)
14089 {
14090 SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
14091 g.NavInitRequest = true;
14092 g.NavInitRequestFromMove = false;
14093 g.NavInitResult.ID = 0;
14094 NavUpdateAnyRequestFlag();
14095 }
14096 else
14097 {
14098 g.NavId = window->NavLastIds[0];
14099 SetNavFocusScope(window->NavRootFocusScopeId);
14100 }
14101 }
14102
14103 static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
14104 {
14105 ImGuiContext& g = *GImGui;
14106 ImGuiWindow* window = g.NavWindow;
14107 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14108
14109 // 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.
14110 if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut)
14111 return ImGuiInputSource_Mouse;
14112 else
14113 return ImGuiInputSource_Keyboard; // or Nav in general
14114 }
14115
14116 static ImVec2 ImGui::NavCalcPreferredRefPos()
14117 {
14118 ImGuiContext& g = *GImGui;
14119 ImGuiWindow* window = g.NavWindow;
14120 ImGuiInputSource source = NavCalcPreferredRefPosSource();
14121
14122 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14123
14124 if (source != ImGuiInputSource_Mouse && !activated_shortcut && window == NULL)
14125 source = ImGuiInputSource_Mouse;
14126
14127 // 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.
14128 if (source == ImGuiInputSource_Mouse)
14129 {
14130 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
14131 // 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.
14132 // In theory we could move that +1.0f offset in OpenPopupEx()
14133 ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
14134 return ImVec2(p.x + 1.0f, p.y);
14135 }
14136 else
14137 {
14138 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
14139 ImRect ref_rect;
14140 if (activated_shortcut)
14141 ref_rect = g.LastItemData.NavRect;
14142 else if (window != NULL)
14143 ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
14144
14145 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
14146 if (window != NULL && window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
14147 {
14148 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
14149 ref_rect.Translate(window->Scroll - next_scroll);
14150 }
14151 ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
14152 ImGuiViewport* viewport = window->Viewport;
14153 return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
14154 }
14155 }
14156
14157 float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
14158 {
14159 ImGuiContext& g = *GImGui;
14160 float repeat_delay, repeat_rate;
14161 GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
14162
14163 ImGuiKey key_less, key_more;
14164 if (g.NavInputSource == ImGuiInputSource_Gamepad)
14165 {
14166 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
14167 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
14168 }
14169 else
14170 {
14171 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
14172 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
14173 }
14174 float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
14175 if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
14176 amount = 0.0f;
14177 return amount;
14178 }
14179
14180 static void ImGui::NavUpdate()
14181 {
14182 ImGuiContext& g = *GImGui;
14183 ImGuiIO& io = g.IO;
14184
14185 io.WantSetMousePos = false;
14186 //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);
14187
14188 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
14189 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
14190 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14191 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
14192 if (nav_gamepad_active)
14193 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
14194 if (IsKeyDown(key))
14195 g.NavInputSource = ImGuiInputSource_Gamepad;
14196 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14197 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
14198 if (nav_keyboard_active)
14199 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
14200 if (IsKeyDown(key))
14201 g.NavInputSource = ImGuiInputSource_Keyboard;
14202
14203 // Process navigation init request (select first/default focus)
14204 g.NavJustMovedToId = 0;
14205 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
14206 if (g.NavInitResult.ID != 0)
14207 NavInitRequestApplyResult();
14208 g.NavInitRequest = false;
14209 g.NavInitRequestFromMove = false;
14210 g.NavInitResult.ID = 0;
14211
14212 // Process navigation move request
14213 if (g.NavMoveSubmitted)
14214 NavMoveRequestApplyResult();
14215 g.NavTabbingCounter = 0;
14216 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
14217 if (g.NavCursorHideFrames > 0)
14218 if (--g.NavCursorHideFrames == 0)
14219 g.NavCursorVisible = true;
14220
14221 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
14222 bool set_mouse_pos = false;
14223 if (g.NavMousePosDirty && g.NavIdIsAlive)
14224 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
14225 set_mouse_pos = true;
14226 g.NavMousePosDirty = false;
14227 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
14228
14229 // 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
14230 if (g.NavWindow)
14231 NavSaveLastChildNavWindowIntoParent(g.NavWindow);
14232 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
14233 g.NavWindow->NavLastChildNavWindow = NULL;
14234
14235 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
14236 NavUpdateWindowing();
14237
14238 // Set output flags for user application
14239 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
14240 io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
14241
14242 // Process NavCancel input (to close a popup, get back to parent, clear focus)
14243 NavUpdateCancelRequest();
14244
14245 // Process manual activation request
14246 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
14247 g.NavActivateFlags = ImGuiActivateFlags_None;
14248 if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14249 {
14250 const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
14251 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
14252 const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
14253 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
14254 if (g.ActiveId == 0 && activate_pressed)
14255 {
14256 g.NavActivateId = g.NavId;
14257 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
14258 }
14259 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
14260 {
14261 g.NavActivateId = g.NavId;
14262 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
14263 }
14264 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
14265 g.NavActivateDownId = g.NavId;
14266 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
14267 {
14268 g.NavActivatePressedId = g.NavId;
14269 NavHighlightActivated(g.NavId);
14270 }
14271 }
14272 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14273 g.NavCursorVisible = false;
14274 else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
14275 g.NavCursorVisible = true;
14276 if (g.NavActivateId != 0)
14277 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
14278
14279 // Highlight
14280 if (g.NavHighlightActivatedTimer > 0.0f)
14281 g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
14282 if (g.NavHighlightActivatedTimer == 0.0f)
14283 g.NavHighlightActivatedId = 0;
14284
14285 // Process programmatic activation request
14286 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
14287 if (g.NavNextActivateId != 0)
14288 {
14289 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
14290 g.NavActivateFlags = g.NavNextActivateFlags;
14291 }
14292 g.NavNextActivateId = 0;
14293
14294 // Process move requests
14295 NavUpdateCreateMoveRequest();
14296 if (g.NavMoveDir == ImGuiDir_None)
14297 NavUpdateCreateTabbingRequest();
14298 NavUpdateAnyRequestFlag();
14299 g.NavIdIsAlive = false;
14300
14301 // Scrolling
14302 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
14303 {
14304 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
14305 ImGuiWindow* window = g.NavWindow;
14306 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.
14307 const ImGuiDir move_dir = g.NavMoveDir;
14308 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
14309 {
14310 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
14311 SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
14312 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
14313 SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
14314 }
14315
14316 // *Normal* Manual scroll with LStick
14317 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
14318 if (nav_gamepad_active)
14319 {
14320 const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
14321 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
14322 if (scroll_dir.x != 0.0f && window->ScrollbarX)
14323 SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
14324 if (scroll_dir.y != 0.0f)
14325 SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
14326 }
14327 }
14328
14329 // Always prioritize mouse highlight if navigation is disabled
14330 if (!nav_keyboard_active && !nav_gamepad_active)
14331 {
14332 g.NavCursorVisible = false;
14333 g.NavHighlightItemUnderNav = set_mouse_pos = false;
14334 }
14335
14336 // Update mouse position if requested
14337 // (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)
14338 if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
14339 TeleportMousePos(NavCalcPreferredRefPos());
14340
14341 // [DEBUG]
14342 g.NavScoringDebugCount = 0;
14343 #if IMGUI_DEBUG_NAV_RECTS
14344 if (ImGuiWindow* debug_window = g.NavWindow)
14345 {
14346 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
14347 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)); }
14348 //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); }
14349 }
14350 #endif
14351 }
14352
14353 void ImGui::NavInitRequestApplyResult()
14354 {
14355 // 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)
14356 ImGuiContext& g = *GImGui;
14357 if (!g.NavWindow)
14358 return;
14359
14360 ImGuiNavItemData* result = &g.NavInitResult;
14361 if (g.NavId != result->ID)
14362 {
14363 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14364 g.NavJustMovedToId = result->ID;
14365 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14366 g.NavJustMovedToKeyMods = 0;
14367 g.NavJustMovedToIsTabbing = false;
14368 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14369 }
14370
14371 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
14372 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
14373 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14374 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
14375 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
14376 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14377 g.NavLastValidSelectionUserData = result->SelectionUserData;
14378 if (g.NavInitRequestFromMove)
14379 SetNavCursorVisibleAfterMove();
14380 }
14381
14382 // Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
14383 static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
14384 {
14385 // Bias initial rect
14386 ImGuiContext& g = *GImGui;
14387 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
14388
14389 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
14390 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
14391 // - But each successful move sets new bias on one axis, only cleared when using mouse.
14392 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
14393 {
14394 if (preferred_pos_rel.x == FLT_MAX)
14395 preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
14396 if (preferred_pos_rel.y == FLT_MAX)
14397 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
14398 }
14399
14400 // Apply general bias on the other axis
14401 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
14402 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
14403 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
14404 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
14405 }
14406
14407 void ImGui::NavUpdateCreateMoveRequest()
14408 {
14409 ImGuiContext& g = *GImGui;
14410 ImGuiIO& io = g.IO;
14411 ImGuiWindow* window = g.NavWindow;
14412 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14413 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14414
14415 if (g.NavMoveForwardToNextFrame && window != NULL)
14416 {
14417 // 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)
14418 // (preserve most state, which were already set by the NavMoveRequestForward() function)
14419 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
14420 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
14421 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
14422 }
14423 else
14424 {
14425 // Initiate directional inputs request
14426 g.NavMoveDir = ImGuiDir_None;
14427 g.NavMoveFlags = ImGuiNavMoveFlags_None;
14428 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
14429 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
14430 {
14431 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
14432 if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
14433 if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
14434 if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
14435 if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
14436 }
14437 g.NavMoveClipDir = g.NavMoveDir;
14438 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14439 }
14440
14441 // Update PageUp/PageDown/Home/End scroll
14442 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
14443 float scoring_rect_offset_y = 0.0f;
14444 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
14445 scoring_rect_offset_y = NavUpdatePageUpPageDown();
14446 if (scoring_rect_offset_y != 0.0f)
14447 {
14448 g.NavScoringNoClipRect = window->InnerRect;
14449 g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
14450 }
14451
14452 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
14453 #if IMGUI_DEBUG_NAV_SCORING
14454 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
14455 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
14456 if (io.KeyCtrl)
14457 {
14458 if (g.NavMoveDir == ImGuiDir_None)
14459 g.NavMoveDir = g.NavMoveDirForDebug;
14460 g.NavMoveClipDir = g.NavMoveDir;
14461 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
14462 }
14463 #endif
14464
14465 // Submit
14466 g.NavMoveForwardToNextFrame = false;
14467 if (g.NavMoveDir != ImGuiDir_None)
14468 NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
14469
14470 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
14471 if (g.NavMoveSubmitted && g.NavId == 0)
14472 {
14473 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
14474 g.NavInitRequest = g.NavInitRequestFromMove = true;
14475 g.NavInitResult.ID = 0;
14476 if (g.IO.ConfigNavCursorVisibleAuto)
14477 g.NavCursorVisible = true;
14478 }
14479
14480 // When using gamepad, we project the reference nav bounding box into window visible area.
14481 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
14482 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
14483 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
14484 {
14485 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
14486 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
14487 ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
14488
14489 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
14490 // Otherwise 'inner_rect_rel' would be off on the move result frame.
14491 inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
14492
14493 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
14494 {
14495 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
14496 float pad_x = ImMin(inner_rect_rel.GetWidth(), window->FontRefSize * 0.5f);
14497 float pad_y = ImMin(inner_rect_rel.GetHeight(), window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
14498 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
14499 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
14500 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
14501 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
14502 window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
14503 g.NavId = 0;
14504 }
14505 }
14506
14507 // Prepare scoring rectangle.
14508 // 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)
14509 ImRect scoring_rect;
14510 if (window != NULL)
14511 {
14512 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
14513 scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
14514 scoring_rect.TranslateY(scoring_rect_offset_y);
14515 if (g.NavMoveSubmitted)
14516 NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
14517 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
14518 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
14519 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
14520 }
14521 g.NavScoringRect = scoring_rect;
14522 //g.NavScoringNoClipRect.Add(scoring_rect);
14523 }
14524
14525 void ImGui::NavUpdateCreateTabbingRequest()
14526 {
14527 ImGuiContext& g = *GImGui;
14528 ImGuiWindow* window = g.NavWindow;
14529 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
14530 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
14531 return;
14532
14533 const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
14534 if (!tab_pressed)
14535 return;
14536
14537 // Initiate tabbing request
14538 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
14539 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
14540 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14541 if (nav_keyboard_active)
14542 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
14543 else
14544 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
14545 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
14546 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
14547 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
14548 NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
14549 g.NavTabbingCounter = -1;
14550 }
14551
14552 // Apply result from previous frame navigation directional move request. Always called from NavUpdate()
14553 void ImGui::NavMoveRequestApplyResult()
14554 {
14555 ImGuiContext& g = *GImGui;
14556 #if IMGUI_DEBUG_NAV_SCORING
14557 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
14558 return;
14559 #endif
14560
14561 // Select which result to use
14562 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
14563
14564 // Tabbing forward wrap
14565 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
14566 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
14567 result = &g.NavTabbingResultFirst;
14568
14569 // 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)
14570 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14571 if (result == NULL)
14572 {
14573 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14574 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
14575 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14576 SetNavCursorVisibleAfterMove();
14577 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
14578 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
14579 return;
14580 }
14581
14582 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
14583 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
14584 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
14585 result = &g.NavMoveResultLocalVisible;
14586
14587 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
14588 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
14589 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
14590 result = &g.NavMoveResultOther;
14591 IM_ASSERT(g.NavWindow && result->Window);
14592
14593 // Scroll to keep newly navigated item fully into view.
14594 if (g.NavLayer == ImGuiNavLayer_Main)
14595 {
14596 ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
14597 ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
14598
14599 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
14600 {
14601 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
14602 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
14603 SetScrollY(result->Window, scroll_target);
14604 }
14605 }
14606
14607 if (g.NavWindow != result->Window)
14608 {
14609 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
14610 g.NavWindow = result->Window;
14611 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14612 }
14613
14614 // Clear active id unless requested not to
14615 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
14616 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
14617 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
14618 ClearActiveID();
14619
14620 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
14621 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
14622 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
14623 {
14624 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14625 g.NavJustMovedToId = result->ID;
14626 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14627 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
14628 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
14629 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14630 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
14631 }
14632
14633 // Apply new NavID/Focus
14634 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14635 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
14636 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
14637 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14638 g.NavLastValidSelectionUserData = result->SelectionUserData;
14639
14640 // Restore last preferred position for current axis
14641 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
14642 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
14643 {
14644 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
14645 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
14646 }
14647
14648 // Tabbing: Activates Inputable, otherwise only Focus
14649 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
14650 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
14651
14652 // Activate
14653 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
14654 {
14655 g.NavNextActivateId = result->ID;
14656 g.NavNextActivateFlags = ImGuiActivateFlags_None;
14657 if (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi)
14658 g.NavNextActivateFlags |= ImGuiActivateFlags_FromFocusApi;
14659 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14660 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
14661 }
14662
14663 // Make nav cursor visible
14664 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14665 SetNavCursorVisibleAfterMove();
14666 }
14667
14668 // Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
14669 // FIXME: In order to support e.g. Escape to clear a selection we'll need:
14670 // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
14671 // - 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
14672 static void ImGui::NavUpdateCancelRequest()
14673 {
14674 ImGuiContext& g = *GImGui;
14675 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14676 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14677 if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
14678 return;
14679
14680 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
14681 if (g.ActiveId != 0)
14682 {
14683 ClearActiveID();
14684 }
14685 else if (g.NavLayer != ImGuiNavLayer_Main)
14686 {
14687 // Leave the "menu" layer
14688 NavRestoreLayer(ImGuiNavLayer_Main);
14689 SetNavCursorVisibleAfterMove();
14690 }
14691 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
14692 {
14693 // Exit child window
14694 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
14695 ImGuiWindow* parent_window = child_window->ParentWindow;
14696 IM_ASSERT(child_window->ChildId != 0);
14697 FocusWindow(parent_window);
14698 SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
14699 SetNavCursorVisibleAfterMove();
14700 }
14701 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
14702 {
14703 // Close open popup/menu
14704 ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
14705 }
14706 else
14707 {
14708 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
14709 // FIXME-NAV: This should happen on window appearing.
14710 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14711 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
14712 g.NavWindow->NavLastIds[0] = 0;
14713
14714 // Clear nav focus
14715 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14716 g.NavId = 0;
14717 if (g.IO.ConfigNavEscapeClearFocusWindow)
14718 FocusWindow(NULL);
14719 }
14720 }
14721
14722 // Handle PageUp/PageDown/Home/End keys
14723 // Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
14724 // FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
14725 // FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
14726 static float ImGui::NavUpdatePageUpPageDown()
14727 {
14728 ImGuiContext& g = *GImGui;
14729 ImGuiWindow* window = g.NavWindow;
14730 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
14731 return 0.0f;
14732
14733 const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
14734 const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
14735 const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14736 const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14737 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
14738 return 0.0f;
14739
14740 if (g.NavLayer != ImGuiNavLayer_Main)
14741 NavRestoreLayer(ImGuiNavLayer_Main);
14742
14743 if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY)
14744 {
14745 // Fallback manual-scroll when window has no navigable item
14746 if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14747 SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
14748 else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14749 SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
14750 else if (home_pressed)
14751 SetScrollY(window, 0.0f);
14752 else if (end_pressed)
14753 SetScrollY(window, window->ScrollMax.y);
14754 }
14755 else
14756 {
14757 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
14758 const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight());
14759 float nav_scoring_rect_offset_y = 0.0f;
14760 if (IsKeyPressed(ImGuiKey_PageUp, true))
14761 {
14762 nav_scoring_rect_offset_y = -page_offset_y;
14763 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)
14764 g.NavMoveClipDir = ImGuiDir_Up;
14765 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
14766 }
14767 else if (IsKeyPressed(ImGuiKey_PageDown, true))
14768 {
14769 nav_scoring_rect_offset_y = +page_offset_y;
14770 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)
14771 g.NavMoveClipDir = ImGuiDir_Down;
14772 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
14773 }
14774 else if (home_pressed)
14775 {
14776 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
14777 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
14778 // Preserve current horizontal position if we have any.
14779 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
14780 if (nav_rect_rel.IsInverted())
14781 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14782 g.NavMoveDir = ImGuiDir_Down;
14783 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14784 // FIXME-NAV: MoveClipDir left to _None, intentional?
14785 }
14786 else if (end_pressed)
14787 {
14788 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
14789 if (nav_rect_rel.IsInverted())
14790 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14791 g.NavMoveDir = ImGuiDir_Up;
14792 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14793 // FIXME-NAV: MoveClipDir left to _None, intentional?
14794 }
14795 return nav_scoring_rect_offset_y;
14796 }
14797 return 0.0f;
14798 }
14799
14800 static void ImGui::NavEndFrame()
14801 {
14802 ImGuiContext& g = *GImGui;
14803
14804 // Show CTRL+TAB list window
14805 if (g.NavWindowingTarget != NULL)
14806 NavUpdateWindowingOverlay();
14807
14808 // Perform wrap-around in menus
14809 // 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.
14810 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
14811 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
14812 NavUpdateCreateWrappingRequest();
14813 }
14814
14815 static void ImGui::NavUpdateCreateWrappingRequest()
14816 {
14817 ImGuiContext& g = *GImGui;
14818 ImGuiWindow* window = g.NavWindow;
14819
14820 bool do_forward = false;
14821 ImRect bb_rel = window->NavRectRel[g.NavLayer];
14822 ImGuiDir clip_dir = g.NavMoveDir;
14823
14824 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
14825 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14826 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14827 {
14828 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
14829 if (move_flags & ImGuiNavMoveFlags_WrapX)
14830 {
14831 bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
14832 clip_dir = ImGuiDir_Up;
14833 }
14834 do_forward = true;
14835 }
14836 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14837 {
14838 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
14839 if (move_flags & ImGuiNavMoveFlags_WrapX)
14840 {
14841 bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
14842 clip_dir = ImGuiDir_Down;
14843 }
14844 do_forward = true;
14845 }
14846 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14847 {
14848 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
14849 if (move_flags & ImGuiNavMoveFlags_WrapY)
14850 {
14851 bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
14852 clip_dir = ImGuiDir_Left;
14853 }
14854 do_forward = true;
14855 }
14856 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14857 {
14858 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
14859 if (move_flags & ImGuiNavMoveFlags_WrapY)
14860 {
14861 bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
14862 clip_dir = ImGuiDir_Right;
14863 }
14864 do_forward = true;
14865 }
14866 if (!do_forward)
14867 return;
14868 window->NavRectRel[g.NavLayer] = bb_rel;
14869 NavClearPreferredPosForAxis(ImGuiAxis_X);
14870 NavClearPreferredPosForAxis(ImGuiAxis_Y);
14871 NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
14872 }
14873
14874 // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
14875 // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
14876 // If you want a window to never be focused, you may use the e.g. NoInputs flag.
14877 bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
14878 {
14879 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
14880 }
14881
14882 static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
14883 {
14884 ImGuiContext& g = *GImGui;
14885 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
14886 if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
14887 return g.WindowsFocusOrder[i];
14888 return NULL;
14889 }
14890
14891 static void NavUpdateWindowingTarget(int focus_change_dir)
14892 {
14893 ImGuiContext& g = *GImGui;
14894 IM_ASSERT(g.NavWindowingTarget);
14895 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
14896 return;
14897
14898 const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
14899 ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
14900 if (!window_target)
14901 window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
14902 if (window_target) // Don't reset windowing target if there's a single window in the list
14903 {
14904 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
14905 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14906 }
14907 g.NavWindowingToggleLayer = false;
14908 }
14909
14910 // Apply focus and close overlay
14911 static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window)
14912 {
14913 // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ?
14914 // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
14915 ImGuiContext& g = *GImGui;
14916 if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)
14917 {
14918 ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
14919 ClearActiveID();
14920 SetNavCursorVisibleAfterMove();
14921 ClosePopupsOverWindow(apply_focus_window, false);
14922 FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
14923 IM_ASSERT(g.NavWindow != NULL);
14924 apply_focus_window = g.NavWindow;
14925 if (apply_focus_window->NavLastIds[0] == 0)
14926 NavInitWindow(apply_focus_window, false);
14927
14928 // If the window has ONLY a menu layer (no main layer), select it directly
14929 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
14930 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
14931 // the target window as already been previewed once.
14932 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
14933 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
14934 // won't be valid.
14935 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
14936 g.NavLayer = ImGuiNavLayer_Menu;
14937
14938 // Request OS level focus
14939 if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
14940 g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
14941 }
14942 g.NavWindowingTarget = NULL;
14943 }
14944
14945 // Windowing management mode
14946 // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
14947 // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
14948 static void ImGui::NavUpdateWindowing()
14949 {
14950 ImGuiContext& g = *GImGui;
14951 ImGuiIO& io = g.IO;
14952
14953 ImGuiWindow* apply_focus_window = NULL;
14954 bool apply_toggle_layer = false;
14955
14956 ImGuiWindow* modal_window = GetTopMostPopupModal();
14957 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.
14958 if (!allow_windowing)
14959 g.NavWindowingTarget = NULL;
14960
14961 // Fade out
14962 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
14963 {
14964 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
14965 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
14966 g.NavWindowingTargetAnim = NULL;
14967 }
14968
14969 // Start CTRL+Tab or Square+L/R window selection
14970 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
14971 const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing");
14972 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14973 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14974 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14975 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14976 const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id);
14977 const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad;
14978 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
14979 bool just_started_windowing_from_null_focus = false;
14980 if (start_toggling_with_gamepad)
14981 {
14982 g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer
14983 g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu;
14984 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad;
14985 }
14986 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
14987 if (ImGuiWindow* window = (g.NavWindow && IsWindowNavFocusable(g.NavWindow)) ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
14988 {
14989 if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad)
14990 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
14991 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
14992 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14993 g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
14994 if (g.NavWindow == NULL)
14995 just_started_windowing_from_null_focus = true;
14996
14997 // 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.
14998 if (keyboard_next_window || keyboard_prev_window)
14999 SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
15000 }
15001
15002 // Gamepad update
15003 if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad)
15004 {
15005 if (g.NavWindowingTarget != NULL)
15006 {
15007 // 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
15008 // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast.
15009 g.NavWindowingTimer += io.DeltaTime;
15010 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
15011
15012 // Select window to focus
15013 const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
15014 if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
15015 {
15016 NavUpdateWindowingTarget(focus_change_dir);
15017 g.NavWindowingHighlightAlpha = 1.0f;
15018 }
15019 }
15020
15021 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
15022 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
15023 {
15024 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
15025 if (g.NavWindowingToggleLayer && g.NavWindow)
15026 apply_toggle_layer = true;
15027 else if (!g.NavWindowingToggleLayer)
15028 apply_focus_window = g.NavWindowingTarget;
15029 g.NavWindowingTarget = NULL;
15030 g.NavWindowingToggleLayer = false;
15031 }
15032 }
15033
15034 // Keyboard: Focus
15035 if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
15036 {
15037 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
15038 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
15039 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
15040 g.NavWindowingTimer += io.DeltaTime;
15041 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
15042 if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
15043 NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1);
15044 else if ((io.KeyMods & shared_mods) != shared_mods)
15045 apply_focus_window = g.NavWindowingTarget;
15046 }
15047
15048 // Keyboard: Press and Release ALT to toggle menu layer
15049 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
15050 bool windowing_toggle_layer_start = false;
15051 if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
15052 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
15053 if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
15054 {
15055 windowing_toggle_layer_start = true;
15056 g.NavWindowingToggleLayer = true;
15057 g.NavWindowingToggleKey = windowing_toggle_key;
15058 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard;
15059 break;
15060 }
15061 if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
15062 {
15063 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
15064 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
15065 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
15066 // We cancel toggling nav layer if an owner has claimed the key.
15067 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
15068 g.NavWindowingToggleLayer = false;
15069 else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time)
15070 g.NavWindowingToggleLayer = false;
15071 else if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
15072 g.NavWindowingToggleLayer = false;
15073
15074 // Apply layer toggle on Alt release
15075 // 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.
15076 if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
15077 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
15078 if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
15079 apply_toggle_layer = true;
15080 if (!IsKeyDown(g.NavWindowingToggleKey))
15081 g.NavWindowingToggleLayer = false;
15082 }
15083
15084 // Move window
15085 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
15086 {
15087 ImVec2 nav_move_dir;
15088 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
15089 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
15090 if (g.NavInputSource == ImGuiInputSource_Gamepad)
15091 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
15092 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
15093 {
15094 const float NAV_MOVE_SPEED = 800.0f;
15095 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
15096 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
15097 g.NavHighlightItemUnderNav = true;
15098 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
15099 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
15100 {
15101 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
15102 SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
15103 g.NavWindowingAccumDeltaPos -= accum_floored;
15104 }
15105 }
15106 }
15107
15108 // Apply final focus
15109 if (apply_focus_window)
15110 NavUpdateWindowingApplyFocus(apply_focus_window);
15111
15112 // Apply menu/layer toggle
15113 if (apply_toggle_layer && g.NavWindow)
15114 {
15115 ClearActiveID();
15116
15117 // Move to parent menu if necessary
15118 ImGuiWindow* new_nav_window = g.NavWindow;
15119 while (new_nav_window->ParentWindow
15120 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
15121 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
15122 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
15123 new_nav_window = new_nav_window->ParentWindow;
15124 if (new_nav_window != g.NavWindow)
15125 {
15126 ImGuiWindow* old_nav_window = g.NavWindow;
15127 FocusWindow(new_nav_window);
15128 new_nav_window->NavLastChildNavWindow = old_nav_window;
15129 }
15130
15131 // Toggle layer
15132 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
15133 if (new_nav_layer != g.NavLayer)
15134 {
15135 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
15136 const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
15137 if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
15138 g.NavWindow->NavLastIds[new_nav_layer] = 0;
15139 NavRestoreLayer(new_nav_layer);
15140 SetNavCursorVisibleAfterMove();
15141 }
15142 }
15143 }
15144
15145 // Window has already passed the IsWindowNavFocusable()
15146 static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
15147 {
15148 if (window->Flags & ImGuiWindowFlags_Popup)
15149 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
15150 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
15151 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
15152 if (window->DockNodeAsHost)
15153 return "(Dock node)"; // Not normally shown to user.
15154 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
15155 }
15156
15157 // Overlay displayed when using CTRL+TAB. Called by EndFrame().
15158 void ImGui::NavUpdateWindowingOverlay()
15159 {
15160 ImGuiContext& g = *GImGui;
15161 IM_ASSERT(g.NavWindowingTarget != NULL);
15162
15163 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
15164 return;
15165
15166 if (g.NavWindowingListWindow == NULL)
15167 g.NavWindowingListWindow = FindWindowByName("##NavWindowingOverlay");
15168 const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
15169 SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
15170 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
15171 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
15172 Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
15173 if (g.ContextName[0] != 0)
15174 SeparatorText(g.ContextName);
15175 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
15176 {
15177 ImGuiWindow* window = g.WindowsFocusOrder[n];
15178 IM_ASSERT(window != NULL); // Fix static analyzers
15179 if (!IsWindowNavFocusable(window))
15180 continue;
15181 const char* label = window->Name;
15182 if (label == FindRenderedTextEnd(label))
15183 label = GetFallbackWindowNameForWindowingList(window);
15184 Selectable(label, g.NavWindowingTarget == window);
15185 }
15186 End();
15187 PopStyleVar();
15188 }
15189
15190 //-----------------------------------------------------------------------------
15191 // [SECTION] DRAG AND DROP
15192 //-----------------------------------------------------------------------------
15193
15194 bool ImGui::IsDragDropActive()
15195 {
15196 ImGuiContext& g = *GImGui;
15197 return g.DragDropActive;
15198 }
15199
15200 void ImGui::ClearDragDrop()
15201 {
15202 ImGuiContext& g = *GImGui;
15203 if (g.DragDropActive)
15204 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
15205 g.DragDropActive = false;
15206 g.DragDropPayload.Clear();
15207 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
15208 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
15209 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
15210 g.DragDropAcceptFrameCount = -1;
15211
15212 g.DragDropPayloadBufHeap.clear();
15213 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
15214 }
15215
15216 bool ImGui::BeginTooltipHidden()
15217 {
15218 ImGuiContext& g = *GImGui;
15219 bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
15220 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
15221 return ret;
15222 }
15223
15224 // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
15225 // If the item has an identifier:
15226 // - This assume/require the item to be activated (typically via ButtonBehavior).
15227 // - 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.
15228 // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
15229 // If the item has no identifier:
15230 // - Currently always assume left mouse button.
15231 bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
15232 {
15233 ImGuiContext& g = *GImGui;
15234 ImGuiWindow* window = g.CurrentWindow;
15235
15236 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
15237 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
15238 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
15239
15240 bool source_drag_active = false;
15241 ImGuiID source_id = 0;
15242 ImGuiID source_parent_id = 0;
15243 if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
15244 {
15245 source_id = g.LastItemData.ID;
15246 if (source_id != 0)
15247 {
15248 // Common path: items with ID
15249 if (g.ActiveId != source_id)
15250 return false;
15251 if (g.ActiveIdMouseButton != -1)
15252 mouse_button = g.ActiveIdMouseButton;
15253 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15254 return false;
15255 g.ActiveIdAllowOverlap = false;
15256 }
15257 else
15258 {
15259 // Uncommon path: items without ID
15260 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15261 return false;
15262 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
15263 return false;
15264
15265 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
15266 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
15267 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
15268 {
15269 IM_ASSERT(0);
15270 return false;
15271 }
15272
15273 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
15274 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
15275 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
15276 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
15277 // Rely on keeping other window->LastItemXXX fields intact.
15278 source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
15279 KeepAliveID(source_id);
15280 bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.ItemFlags);
15281 if (is_hovered && g.IO.MouseClicked[mouse_button])
15282 {
15283 SetActiveID(source_id, window);
15284 FocusWindow(window);
15285 }
15286 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
15287 g.ActiveIdAllowOverlap = is_hovered;
15288 }
15289 if (g.ActiveId != source_id)
15290 return false;
15291 source_parent_id = window->IDStack.back();
15292 source_drag_active = IsMouseDragging(mouse_button);
15293
15294 // Disable navigation and key inputs while dragging + cancel existing request if any
15295 SetActiveIdUsingAllKeyboardKeys();
15296 }
15297 else
15298 {
15299 // When ImGuiDragDropFlags_SourceExtern is set:
15300 window = NULL;
15301 source_id = ImHashStr("#SourceExtern");
15302 source_drag_active = true;
15303 mouse_button = g.IO.MouseDown[0] ? 0 : -1;
15304 KeepAliveID(source_id);
15305 SetActiveID(source_id, NULL);
15306 }
15307
15308 IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15309 if (!source_drag_active)
15310 return false;
15311
15312 // Activate drag and drop
15313 if (!g.DragDropActive)
15314 {
15315 IM_ASSERT(source_id != 0);
15316 ClearDragDrop();
15317 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
15318 source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
15319 ImGuiPayload& payload = g.DragDropPayload;
15320 payload.SourceId = source_id;
15321 payload.SourceParentId = source_parent_id;
15322 g.DragDropActive = true;
15323 g.DragDropSourceFlags = flags;
15324 g.DragDropMouseButton = mouse_button;
15325 if (payload.SourceId == g.ActiveId)
15326 g.ActiveIdNoClearOnFocusLoss = true;
15327 }
15328 g.DragDropSourceFrameCount = g.FrameCount;
15329 g.DragDropWithinSource = true;
15330
15331 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15332 {
15333 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
15334 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
15335 bool ret;
15336 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
15337 ret = BeginTooltipHidden();
15338 else
15339 ret = BeginTooltip();
15340 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
15341 IM_UNUSED(ret);
15342 }
15343
15344 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
15345 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
15346
15347 return true;
15348 }
15349
15350 void ImGui::EndDragDropSource()
15351 {
15352 ImGuiContext& g = *GImGui;
15353 IM_ASSERT(g.DragDropActive);
15354 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
15355
15356 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15357 EndTooltip();
15358
15359 // Discard the drag if have not called SetDragDropPayload()
15360 if (g.DragDropPayload.DataFrameCount == -1)
15361 ClearDragDrop();
15362 g.DragDropWithinSource = false;
15363 }
15364
15365 // Use 'cond' to choose to submit payload on drag start or every frame
15366 bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
15367 {
15368 ImGuiContext& g = *GImGui;
15369 ImGuiPayload& payload = g.DragDropPayload;
15370 if (cond == 0)
15371 cond = ImGuiCond_Always;
15372
15373 IM_ASSERT(type != NULL);
15374 IM_ASSERT(ImStrlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
15375 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
15376 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
15377 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
15378
15379 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
15380 {
15381 // Copy payload
15382 ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
15383 g.DragDropPayloadBufHeap.resize(0);
15384 if (data_size > sizeof(g.DragDropPayloadBufLocal))
15385 {
15386 // Store in heap
15387 g.DragDropPayloadBufHeap.resize((int)data_size);
15388 payload.Data = g.DragDropPayloadBufHeap.Data;
15389 memcpy(payload.Data, data, data_size);
15390 }
15391 else if (data_size > 0)
15392 {
15393 // Store locally
15394 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
15395 payload.Data = g.DragDropPayloadBufLocal;
15396 memcpy(payload.Data, data, data_size);
15397 }
15398 else
15399 {
15400 payload.Data = NULL;
15401 }
15402 payload.DataSize = (int)data_size;
15403 }
15404 payload.DataFrameCount = g.FrameCount;
15405
15406 // Return whether the payload has been accepted
15407 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
15408 }
15409
15410 bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
15411 {
15412 ImGuiContext& g = *GImGui;
15413 if (!g.DragDropActive)
15414 return false;
15415
15416 ImGuiWindow* window = g.CurrentWindow;
15417 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15418 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
15419 return false;
15420 IM_ASSERT(id != 0);
15421 if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
15422 return false;
15423 if (window->SkipItems)
15424 return false;
15425
15426 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15427 g.DragDropTargetRect = bb;
15428 g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
15429 g.DragDropTargetId = id;
15430 g.DragDropWithinTarget = true;
15431 return true;
15432 }
15433
15434 // We don't use BeginDragDropTargetCustom() and duplicate its code because:
15435 // 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.
15436 // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
15437 // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
15438 bool ImGui::BeginDragDropTarget()
15439 {
15440 ImGuiContext& g = *GImGui;
15441 if (!g.DragDropActive)
15442 return false;
15443
15444 ImGuiWindow* window = g.CurrentWindow;
15445 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
15446 return false;
15447 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15448 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
15449 return false;
15450
15451 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
15452 ImGuiID id = g.LastItemData.ID;
15453 if (id == 0)
15454 {
15455 id = window->GetIDFromRectangle(display_rect);
15456 KeepAliveID(id);
15457 }
15458 if (g.DragDropPayload.SourceId == id)
15459 return false;
15460
15461 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15462 g.DragDropTargetRect = display_rect;
15463 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
15464 g.DragDropTargetId = id;
15465 g.DragDropWithinTarget = true;
15466 return true;
15467 }
15468
15469 bool ImGui::IsDragDropPayloadBeingAccepted()
15470 {
15471 ImGuiContext& g = *GImGui;
15472 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
15473 }
15474
15475 const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
15476 {
15477 ImGuiContext& g = *GImGui;
15478 ImGuiPayload& payload = g.DragDropPayload;
15479 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
15480 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
15481 if (type != NULL && !payload.IsDataType(type))
15482 return NULL;
15483
15484 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
15485 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
15486 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
15487 ImRect r = g.DragDropTargetRect;
15488 float r_surface = r.GetWidth() * r.GetHeight();
15489 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
15490 return NULL;
15491
15492 g.DragDropAcceptFlags = flags;
15493 g.DragDropAcceptIdCurr = g.DragDropTargetId;
15494 g.DragDropAcceptIdCurrRectSurface = r_surface;
15495 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
15496
15497 // Render default drop visuals
15498 payload.Preview = was_accepted_previously;
15499 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
15500 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
15501 RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
15502
15503 g.DragDropAcceptFrameCount = g.FrameCount;
15504 if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
15505 payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
15506 else
15507 payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
15508 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
15509 return NULL;
15510
15511 if (payload.Delivery)
15512 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
15513 return &payload;
15514 }
15515
15516 // FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
15517 void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
15518 {
15519 ImGuiContext& g = *GImGui;
15520 ImGuiWindow* window = g.CurrentWindow;
15521 ImRect bb_display = bb;
15522 bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
15523 bb_display.Expand(3.5f);
15524 bool push_clip_rect = !window->ClipRect.Contains(bb_display);
15525 if (push_clip_rect)
15526 window->DrawList->PushClipRectFullScreen();
15527 window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI
15528 if (push_clip_rect)
15529 window->DrawList->PopClipRect();
15530 }
15531
15532 const ImGuiPayload* ImGui::GetDragDropPayload()
15533 {
15534 ImGuiContext& g = *GImGui;
15535 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
15536 }
15537
15538 void ImGui::EndDragDropTarget()
15539 {
15540 ImGuiContext& g = *GImGui;
15541 IM_ASSERT(g.DragDropActive);
15542 IM_ASSERT(g.DragDropWithinTarget);
15543 g.DragDropWithinTarget = false;
15544
15545 // Clear drag and drop state payload right after delivery
15546 if (g.DragDropPayload.Delivery)
15547 ClearDragDrop();
15548 }
15549
15550 //-----------------------------------------------------------------------------
15551 // [SECTION] LOGGING/CAPTURING
15552 //-----------------------------------------------------------------------------
15553 // All text output from the interface can be captured into tty/file/clipboard.
15554 // By default, tree nodes are automatically opened during logging.
15555 //-----------------------------------------------------------------------------
15556
15557 // Pass text data straight to log (without being displayed)
15558 static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
15559 {
15560 if (g.LogFile)
15561 {
15562 g.LogBuffer.Buf.resize(0);
15563 g.LogBuffer.appendfv(fmt, args);
15564 ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
15565 }
15566 else
15567 {
15568 g.LogBuffer.appendfv(fmt, args);
15569 }
15570 }
15571
15572 void ImGui::LogText(const char* fmt, ...)
15573 {
15574 ImGuiContext& g = *GImGui;
15575 if (!g.LogEnabled)
15576 return;
15577
15578 va_list args;
15579 va_start(args, fmt);
15580 LogTextV(g, fmt, args);
15581 va_end(args);
15582 }
15583
15584 void ImGui::LogTextV(const char* fmt, va_list args)
15585 {
15586 ImGuiContext& g = *GImGui;
15587 if (!g.LogEnabled)
15588 return;
15589
15590 LogTextV(g, fmt, args);
15591 }
15592
15593 // Internal version that takes a position to decide on newline placement and pad items according to their depth.
15594 // We split text into individual lines to add current tree level padding
15595 // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
15596 void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
15597 {
15598 ImGuiContext& g = *GImGui;
15599 ImGuiWindow* window = g.CurrentWindow;
15600
15601 const char* prefix = g.LogNextPrefix;
15602 const char* suffix = g.LogNextSuffix;
15603 g.LogNextPrefix = g.LogNextSuffix = NULL;
15604
15605 if (!text_end)
15606 text_end = FindRenderedTextEnd(text, text_end);
15607
15608 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
15609 if (ref_pos)
15610 g.LogLinePosY = ref_pos->y;
15611 if (log_new_line)
15612 {
15613 LogText(IM_NEWLINE);
15614 g.LogLineFirstItem = true;
15615 }
15616
15617 if (prefix)
15618 LogRenderedText(ref_pos, prefix, prefix + ImStrlen(prefix)); // Calculate end ourself to ensure "##" are included here.
15619
15620 // Re-adjust padding if we have popped out of our starting depth
15621 if (g.LogDepthRef > window->DC.TreeDepth)
15622 g.LogDepthRef = window->DC.TreeDepth;
15623 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
15624
15625 const char* text_remaining = text;
15626 for (;;)
15627 {
15628 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
15629 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
15630 const char* line_start = text_remaining;
15631 const char* line_end = ImStreolRange(line_start, text_end);
15632 const bool is_last_line = (line_end == text_end);
15633 if (line_start != line_end || !is_last_line)
15634 {
15635 const int line_length = (int)(line_end - line_start);
15636 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
15637 LogText("%*s%.*s", indentation, "", line_length, line_start);
15638 g.LogLineFirstItem = false;
15639 if (*line_end == '\n')
15640 {
15641 LogText(IM_NEWLINE);
15642 g.LogLineFirstItem = true;
15643 }
15644 }
15645 if (is_last_line)
15646 break;
15647 text_remaining = line_end + 1;
15648 }
15649
15650 if (suffix)
15651 LogRenderedText(ref_pos, suffix, suffix + ImStrlen(suffix));
15652 }
15653
15654 // Start logging/capturing text output
15655 void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
15656 {
15657 ImGuiContext& g = *GImGui;
15658 ImGuiWindow* window = g.CurrentWindow;
15659 IM_ASSERT(g.LogEnabled == false);
15660 IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
15661 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
15662
15663 g.LogEnabled = g.ItemUnclipByLog = true;
15664 g.LogFlags = flags;
15665 g.LogWindow = window;
15666 g.LogNextPrefix = g.LogNextSuffix = NULL;
15667 g.LogDepthRef = window->DC.TreeDepth;
15668 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
15669 g.LogLinePosY = FLT_MAX;
15670 g.LogLineFirstItem = true;
15671 }
15672
15673 // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
15674 void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
15675 {
15676 ImGuiContext& g = *GImGui;
15677 g.LogNextPrefix = prefix;
15678 g.LogNextSuffix = suffix;
15679 }
15680
15681 void ImGui::LogToTTY(int auto_open_depth)
15682 {
15683 ImGuiContext& g = *GImGui;
15684 if (g.LogEnabled)
15685 return;
15686 IM_UNUSED(auto_open_depth);
15687 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15688 LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth);
15689 g.LogFile = stdout;
15690 #endif
15691 }
15692
15693 // Start logging/capturing text output to given file
15694 void ImGui::LogToFile(int auto_open_depth, const char* filename)
15695 {
15696 ImGuiContext& g = *GImGui;
15697 if (g.LogEnabled)
15698 return;
15699
15700 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
15701 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
15702 // By opening the file in binary mode "ab" we have consistent output everywhere.
15703 if (!filename)
15704 filename = g.IO.LogFilename;
15705 if (!filename || !filename[0])
15706 return;
15707 ImFileHandle f = ImFileOpen(filename, "ab");
15708 if (!f)
15709 {
15710 IM_ASSERT(0);
15711 return;
15712 }
15713
15714 LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth);
15715 g.LogFile = f;
15716 }
15717
15718 // Start logging/capturing text output to clipboard
15719 void ImGui::LogToClipboard(int auto_open_depth)
15720 {
15721 ImGuiContext& g = *GImGui;
15722 if (g.LogEnabled)
15723 return;
15724 LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth);
15725 }
15726
15727 void ImGui::LogToBuffer(int auto_open_depth)
15728 {
15729 ImGuiContext& g = *GImGui;
15730 if (g.LogEnabled)
15731 return;
15732 LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth);
15733 }
15734
15735 void ImGui::LogFinish()
15736 {
15737 ImGuiContext& g = *GImGui;
15738 if (!g.LogEnabled)
15739 return;
15740
15741 LogText(IM_NEWLINE);
15742 switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
15743 {
15744 case ImGuiLogFlags_OutputTTY:
15745 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15746 fflush(g.LogFile);
15747 #endif
15748 break;
15749 case ImGuiLogFlags_OutputFile:
15750 ImFileClose(g.LogFile);
15751 break;
15752 case ImGuiLogFlags_OutputBuffer:
15753 break;
15754 case ImGuiLogFlags_OutputClipboard:
15755 if (!g.LogBuffer.empty())
15756 SetClipboardText(g.LogBuffer.begin());
15757 break;
15758 default:
15759 IM_ASSERT(0);
15760 break;
15761 }
15762
15763 g.LogEnabled = g.ItemUnclipByLog = false;
15764 g.LogFlags = ImGuiLogFlags_None;
15765 g.LogFile = NULL;
15766 g.LogBuffer.clear();
15767 }
15768
15769 // Helper to display logging buttons
15770 // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
15771 void ImGui::LogButtons()
15772 {
15773 ImGuiContext& g = *GImGui;
15774
15775 PushID("LogButtons");
15776 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15777 const bool log_to_tty = Button("Log To TTY"); SameLine();
15778 #else
15779 const bool log_to_tty = false;
15780 #endif
15781 const bool log_to_file = Button("Log To File"); SameLine();
15782 const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
15783 PushItemFlag(ImGuiItemFlags_NoTabStop, true);
15784 SetNextItemWidth(80.0f);
15785 SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
15786 PopItemFlag();
15787 PopID();
15788
15789 // Start logging at the end of the function so that the buttons don't appear in the log
15790 if (log_to_tty)
15791 LogToTTY();
15792 if (log_to_file)
15793 LogToFile();
15794 if (log_to_clipboard)
15795 LogToClipboard();
15796 }
15797
15798 //-----------------------------------------------------------------------------
15799 // [SECTION] SETTINGS
15800 //-----------------------------------------------------------------------------
15801 // - UpdateSettings() [Internal]
15802 // - MarkIniSettingsDirty() [Internal]
15803 // - FindSettingsHandler() [Internal]
15804 // - ClearIniSettings() [Internal]
15805 // - LoadIniSettingsFromDisk()
15806 // - LoadIniSettingsFromMemory()
15807 // - SaveIniSettingsToDisk()
15808 // - SaveIniSettingsToMemory()
15809 //-----------------------------------------------------------------------------
15810 // - CreateNewWindowSettings() [Internal]
15811 // - FindWindowSettingsByID() [Internal]
15812 // - FindWindowSettingsByWindow() [Internal]
15813 // - ClearWindowSettings() [Internal]
15814 // - WindowSettingsHandler_***() [Internal]
15815 //-----------------------------------------------------------------------------
15816
15817 // Called by NewFrame()
15818 void ImGui::UpdateSettings()
15819 {
15820 // Load settings on first frame (if not explicitly loaded manually before)
15821 ImGuiContext& g = *GImGui;
15822 if (!g.SettingsLoaded)
15823 {
15824 IM_ASSERT(g.SettingsWindows.empty());
15825 if (g.IO.IniFilename)
15826 LoadIniSettingsFromDisk(g.IO.IniFilename);
15827 g.SettingsLoaded = true;
15828 }
15829
15830 // Save settings (with a delay after the last modification, so we don't spam disk too much)
15831 if (g.SettingsDirtyTimer > 0.0f)
15832 {
15833 g.SettingsDirtyTimer -= g.IO.DeltaTime;
15834 if (g.SettingsDirtyTimer <= 0.0f)
15835 {
15836 if (g.IO.IniFilename != NULL)
15837 SaveIniSettingsToDisk(g.IO.IniFilename);
15838 else
15839 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
15840 g.SettingsDirtyTimer = 0.0f;
15841 }
15842 }
15843 }
15844
15845 void ImGui::MarkIniSettingsDirty()
15846 {
15847 ImGuiContext& g = *GImGui;
15848 if (g.SettingsDirtyTimer <= 0.0f)
15849 g.SettingsDirtyTimer = g.IO.IniSavingRate;
15850 }
15851
15852 void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
15853 {
15854 ImGuiContext& g = *GImGui;
15855 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
15856 if (g.SettingsDirtyTimer <= 0.0f)
15857 g.SettingsDirtyTimer = g.IO.IniSavingRate;
15858 }
15859
15860 void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
15861 {
15862 ImGuiContext& g = *GImGui;
15863 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
15864 g.SettingsHandlers.push_back(*handler);
15865 }
15866
15867 void ImGui::RemoveSettingsHandler(const char* type_name)
15868 {
15869 ImGuiContext& g = *GImGui;
15870 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
15871 g.SettingsHandlers.erase(handler);
15872 }
15873
15874 ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
15875 {
15876 ImGuiContext& g = *GImGui;
15877 const ImGuiID type_hash = ImHashStr(type_name);
15878 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15879 if (handler.TypeHash == type_hash)
15880 return &handler;
15881 return NULL;
15882 }
15883
15884 // Clear all settings (windows, tables, docking etc.)
15885 void ImGui::ClearIniSettings()
15886 {
15887 ImGuiContext& g = *GImGui;
15888 g.SettingsIniData.clear();
15889 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15890 if (handler.ClearAllFn != NULL)
15891 handler.ClearAllFn(&g, &handler);
15892 }
15893
15894 void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
15895 {
15896 size_t file_data_size = 0;
15897 char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
15898 if (!file_data)
15899 return;
15900 if (file_data_size > 0)
15901 LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
15902 IM_FREE(file_data);
15903 }
15904
15905 // Zero-tolerance, no error reporting, cheap .ini parsing
15906 // 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!
15907 void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
15908 {
15909 ImGuiContext& g = *GImGui;
15910 IM_ASSERT(g.Initialized);
15911 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
15912 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
15913
15914 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
15915 // 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..
15916 if (ini_size == 0)
15917 ini_size = ImStrlen(ini_data);
15918 g.SettingsIniData.Buf.resize((int)ini_size + 1);
15919 char* const buf = g.SettingsIniData.Buf.Data;
15920 char* const buf_end = buf + ini_size;
15921 memcpy(buf, ini_data, ini_size);
15922 buf_end[0] = 0;
15923
15924 // Call pre-read handlers
15925 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
15926 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15927 if (handler.ReadInitFn != NULL)
15928 handler.ReadInitFn(&g, &handler);
15929
15930 void* entry_data = NULL;
15931 ImGuiSettingsHandler* entry_handler = NULL;
15932
15933 char* line_end = NULL;
15934 for (char* line = buf; line < buf_end; line = line_end + 1)
15935 {
15936 // Skip new lines markers, then find end of the line
15937 while (*line == '\n' || *line == '\r')
15938 line++;
15939 line_end = line;
15940 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
15941 line_end++;
15942 line_end[0] = 0;
15943 if (line[0] == ';')
15944 continue;
15945 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
15946 {
15947 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
15948 line_end[-1] = 0;
15949 const char* name_end = line_end - 1;
15950 const char* type_start = line + 1;
15951 char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
15952 const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
15953 if (!type_end || !name_start)
15954 continue;
15955 *type_end = 0; // Overwrite first ']'
15956 name_start++; // Skip second '['
15957 entry_handler = FindSettingsHandler(type_start);
15958 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
15959 }
15960 else if (entry_handler != NULL && entry_data != NULL)
15961 {
15962 // Let type handler parse the line
15963 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
15964 }
15965 }
15966 g.SettingsLoaded = true;
15967
15968 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
15969 memcpy(buf, ini_data, ini_size);
15970
15971 // Call post-read handlers
15972 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15973 if (handler.ApplyAllFn != NULL)
15974 handler.ApplyAllFn(&g, &handler);
15975 }
15976
15977 void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
15978 {
15979 ImGuiContext& g = *GImGui;
15980 g.SettingsDirtyTimer = 0.0f;
15981 if (!ini_filename)
15982 return;
15983
15984 size_t ini_data_size = 0;
15985 const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
15986 ImFileHandle f = ImFileOpen(ini_filename, "wt");
15987 if (!f)
15988 return;
15989 ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
15990 ImFileClose(f);
15991 }
15992
15993 // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
15994 const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
15995 {
15996 ImGuiContext& g = *GImGui;
15997 g.SettingsDirtyTimer = 0.0f;
15998 g.SettingsIniData.Buf.resize(0);
15999 g.SettingsIniData.Buf.push_back(0);
16000 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
16001 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
16002 if (out_size)
16003 *out_size = (size_t)g.SettingsIniData.size();
16004 return g.SettingsIniData.c_str();
16005 }
16006
16007 ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
16008 {
16009 ImGuiContext& g = *GImGui;
16010
16011 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
16012 if (g.IO.ConfigDebugIniSettings == false)
16013 name = ImHashSkipUncontributingPrefix(name);
16014 const size_t name_len = ImStrlen(name);
16015
16016 // Allocate chunk
16017 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
16018 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
16019 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
16020 settings->ID = ImHashStr(name, name_len);
16021 memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
16022
16023 return settings;
16024 }
16025
16026 // We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
16027 // This is called once per window .ini entry + once per newly instantiated window.
16028 ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
16029 {
16030 ImGuiContext& g = *GImGui;
16031 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16032 if (settings->ID == id && !settings->WantDelete)
16033 return settings;
16034 return NULL;
16035 }
16036
16037 // This is faster if you are holding on a Window already as we don't need to perform a search.
16038 ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
16039 {
16040 ImGuiContext& g = *GImGui;
16041 if (window->SettingsOffset != -1)
16042 return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
16043 return FindWindowSettingsByID(window->ID);
16044 }
16045
16046 // This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
16047 void ImGui::ClearWindowSettings(const char* name)
16048 {
16049 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
16050 ImGuiContext& g = *GImGui;
16051 ImGuiWindow* window = FindWindowByName(name);
16052 if (window != NULL)
16053 {
16054 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
16055 InitOrLoadWindowSettings(window, NULL);
16056 if (window->DockId != 0)
16057 DockContextProcessUndockWindow(&g, window, true);
16058 }
16059 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
16060 settings->WantDelete = true;
16061 }
16062
16063 static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
16064 {
16065 ImGuiContext& g = *ctx;
16066 for (ImGuiWindow* window : g.Windows)
16067 window->SettingsOffset = -1;
16068 g.SettingsWindows.clear();
16069 }
16070
16071 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
16072 {
16073 ImGuiID id = ImHashStr(name);
16074 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
16075 if (settings)
16076 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
16077 else
16078 settings = ImGui::CreateNewWindowSettings(name);
16079 settings->ID = id;
16080 settings->WantApply = true;
16081 return (void*)settings;
16082 }
16083
16084 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
16085 {
16086 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
16087 int x, y;
16088 int i;
16089 ImU32 u1;
16090 if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
16091 else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
16092 else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
16093 else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
16094 else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
16095 else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
16096 else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
16097 else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
16098 else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
16099 }
16100
16101 // Apply to existing windows (if any)
16102 static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
16103 {
16104 ImGuiContext& g = *ctx;
16105 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16106 if (settings->WantApply)
16107 {
16108 if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
16109 ApplyWindowSettings(window, settings);
16110 settings->WantApply = false;
16111 }
16112 }
16113
16114 static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
16115 {
16116 // Gather data from windows that were active during this session
16117 // (if a window wasn't opened in this session we preserve its settings)
16118 ImGuiContext& g = *ctx;
16119 for (ImGuiWindow* window : g.Windows)
16120 {
16121 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
16122 continue;
16123
16124 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
16125 if (!settings)
16126 {
16127 settings = ImGui::CreateNewWindowSettings(window->Name);
16128 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
16129 }
16130 IM_ASSERT(settings->ID == window->ID);
16131 settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
16132 settings->Size = ImVec2ih(window->SizeFull);
16133 settings->ViewportId = window->ViewportId;
16134 settings->ViewportPos = ImVec2ih(window->ViewportPos);
16135 IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
16136 settings->DockId = window->DockId;
16137 settings->ClassId = window->WindowClass.ClassId;
16138 settings->DockOrder = window->DockOrder;
16139 settings->Collapsed = window->Collapsed;
16140 settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
16141 settings->WantDelete = false;
16142 }
16143
16144 // Write to text buffer
16145 buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
16146 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16147 {
16148 if (settings->WantDelete)
16149 continue;
16150 const char* settings_name = settings->GetName();
16151 buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
16152 if (settings->IsChild)
16153 {
16154 buf->appendf("IsChild=1\n");
16155 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
16156 }
16157 else
16158 {
16159 if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
16160 {
16161 buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
16162 buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
16163 }
16164 if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
16165 buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
16166 if (settings->Size.x != 0 || settings->Size.y != 0)
16167 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
16168 buf->appendf("Collapsed=%d\n", settings->Collapsed);
16169 if (settings->DockId != 0)
16170 {
16171 //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.
16172 if (settings->DockOrder == -1)
16173 buf->appendf("DockId=0x%08X\n", settings->DockId);
16174 else
16175 buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
16176 if (settings->ClassId != 0)
16177 buf->appendf("ClassId=0x%08X\n", settings->ClassId);
16178 }
16179 }
16180 buf->append("\n");
16181 }
16182 }
16183
16184 //-----------------------------------------------------------------------------
16185 // [SECTION] LOCALIZATION
16186 //-----------------------------------------------------------------------------
16187
16188 void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
16189 {
16190 ImGuiContext& g = *GImGui;
16191 for (int n = 0; n < count; n++)
16192 g.LocalizationTable[entries[n].Key] = entries[n].Text;
16193 }
16194
16195 //-----------------------------------------------------------------------------
16196 // [SECTION] VIEWPORTS, PLATFORM WINDOWS
16197 //-----------------------------------------------------------------------------
16198 // - GetMainViewport()
16199 // - FindViewportByID()
16200 // - FindViewportByPlatformHandle()
16201 // - SetCurrentViewport() [Internal]
16202 // - SetWindowViewport() [Internal]
16203 // - GetWindowAlwaysWantOwnViewport() [Internal]
16204 // - UpdateTryMergeWindowIntoHostViewport() [Internal]
16205 // - UpdateTryMergeWindowIntoHostViewports() [Internal]
16206 // - TranslateWindowsInViewport() [Internal]
16207 // - ScaleWindowsInViewport() [Internal]
16208 // - FindHoveredViewportFromPlatformWindowStack() [Internal]
16209 // - UpdateViewportsNewFrame() [Internal]
16210 // - UpdateViewportsEndFrame() [Internal]
16211 // - AddUpdateViewport() [Internal]
16212 // - WindowSelectViewport() [Internal]
16213 // - WindowSyncOwnedViewport() [Internal]
16214 // - UpdatePlatformWindows()
16215 // - RenderPlatformWindowsDefault()
16216 // - FindPlatformMonitorForPos() [Internal]
16217 // - FindPlatformMonitorForRect() [Internal]
16218 // - UpdateViewportPlatformMonitor() [Internal]
16219 // - DestroyPlatformWindow() [Internal]
16220 // - DestroyPlatformWindows()
16221 //-----------------------------------------------------------------------------
16222
16223 ImGuiViewport* ImGui::GetMainViewport()
16224 {
16225 ImGuiContext& g = *GImGui;
16226 return g.Viewports[0];
16227 }
16228
16229 // FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
16230 ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
16231 {
16232 ImGuiContext& g = *GImGui;
16233 for (ImGuiViewportP* viewport : g.Viewports)
16234 if (viewport->ID == id)
16235 return viewport;
16236 return NULL;
16237 }
16238
16239 ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
16240 {
16241 ImGuiContext& g = *GImGui;
16242 for (ImGuiViewportP* viewport : g.Viewports)
16243 if (viewport->PlatformHandle == platform_handle)
16244 return viewport;
16245 return NULL;
16246 }
16247
16248 void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
16249 {
16250 ImGuiContext& g = *GImGui;
16251 (void)current_window;
16252
16253 if (viewport)
16254 viewport->LastFrameActive = g.FrameCount;
16255 if (g.CurrentViewport == viewport)
16256 return;
16257 g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
16258 g.CurrentViewport = viewport;
16259 IM_ASSERT(g.CurrentDpiScale > 0.0f && g.CurrentDpiScale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
16260 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
16261 if (g.IO.ConfigDpiScaleFonts)
16262 g.Style.FontScaleDpi = g.CurrentDpiScale;
16263
16264 // Notify platform layer of viewport changes
16265 // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
16266 if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
16267 g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
16268 }
16269
16270 void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16271 {
16272 // Abandon viewport
16273 if (window->ViewportOwned && window->Viewport->Window == window)
16274 window->Viewport->Size = ImVec2(0.0f, 0.0f);
16275
16276 window->Viewport = viewport;
16277 window->ViewportId = viewport->ID;
16278 window->ViewportOwned = (viewport->Window == window);
16279 }
16280
16281 static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
16282 {
16283 // 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.
16284 ImGuiContext& g = *GImGui;
16285 if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
16286 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16287 if (!window->DockIsActive)
16288 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
16289 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
16290 return true;
16291 return false;
16292 }
16293
16294 static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16295 {
16296 ImGuiContext& g = *GImGui;
16297 if (window->Viewport == viewport)
16298 return false;
16299 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
16300 return false;
16301 if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
16302 return false;
16303 if (!viewport->GetMainRect().Contains(window->Rect()))
16304 return false;
16305 if (GetWindowAlwaysWantOwnViewport(window))
16306 return false;
16307
16308 // 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..
16309 for (ImGuiWindow* window_behind : g.Windows)
16310 {
16311 if (window_behind == window)
16312 break;
16313 if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
16314 if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
16315 return false;
16316 }
16317
16318 // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
16319 ImGuiViewportP* old_viewport = window->Viewport;
16320 if (window->ViewportOwned)
16321 for (int n = 0; n < g.Windows.Size; n++)
16322 if (g.Windows[n]->Viewport == old_viewport)
16323 SetWindowViewport(g.Windows[n], viewport);
16324 SetWindowViewport(window, viewport);
16325 BringWindowToDisplayFront(window);
16326
16327 return true;
16328 }
16329
16330 // FIXME: handle 0 to N host viewports
16331 static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
16332 {
16333 ImGuiContext& g = *GImGui;
16334 return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
16335 }
16336
16337 // Translate Dear ImGui windows when a Host Viewport has been moved
16338 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
16339 void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size)
16340 {
16341 ImGuiContext& g = *GImGui;
16342 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X\n", viewport->ID);
16343 IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
16344
16345 // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
16346 // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
16347 // 2) If it's not going to fit into the new size, keep it at same absolute position.
16348 // One problem with this is that most Win32 applications doesn't update their render while dragging,
16349 // and so the window will appear to teleport when releasing the mouse.
16350 const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
16351 ImRect test_still_fit_rect(old_pos, old_pos + old_size);
16352 ImVec2 delta_pos = new_pos - old_pos;
16353 for (ImGuiWindow* window : g.Windows) // FIXME-OPT
16354 if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(window->Rect()))))
16355 TranslateWindow(window, delta_pos);
16356 }
16357
16358 // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
16359 void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
16360 {
16361 ImGuiContext& g = *GImGui;
16362 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport->ID);
16363 if (viewport->Window)
16364 {
16365 ScaleWindow(viewport->Window, scale);
16366 }
16367 else
16368 {
16369 for (ImGuiWindow* window : g.Windows)
16370 if (window->Viewport == viewport)
16371 ScaleWindow(window, scale);
16372 }
16373 }
16374
16375 // If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
16376 // A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
16377 // B) It requires Platform_GetWindowFocus to be implemented by backend.
16378 ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
16379 {
16380 ImGuiContext& g = *GImGui;
16381 ImGuiViewportP* best_candidate = NULL;
16382 for (ImGuiViewportP* viewport : g.Viewports)
16383 if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
16384 if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
16385 best_candidate = viewport;
16386 return best_candidate;
16387 }
16388
16389 // Update viewports and monitor infos
16390 // Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
16391 static void ImGui::UpdateViewportsNewFrame()
16392 {
16393 ImGuiContext& g = *GImGui;
16394 IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
16395
16396 // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
16397 // Update Focused status
16398 const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
16399 if (viewports_enabled)
16400 {
16401 ImGuiViewportP* focused_viewport = NULL;
16402 for (ImGuiViewportP* viewport : g.Viewports)
16403 {
16404 const bool platform_funcs_available = viewport->PlatformWindowCreated;
16405 if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
16406 {
16407 bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
16408 if (is_minimized)
16409 viewport->Flags |= ImGuiViewportFlags_IsMinimized;
16410 else
16411 viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
16412 }
16413
16414 // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
16415 // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
16416 if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
16417 {
16418 bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
16419 if (is_focused)
16420 viewport->Flags |= ImGuiViewportFlags_IsFocused;
16421 else
16422 viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
16423 if (is_focused)
16424 focused_viewport = viewport;
16425 }
16426 }
16427
16428 // Focused viewport has changed?
16429 if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
16430 {
16431 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");
16432 const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
16433 const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
16434
16435 // Store a tag so we can infer z-order easily from all our windows
16436 // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
16437 // will keep the front most stamp instead of losing it back to their parent viewport.
16438 if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
16439 focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
16440 g.PlatformLastFocusedViewportId = focused_viewport->ID;
16441
16442 // Focus associated dear imgui window
16443 // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
16444 // - if focus didn't happen because we destroyed another window (#6462)
16445 // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
16446 const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
16447 if (apply_imgui_focus_on_focused_viewport && g.IO.ConfigViewportPlatformFocusSetsImGuiFocus)
16448 {
16449 focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
16450 ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
16451 if (focused_viewport->Window != NULL)
16452 FocusWindow(focused_viewport->Window, focus_request_flags);
16453 else if (focused_viewport->LastFocusedHadNavWindow)
16454 FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
16455 else
16456 FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
16457 }
16458 }
16459 if (focused_viewport)
16460 focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
16461 }
16462
16463 // Create/update main viewport with current platform position.
16464 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
16465 ImGuiViewportP* main_viewport = g.Viewports[0];
16466 IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
16467 IM_ASSERT(main_viewport->Window == NULL);
16468 ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
16469 ImVec2 main_viewport_size = g.IO.DisplaySize;
16470 ImVec2 main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale;
16471 if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
16472 {
16473 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)
16474 main_viewport_size = main_viewport->Size;
16475 main_viewport_framebuffer_scale = main_viewport->FramebufferScale;
16476 }
16477 AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
16478
16479 g.CurrentDpiScale = 0.0f;
16480 g.CurrentViewport = NULL;
16481 g.MouseViewport = NULL;
16482 for (int n = 0; n < g.Viewports.Size; n++)
16483 {
16484 ImGuiViewportP* viewport = g.Viewports[n];
16485 viewport->Idx = n;
16486
16487 // Erase unused viewports
16488 if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
16489 {
16490 DestroyViewport(viewport);
16491 n--;
16492 continue;
16493 }
16494
16495 const bool platform_funcs_available = viewport->PlatformWindowCreated;
16496 if (viewports_enabled)
16497 {
16498 // Update Position and Size (from Platform Window to ImGui) if requested.
16499 // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
16500 if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
16501 {
16502 // Viewport->WorkPos and WorkSize will be updated below
16503 if (viewport->PlatformRequestMove)
16504 viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
16505 if (viewport->PlatformRequestResize)
16506 viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
16507 if (g.PlatformIO.Platform_GetWindowFramebufferScale != NULL)
16508 viewport->FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport);
16509 }
16510 }
16511
16512 // Update/copy monitor info
16513 UpdateViewportPlatformMonitor(viewport);
16514
16515 // Lock down space taken by menu bars and status bars + query initial insets from backend
16516 // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
16517 viewport->WorkInsetMin = viewport->BuildWorkInsetMin;
16518 viewport->WorkInsetMax = viewport->BuildWorkInsetMax;
16519 viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f);
16520 if (g.PlatformIO.Platform_GetWindowWorkAreaInsets != NULL && platform_funcs_available)
16521 {
16522 ImVec4 insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport);
16523 IM_ASSERT(insets.x >= 0.0f && insets.y >= 0.0f && insets.z >= 0.0f && insets.w >= 0.0f);
16524 viewport->BuildWorkInsetMin = ImVec2(insets.x, insets.y);
16525 viewport->BuildWorkInsetMax = ImVec2(insets.z, insets.w);
16526 }
16527 viewport->UpdateWorkRect();
16528
16529 // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
16530 viewport->Alpha = 1.0f;
16531
16532 // Translate Dear ImGui windows when a Host Viewport has been moved
16533 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
16534 const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
16535 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
16536 TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos, viewport->LastSize, viewport->Size);
16537
16538 // Update DPI scale
16539 float new_dpi_scale;
16540 if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
16541 new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
16542 else if (viewport->PlatformMonitor != -1)
16543 new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
16544 else
16545 new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
16546 IM_ASSERT(new_dpi_scale > 0.0f && new_dpi_scale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
16547 if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
16548 {
16549 float scale_factor = new_dpi_scale / viewport->DpiScale;
16550 if (g.IO.ConfigDpiScaleViewports)
16551 ScaleWindowsInViewport(viewport, scale_factor);
16552 //if (viewport == GetMainViewport())
16553 // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
16554
16555 // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
16556 // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
16557 // (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.)
16558 //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
16559 // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
16560 }
16561 viewport->DpiScale = new_dpi_scale;
16562 }
16563
16564 // Update fallback monitor
16565 g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
16566 if (g.PlatformIO.Monitors.Size == 0)
16567 {
16568 ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
16569 monitor->MainPos = main_viewport->Pos;
16570 monitor->MainSize = main_viewport->Size;
16571 monitor->WorkPos = main_viewport->WorkPos;
16572 monitor->WorkSize = main_viewport->WorkSize;
16573 monitor->DpiScale = main_viewport->DpiScale;
16574 g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
16575 g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
16576 }
16577 else
16578 {
16579 g.FallbackMonitor = g.PlatformIO.Monitors[0];
16580 }
16581 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
16582 {
16583 g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
16584 g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
16585 }
16586
16587 if (!viewports_enabled)
16588 {
16589 g.MouseViewport = main_viewport;
16590 return;
16591 }
16592
16593 // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
16594 // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
16595 ImGuiViewportP* viewport_hovered = NULL;
16596 if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
16597 {
16598 viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
16599 if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
16600 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
16601 }
16602 else
16603 {
16604 // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
16605 // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
16606 // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
16607 // 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)
16608 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
16609 }
16610 if (viewport_hovered != NULL)
16611 g.MouseLastHoveredViewport = viewport_hovered;
16612 else if (g.MouseLastHoveredViewport == NULL)
16613 g.MouseLastHoveredViewport = g.Viewports[0];
16614
16615 // Update mouse reference viewport
16616 // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
16617 // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
16618 if (g.MovingWindow && g.MovingWindow->Viewport)
16619 g.MouseViewport = g.MovingWindow->Viewport;
16620 else
16621 g.MouseViewport = g.MouseLastHoveredViewport;
16622
16623 // When dragging something, always refer to the last hovered viewport.
16624 // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
16625 // - 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)
16626 // - 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.
16627 // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
16628 const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
16629 if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
16630 viewport_hovered = g.MouseLastHoveredViewport;
16631 if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
16632 if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
16633 g.MouseViewport = viewport_hovered;
16634
16635 IM_ASSERT(g.MouseViewport != NULL);
16636 }
16637
16638 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
16639 static void ImGui::UpdateViewportsEndFrame()
16640 {
16641 ImGuiContext& g = *GImGui;
16642 g.PlatformIO.Viewports.resize(0);
16643 for (int i = 0; i < g.Viewports.Size; i++)
16644 {
16645 ImGuiViewportP* viewport = g.Viewports[i];
16646 viewport->LastPos = viewport->Pos;
16647 viewport->LastSize = viewport->Size;
16648 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
16649 if (i > 0) // Always include main viewport in the list
16650 continue;
16651 if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
16652 continue;
16653 if (i > 0)
16654 IM_ASSERT(viewport->Window != NULL);
16655 g.PlatformIO.Viewports.push_back(viewport);
16656 }
16657 g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
16658 }
16659
16660 // FIXME: We should ideally refactor the system to call this every frame (we currently don't)
16661 ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
16662 {
16663 ImGuiContext& g = *GImGui;
16664 IM_ASSERT(id != 0);
16665
16666 flags |= ImGuiViewportFlags_IsPlatformWindow;
16667 if (window != NULL)
16668 {
16669 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
16670 if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
16671 flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
16672 if (!window_can_use_inputs)
16673 flags |= ImGuiViewportFlags_NoInputs;
16674 if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
16675 flags |= ImGuiViewportFlags_NoFocusOnAppearing;
16676 }
16677
16678 ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
16679 if (viewport)
16680 {
16681 // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
16682 ImVec2 prev_pos = viewport->Pos;
16683 ImVec2 prev_size = viewport->Size;
16684 if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
16685 viewport->Pos = pos;
16686 if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
16687 viewport->Size = size;
16688 viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
16689 if (prev_pos != viewport->Pos || prev_size != viewport->Size)
16690 UpdateViewportPlatformMonitor(viewport);
16691 }
16692 else
16693 {
16694 // New viewport
16695 viewport = IM_NEW(ImGuiViewportP)();
16696 viewport->ID = id;
16697 viewport->Idx = g.Viewports.Size;
16698 viewport->Pos = viewport->LastPos = pos;
16699 viewport->Size = viewport->LastSize = size;
16700 viewport->Flags = flags;
16701 UpdateViewportPlatformMonitor(viewport);
16702 g.Viewports.push_back(viewport);
16703 g.ViewportCreatedCount++;
16704 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
16705
16706 // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
16707 // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
16708 g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
16709 g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
16710 g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
16711 g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
16712
16713 // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
16714 // This is so we can select an appropriate font size on the first frame of our window lifetime
16715 viewport->DpiScale = GetViewportPlatformMonitor(viewport)->DpiScale;
16716 }
16717
16718 viewport->Window = window;
16719 viewport->LastFrameActive = g.FrameCount;
16720 viewport->UpdateWorkRect();
16721 IM_ASSERT(window == NULL || viewport->ID == window->ID);
16722
16723 if (window != NULL)
16724 window->ViewportOwned = true;
16725
16726 return viewport;
16727 }
16728
16729 static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
16730 {
16731 // Clear references to this viewport in windows (window->ViewportId becomes the master data)
16732 ImGuiContext& g = *GImGui;
16733 for (ImGuiWindow* window : g.Windows)
16734 {
16735 if (window->Viewport != viewport)
16736 continue;
16737 window->Viewport = NULL;
16738 window->ViewportOwned = false;
16739 }
16740 if (viewport == g.MouseLastHoveredViewport)
16741 g.MouseLastHoveredViewport = NULL;
16742
16743 // Destroy
16744 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
16745 DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
16746 IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
16747 IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
16748 g.Viewports.erase(g.Viewports.Data + viewport->Idx);
16749 IM_DELETE(viewport);
16750 }
16751
16752 // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
16753 static void ImGui::WindowSelectViewport(ImGuiWindow* window)
16754 {
16755 ImGuiContext& g = *GImGui;
16756 ImGuiWindowFlags flags = window->Flags;
16757 window->ViewportAllowPlatformMonitorExtend = -1;
16758
16759 // Restore main viewport if multi-viewport is not supported by the backend
16760 ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
16761 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
16762 {
16763 SetWindowViewport(window, main_viewport);
16764 return;
16765 }
16766 window->ViewportOwned = false;
16767
16768 // Appearing popups reset their viewport so they can inherit again
16769 if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
16770 {
16771 window->Viewport = NULL;
16772 window->ViewportId = 0;
16773 }
16774
16775 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport) == 0)
16776 {
16777 // By default inherit from parent window
16778 if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
16779 window->Viewport = window->ParentWindow->Viewport;
16780
16781 // 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
16782 if (window->Viewport == NULL && window->ViewportId != 0)
16783 {
16784 window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
16785 if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
16786 window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
16787 }
16788 }
16789
16790 bool lock_viewport = false;
16791 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport)
16792 {
16793 // Code explicitly request a viewport
16794 window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
16795 window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
16796 if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
16797 {
16798 window->Viewport->Window = window;
16799 window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
16800 }
16801 lock_viewport = true;
16802 }
16803 else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
16804 {
16805 // Always inherit viewport from parent window
16806 if (window->DockNode && window->DockNode->HostWindow)
16807 IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
16808 window->Viewport = window->ParentWindow->Viewport;
16809 }
16810 else if (window->DockNode && window->DockNode->HostWindow)
16811 {
16812 // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
16813 window->Viewport = window->DockNode->HostWindow->Viewport;
16814 }
16815 else if (flags & ImGuiWindowFlags_Tooltip)
16816 {
16817 window->Viewport = g.MouseViewport;
16818 }
16819 else if (GetWindowAlwaysWantOwnViewport(window))
16820 {
16821 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
16822 }
16823 else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
16824 {
16825 if (window->Viewport != NULL && window->Viewport->Window == window)
16826 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
16827 }
16828 else
16829 {
16830 // Merge into host viewport?
16831 // We cannot test window->ViewportOwned as it set lower in the function.
16832 // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
16833 bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
16834 if (try_to_merge_into_host_viewport)
16835 UpdateTryMergeWindowIntoHostViewports(window);
16836 }
16837
16838 // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
16839 if (window->Viewport == NULL)
16840 if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
16841 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
16842
16843 // Mark window as allowed to protrude outside of its viewport and into the current monitor
16844 if (!lock_viewport)
16845 {
16846 if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
16847 {
16848 // We need to take account of the possibility that mouse may become invalid.
16849 // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
16850 ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
16851 bool use_mouse_ref = (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !g.NavWindow);
16852 bool mouse_valid = IsMousePosValid(&mouse_ref);
16853 if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
16854 window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
16855 else
16856 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
16857 }
16858 else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
16859 {
16860 // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
16861 const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
16862 if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
16863 {
16864 // Steal/transfer ownership
16865 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
16866 window->Viewport->Window = window;
16867 window->Viewport->ID = window->ID;
16868 window->Viewport->LastNameHash = 0;
16869 }
16870 else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
16871 {
16872 // New viewport
16873 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
16874 }
16875 }
16876 else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
16877 {
16878 // Regular (non-child, non-popup) windows by default are also allowed to protrude
16879 // Child windows are kept contained within their parent.
16880 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
16881 }
16882 }
16883
16884 // Update flags
16885 window->ViewportOwned = (window == window->Viewport->Window);
16886 window->ViewportId = window->Viewport->ID;
16887
16888 // If the OS window has a title bar, hide our imgui title bar
16889 //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
16890 // window->Flags |= ImGuiWindowFlags_NoTitleBar;
16891 }
16892
16893 void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
16894 {
16895 ImGuiContext& g = *GImGui;
16896
16897 bool viewport_rect_changed = false;
16898
16899 // Synchronize window --> viewport in most situations
16900 // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
16901 if (window->Viewport->PlatformRequestMove)
16902 {
16903 window->Pos = window->Viewport->Pos;
16904 MarkIniSettingsDirty(window);
16905 }
16906 else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
16907 {
16908 viewport_rect_changed = true;
16909 window->Viewport->Pos = window->Pos;
16910 }
16911
16912 if (window->Viewport->PlatformRequestResize)
16913 {
16914 window->Size = window->SizeFull = window->Viewport->Size;
16915 MarkIniSettingsDirty(window);
16916 }
16917 else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
16918 {
16919 viewport_rect_changed = true;
16920 window->Viewport->Size = window->Size;
16921 }
16922 window->Viewport->UpdateWorkRect();
16923
16924 // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
16925 // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
16926 if (viewport_rect_changed)
16927 UpdateViewportPlatformMonitor(window->Viewport);
16928
16929 // Update common viewport flags
16930 const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
16931 ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
16932 ImGuiWindowFlags window_flags = window->Flags;
16933 const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
16934 const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
16935 if (window_flags & ImGuiWindowFlags_Tooltip)
16936 viewport_flags |= ImGuiViewportFlags_TopMost;
16937 if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
16938 viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
16939 if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
16940 viewport_flags |= ImGuiViewportFlags_NoDecoration;
16941
16942 // Not correct to set modal as topmost because:
16943 // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
16944 // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
16945 //if (flags & ImGuiWindowFlags_Modal)
16946 // viewport_flags |= ImGuiViewportFlags_TopMost;
16947
16948 // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
16949 // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
16950 // 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,
16951 // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
16952 if (is_short_lived_floating_window && !is_modal)
16953 viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
16954
16955 // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
16956 if (window->WindowClass.ViewportFlagsOverrideSet)
16957 viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
16958 if (window->WindowClass.ViewportFlagsOverrideClear)
16959 viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
16960
16961 // We can also tell the backend that clearing the platform window won't be necessary,
16962 // as our window background is filling the viewport and we have disabled BgAlpha.
16963 // FIXME: Work on support for per-viewport transparency (#2766)
16964 if (!(window_flags & ImGuiWindowFlags_NoBackground))
16965 viewport_flags |= ImGuiViewportFlags_NoRendererClear;
16966
16967 window->Viewport->Flags = viewport_flags;
16968
16969 // Update parent viewport ID
16970 // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
16971 if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
16972 window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
16973 else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
16974 window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
16975 else
16976 window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
16977 }
16978
16979 // Called by user at the end of the main loop, after EndFrame()
16980 // This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
16981 void ImGui::UpdatePlatformWindows()
16982 {
16983 ImGuiContext& g = *GImGui;
16984 IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
16985 IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
16986 g.FrameCountPlatformEnded = g.FrameCount;
16987 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
16988 return;
16989
16990 // Create/resize/destroy platform windows to match each active viewport.
16991 // Skip the main viewport (index 0), which is always fully handled by the application!
16992 for (int i = 1; i < g.Viewports.Size; i++)
16993 {
16994 ImGuiViewportP* viewport = g.Viewports[i];
16995
16996 // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
16997 // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
16998 bool destroy_platform_window = false;
16999 destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
17000 destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
17001 if (destroy_platform_window)
17002 {
17003 DestroyPlatformWindow(viewport);
17004 continue;
17005 }
17006
17007 // New windows that appears directly in a new viewport won't always have a size on their first frame
17008 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
17009 continue;
17010
17011 // Create window
17012 const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
17013 if (is_new_platform_window)
17014 {
17015 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
17016 g.PlatformIO.Platform_CreateWindow(viewport);
17017 if (g.PlatformIO.Renderer_CreateWindow != NULL)
17018 g.PlatformIO.Renderer_CreateWindow(viewport);
17019 g.PlatformWindowsCreatedCount++;
17020 viewport->LastNameHash = 0;
17021 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?)
17022 viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
17023 viewport->PlatformWindowCreated = true;
17024 }
17025
17026 // Apply Position and Size (from ImGui to Platform/Renderer backends)
17027 if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
17028 g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
17029 if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
17030 g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
17031 if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
17032 g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
17033 viewport->LastPlatformPos = viewport->Pos;
17034 viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
17035
17036 // Update title bar (if it changed)
17037 if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
17038 {
17039 const char* title_begin = window_for_title->Name;
17040 char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
17041 const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
17042 if (viewport->LastNameHash != title_hash)
17043 {
17044 char title_end_backup_c = *title_end;
17045 *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
17046 g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
17047 *title_end = title_end_backup_c;
17048 viewport->LastNameHash = title_hash;
17049 }
17050 }
17051
17052 // Update alpha (if it changed)
17053 if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
17054 g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
17055 viewport->LastAlpha = viewport->Alpha;
17056
17057 // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
17058 if (g.PlatformIO.Platform_UpdateWindow)
17059 g.PlatformIO.Platform_UpdateWindow(viewport);
17060
17061 if (is_new_platform_window)
17062 {
17063 // 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)
17064 if (g.FrameCount < 3)
17065 viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
17066
17067 // Show window
17068 g.PlatformIO.Platform_ShowWindow(viewport);
17069
17070 // Even without focus, we assume the window becomes front-most.
17071 // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
17072 if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
17073 viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
17074 }
17075
17076 // Clear request flags
17077 viewport->ClearRequestFlags();
17078 }
17079 }
17080
17081 // This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
17082 // Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
17083 // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
17084 //
17085 // ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
17086 // for (int i = 1; i < platform_io.Viewports.Size; i++)
17087 // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
17088 // MyRenderFunction(platform_io.Viewports[i], my_args);
17089 // for (int i = 1; i < platform_io.Viewports.Size; i++)
17090 // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
17091 // MySwapBufferFunction(platform_io.Viewports[i], my_args);
17092 //
17093 void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
17094 {
17095 // Skip the main viewport (index 0), which is always fully handled by the application!
17096 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
17097 for (int i = 1; i < platform_io.Viewports.Size; i++)
17098 {
17099 ImGuiViewport* viewport = platform_io.Viewports[i];
17100 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
17101 continue;
17102 if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
17103 if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
17104 }
17105 for (int i = 1; i < platform_io.Viewports.Size; i++)
17106 {
17107 ImGuiViewport* viewport = platform_io.Viewports[i];
17108 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
17109 continue;
17110 if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
17111 if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
17112 }
17113 }
17114
17115 static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
17116 {
17117 ImGuiContext& g = *GImGui;
17118 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
17119 {
17120 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
17121 if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
17122 return monitor_n;
17123 }
17124 return -1;
17125 }
17126
17127 // Search for the monitor with the largest intersection area with the given rectangle
17128 // We generally try to avoid searching loops but the monitor count should be very small here
17129 // FIXME-OPT: We could test the last monitor used for that viewport first, and early
17130 static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
17131 {
17132 ImGuiContext& g = *GImGui;
17133
17134 const int monitor_count = g.PlatformIO.Monitors.Size;
17135 if (monitor_count <= 1)
17136 return monitor_count - 1;
17137
17138 // 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.
17139 // This is necessary for tooltips which always resize down to zero at first.
17140 const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
17141 int best_monitor_n = 0; // Default to the first monitor as fallback
17142 float best_monitor_surface = 0.001f;
17143
17144 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
17145 {
17146 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
17147 const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
17148 if (monitor_rect.Contains(rect))
17149 return monitor_n;
17150 ImRect overlapping_rect = rect;
17151 overlapping_rect.ClipWithFull(monitor_rect);
17152 float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
17153 if (overlapping_surface < best_monitor_surface)
17154 continue;
17155 best_monitor_surface = overlapping_surface;
17156 best_monitor_n = monitor_n;
17157 }
17158 return best_monitor_n;
17159 }
17160
17161 // Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
17162 static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
17163 {
17164 viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
17165 }
17166
17167 // Return value is always != NULL, but don't hold on it across frames.
17168 const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
17169 {
17170 ImGuiContext& g = *GImGui;
17171 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
17172 int monitor_idx = viewport->PlatformMonitor;
17173 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
17174 return &g.PlatformIO.Monitors[monitor_idx];
17175 return &g.FallbackMonitor;
17176 }
17177
17178 void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
17179 {
17180 ImGuiContext& g = *GImGui;
17181 if (viewport->PlatformWindowCreated)
17182 {
17183 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
17184 if (g.PlatformIO.Renderer_DestroyWindow)
17185 g.PlatformIO.Renderer_DestroyWindow(viewport);
17186 if (g.PlatformIO.Platform_DestroyWindow)
17187 g.PlatformIO.Platform_DestroyWindow(viewport);
17188 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
17189
17190 // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
17191 // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
17192 if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
17193 viewport->PlatformWindowCreated = false;
17194 }
17195 else
17196 {
17197 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
17198 }
17199 viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
17200 viewport->ClearRequestFlags();
17201 }
17202
17203 void ImGui::DestroyPlatformWindows()
17204 {
17205 // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
17206 // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
17207 // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
17208 // code to operator a consistent manner.
17209 // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
17210 // crashing if it doesn't have data stored.
17211 ImGuiContext& g = *GImGui;
17212 for (ImGuiViewportP* viewport : g.Viewports)
17213 DestroyPlatformWindow(viewport);
17214 }
17215
17216
17217 //-----------------------------------------------------------------------------
17218 // [SECTION] DOCKING
17219 //-----------------------------------------------------------------------------
17220 // Docking: Internal Types
17221 // Docking: Forward Declarations
17222 // Docking: ImGuiDockContext
17223 // Docking: ImGuiDockContext Docking/Undocking functions
17224 // Docking: ImGuiDockNode
17225 // Docking: ImGuiDockNode Tree manipulation functions
17226 // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17227 // Docking: Builder Functions
17228 // Docking: Begin/End Support Functions (called from Begin/End)
17229 // Docking: Settings
17230 //-----------------------------------------------------------------------------
17231
17232 //-----------------------------------------------------------------------------
17233 // Typical Docking call flow: (root level is generally public API):
17234 //-----------------------------------------------------------------------------
17235 // - NewFrame() new dear imgui frame
17236 // | DockContextNewFrameUpdateUndocking() - process queued undocking requests
17237 // | - DockContextProcessUndockWindow() - process one window undocking request
17238 // | - DockContextProcessUndockNode() - process one whole node undocking request
17239 // | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes
17240 // | - update g.HoveredDockNode - [debug] update node hovered by mouse
17241 // | - DockContextProcessDock() - process one docking request
17242 // | - DockNodeUpdate()
17243 // | - DockNodeUpdateForRootNode()
17244 // | - DockNodeUpdateFlagsAndCollapse()
17245 // | - DockNodeFindInfo()
17246 // | - destroy unused node or tab bar
17247 // | - create dock node host window
17248 // | - Begin() etc.
17249 // | - DockNodeStartMouseMovingWindow()
17250 // | - DockNodeTreeUpdatePosSize()
17251 // | - DockNodeTreeUpdateSplitter()
17252 // | - draw node background
17253 // | - DockNodeUpdateTabBar() - create/update tab bar for a docking node
17254 // | - DockNodeAddTabBar()
17255 // | - DockNodeWindowMenuUpdate()
17256 // | - DockNodeCalcTabBarLayout()
17257 // | - BeginTabBarEx()
17258 // | - TabItemEx() calls
17259 // | - EndTabBar()
17260 // | - BeginDockableDragDropTarget()
17261 // | - DockNodeUpdate() - recurse into child nodes...
17262 //-----------------------------------------------------------------------------
17263 // - DockSpace() user submit a dockspace into a window
17264 // | Begin(Child) - create a child window
17265 // | DockNodeUpdate() - call main dock node update function
17266 // | End(Child)
17267 // | ItemSize()
17268 //-----------------------------------------------------------------------------
17269 // - Begin()
17270 // | BeginDocked()
17271 // | BeginDockableDragDropSource()
17272 // | BeginDockableDragDropTarget()
17273 // | - DockNodePreviewDockRender()
17274 //-----------------------------------------------------------------------------
17275 // - EndFrame()
17276 // | DockContextEndFrame()
17277 //-----------------------------------------------------------------------------
17278
17279 //-----------------------------------------------------------------------------
17280 // Docking: Internal Types
17281 //-----------------------------------------------------------------------------
17282 // - ImGuiDockRequestType
17283 // - ImGuiDockRequest
17284 // - ImGuiDockPreviewData
17285 // - ImGuiDockNodeSettings
17286 // - ImGuiDockContext
17287 //-----------------------------------------------------------------------------
17288
17289 enum ImGuiDockRequestType
17290 {
17291 ImGuiDockRequestType_None = 0,
17292 ImGuiDockRequestType_Dock,
17293 ImGuiDockRequestType_Undock,
17294 ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
17295 };
17296
17297 struct ImGuiDockRequest
17298 {
17299 ImGuiDockRequestType Type;
17300 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)
17301 ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
17302 ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
17303 ImGuiDir DockSplitDir;
17304 float DockSplitRatio;
17305 bool DockSplitOuter;
17306 ImGuiWindow* UndockTargetWindow;
17307 ImGuiDockNode* UndockTargetNode;
17308
17309 ImGuiDockRequest()
17310 {
17311 Type = ImGuiDockRequestType_None;
17312 DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
17313 DockTargetNode = UndockTargetNode = NULL;
17314 DockSplitDir = ImGuiDir_None;
17315 DockSplitRatio = 0.5f;
17316 DockSplitOuter = false;
17317 }
17318 };
17319
17320 struct ImGuiDockPreviewData
17321 {
17322 ImGuiDockNode FutureNode;
17323 bool IsDropAllowed;
17324 bool IsCenterAvailable;
17325 bool IsSidesAvailable; // Hold your breath, grammar freaks..
17326 bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
17327 ImGuiDockNode* SplitNode;
17328 ImGuiDir SplitDir;
17329 float SplitRatio;
17330 ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
17331
17332 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); }
17333 };
17334
17335 // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
17336 struct ImGuiDockNodeSettings
17337 {
17338 ImGuiID ID;
17339 ImGuiID ParentNodeId;
17340 ImGuiID ParentWindowId;
17341 ImGuiID SelectedTabId;
17342 signed char SplitAxis;
17343 char Depth;
17344 ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
17345 ImVec2ih Pos;
17346 ImVec2ih Size;
17347 ImVec2ih SizeRef;
17348 ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
17349 };
17350
17351 //-----------------------------------------------------------------------------
17352 // Docking: Forward Declarations
17353 //-----------------------------------------------------------------------------
17354
17355 namespace ImGui
17356 {
17357 // ImGuiDockContext
17358 static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
17359 static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
17360 static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
17361 static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
17362 static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
17363 static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
17364 static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
17365 static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
17366
17367 // ImGuiDockNode
17368 static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
17369 static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
17370 static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
17371 static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
17372 static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
17373 static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
17374 static void DockNodeHideHostWindow(ImGuiDockNode* node);
17375 static void DockNodeUpdate(ImGuiDockNode* node);
17376 static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
17377 static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
17378 static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
17379 static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
17380 static void DockNodeAddTabBar(ImGuiDockNode* node);
17381 static void DockNodeRemoveTabBar(ImGuiDockNode* node);
17382 static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
17383 static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
17384 static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
17385 static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
17386 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);
17387 static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
17388 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);
17389 static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
17390 static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
17391 static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
17392 static int DockNodeGetTabOrder(ImGuiWindow* window);
17393
17394 // ImGuiDockNode tree manipulations
17395 static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
17396 static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
17397 static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
17398 static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
17399 static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
17400 static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
17401
17402 // Settings
17403 static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
17404 static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
17405 static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
17406 static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
17407 static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
17408 static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
17409 static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
17410 static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
17411 }
17412
17413 //-----------------------------------------------------------------------------
17414 // Docking: ImGuiDockContext
17415 //-----------------------------------------------------------------------------
17416 // The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
17417 // 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.
17418 // At boot time only, we run a simple GC to remove nodes that have no references.
17419 // Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
17420 // we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
17421 // This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
17422 //-----------------------------------------------------------------------------
17423 // - DockContextInitialize()
17424 // - DockContextShutdown()
17425 // - DockContextClearNodes()
17426 // - DockContextRebuildNodes()
17427 // - DockContextNewFrameUpdateUndocking()
17428 // - DockContextNewFrameUpdateDocking()
17429 // - DockContextEndFrame()
17430 // - DockContextFindNodeByID()
17431 // - DockContextBindNodeToWindow()
17432 // - DockContextGenNodeID()
17433 // - DockContextAddNode()
17434 // - DockContextRemoveNode()
17435 // - ImGuiDockContextPruneNodeData
17436 // - DockContextPruneUnusedSettingsNodes()
17437 // - DockContextBuildNodesFromSettings()
17438 // - DockContextBuildAddWindowsToNodes()
17439 //-----------------------------------------------------------------------------
17440
17441 void ImGui::DockContextInitialize(ImGuiContext* ctx)
17442 {
17443 ImGuiContext& g = *ctx;
17444
17445 // Add .ini handle for persistent docking data
17446 ImGuiSettingsHandler ini_handler;
17447 ini_handler.TypeName = "Docking";
17448 ini_handler.TypeHash = ImHashStr("Docking");
17449 ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
17450 ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
17451 ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
17452 ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
17453 ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
17454 ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
17455 g.SettingsHandlers.push_back(ini_handler);
17456
17457 g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
17458 }
17459
17460 void ImGui::DockContextShutdown(ImGuiContext* ctx)
17461 {
17462 ImGuiDockContext* dc = &ctx->DockContext;
17463 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17464 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17465 IM_DELETE(node);
17466 }
17467
17468 void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
17469 {
17470 IM_UNUSED(ctx);
17471 IM_ASSERT(ctx == GImGui);
17472 DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
17473 DockBuilderRemoveNodeChildNodes(root_id);
17474 }
17475
17476 // [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
17477 // (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
17478 void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
17479 {
17480 ImGuiContext& g = *ctx;
17481 ImGuiDockContext* dc = &ctx->DockContext;
17482 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
17483 SaveIniSettingsToMemory();
17484 ImGuiID root_id = 0; // Rebuild all
17485 DockContextClearNodes(ctx, root_id, false);
17486 DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
17487 DockContextBuildAddWindowsToNodes(ctx, root_id);
17488 }
17489
17490 // Docking context update function, called by NewFrame()
17491 void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
17492 {
17493 ImGuiContext& g = *ctx;
17494 ImGuiDockContext* dc = &ctx->DockContext;
17495 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17496 {
17497 if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
17498 DockContextClearNodes(ctx, 0, true);
17499 return;
17500 }
17501
17502 // Setting NoSplit at runtime merges all nodes
17503 if (g.IO.ConfigDockingNoSplit)
17504 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17505 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17506 if (node->IsRootNode() && node->IsSplitNode())
17507 {
17508 DockBuilderRemoveNodeChildNodes(node->ID);
17509 //dc->WantFullRebuild = true;
17510 }
17511
17512 // Process full rebuild
17513 #if 0
17514 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
17515 dc->WantFullRebuild = true;
17516 #endif
17517 if (dc->WantFullRebuild)
17518 {
17519 DockContextRebuildNodes(ctx);
17520 dc->WantFullRebuild = false;
17521 }
17522
17523 // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
17524 for (ImGuiDockRequest& req : dc->Requests)
17525 {
17526 if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
17527 DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
17528 else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
17529 DockContextProcessUndockNode(ctx, req.UndockTargetNode);
17530 }
17531 }
17532
17533 // Docking context update function, called by NewFrame()
17534 void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
17535 {
17536 ImGuiContext& g = *ctx;
17537 ImGuiDockContext* dc = &ctx->DockContext;
17538 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17539 return;
17540
17541 // [DEBUG] Store hovered dock node.
17542 // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
17543 // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
17544 g.DebugHoveredDockNode = NULL;
17545 if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
17546 {
17547 if (hovered_window->DockNodeAsHost)
17548 g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
17549 else if (hovered_window->RootWindow->DockNode)
17550 g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
17551 }
17552
17553 // Process Docking requests
17554 for (ImGuiDockRequest& req : dc->Requests)
17555 if (req.Type == ImGuiDockRequestType_Dock)
17556 DockContextProcessDock(ctx, &req);
17557 dc->Requests.resize(0);
17558
17559 // Create windows for each automatic docking nodes
17560 // 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)
17561 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17562 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17563 if (node->IsFloatingNode())
17564 DockNodeUpdate(node);
17565 }
17566
17567 void ImGui::DockContextEndFrame(ImGuiContext* ctx)
17568 {
17569 // Draw backgrounds of node missing their window
17570 ImGuiContext& g = *ctx;
17571 ImGuiDockContext* dc = &g.DockContext;
17572 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17573 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17574 if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
17575 {
17576 ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
17577 ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
17578 node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17579 node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
17580 }
17581 }
17582
17583 ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
17584 {
17585 return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
17586 }
17587
17588 ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
17589 {
17590 // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
17591 // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
17592 // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
17593 ImGuiID id = 0x0001;
17594 while (DockContextFindNodeByID(ctx, id) != NULL)
17595 id++;
17596 return id;
17597 }
17598
17599 static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
17600 {
17601 // 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.
17602 ImGuiContext& g = *ctx;
17603 if (id == 0)
17604 id = DockContextGenNodeID(ctx);
17605 else
17606 IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
17607
17608 // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
17609 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
17610 ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
17611 ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
17612 return node;
17613 }
17614
17615 static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
17616 {
17617 ImGuiContext& g = *ctx;
17618 ImGuiDockContext* dc = &ctx->DockContext;
17619
17620 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
17621 IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
17622 IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
17623 IM_ASSERT(node->Windows.Size == 0);
17624
17625 if (node->HostWindow)
17626 node->HostWindow->DockNodeAsHost = NULL;
17627
17628 ImGuiDockNode* parent_node = node->ParentNode;
17629 const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
17630 if (merge)
17631 {
17632 IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
17633 ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
17634 DockNodeTreeMerge(&g, parent_node, sibling_node);
17635 }
17636 else
17637 {
17638 for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
17639 if (parent_node->ChildNodes[n] == node)
17640 node->ParentNode->ChildNodes[n] = NULL;
17641 dc->Nodes.SetVoidPtr(node->ID, NULL);
17642 IM_DELETE(node);
17643 }
17644 }
17645
17646 static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
17647 {
17648 const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
17649 const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
17650 return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
17651 }
17652
17653 // Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
17654 struct ImGuiDockContextPruneNodeData
17655 {
17656 int CountWindows, CountChildWindows, CountChildNodes;
17657 ImGuiID RootId;
17658 ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
17659 };
17660
17661 // Garbage collect unused nodes (run once at init time)
17662 static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
17663 {
17664 ImGuiContext& g = *ctx;
17665 ImGuiDockContext* dc = &ctx->DockContext;
17666 IM_ASSERT(g.Windows.Size == 0);
17667
17668 ImPool<ImGuiDockContextPruneNodeData> pool;
17669 pool.Reserve(dc->NodesSettings.Size);
17670
17671 // Count child nodes and compute RootID
17672 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17673 {
17674 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17675 ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
17676 pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
17677 if (settings->ParentNodeId)
17678 pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
17679 }
17680
17681 // Count reference to dock ids from dockspaces
17682 // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
17683 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17684 {
17685 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17686 if (settings->ParentWindowId != 0)
17687 if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
17688 if (window_settings->DockId)
17689 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
17690 data->CountChildNodes++;
17691 }
17692
17693 // Count reference to dock ids from window settings
17694 // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
17695 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17696 if (ImGuiID dock_id = settings->DockId)
17697 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
17698 {
17699 data->CountWindows++;
17700 if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
17701 data_root->CountChildWindows++;
17702 }
17703
17704 // Prune
17705 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17706 {
17707 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17708 ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
17709 if (data == NULL || data->CountWindows > 1)
17710 continue;
17711 ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
17712
17713 bool remove = false;
17714 remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
17715 remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
17716 remove |= (data_root->CountChildWindows == 0);
17717 if (remove)
17718 {
17719 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
17720 DockSettingsRemoveNodeReferences(&settings->ID, 1);
17721 settings->ID = 0;
17722 }
17723 }
17724 }
17725
17726 static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
17727 {
17728 // Build nodes
17729 for (int node_n = 0; node_n < node_settings_count; node_n++)
17730 {
17731 ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
17732 if (settings->ID == 0)
17733 continue;
17734 ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
17735 node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
17736 node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
17737 node->Size = ImVec2(settings->Size.x, settings->Size.y);
17738 node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
17739 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
17740 if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
17741 node->ParentNode->ChildNodes[0] = node;
17742 else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
17743 node->ParentNode->ChildNodes[1] = node;
17744 node->SelectedTabId = settings->SelectedTabId;
17745 node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
17746 node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
17747
17748 // Bind host window immediately if it already exist (in case of a rebuild)
17749 // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
17750 char host_window_title[20];
17751 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17752 node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
17753 }
17754 }
17755
17756 void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
17757 {
17758 // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
17759 ImGuiContext& g = *ctx;
17760 for (ImGuiWindow* window : g.Windows)
17761 {
17762 if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
17763 continue;
17764 if (window->DockNode != NULL)
17765 continue;
17766
17767 ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
17768 IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
17769 if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
17770 DockNodeAddWindow(node, window, true);
17771 }
17772 }
17773
17774 //-----------------------------------------------------------------------------
17775 // Docking: ImGuiDockContext Docking/Undocking functions
17776 //-----------------------------------------------------------------------------
17777 // - DockContextQueueDock()
17778 // - DockContextQueueUndockWindow()
17779 // - DockContextQueueUndockNode()
17780 // - DockContextQueueNotifyRemovedNode()
17781 // - DockContextProcessDock()
17782 // - DockContextProcessUndockWindow()
17783 // - DockContextProcessUndockNode()
17784 // - DockContextCalcDropPosForDocking()
17785 //-----------------------------------------------------------------------------
17786
17787 void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
17788 {
17789 IM_ASSERT(target != payload);
17790 ImGuiDockRequest req;
17791 req.Type = ImGuiDockRequestType_Dock;
17792 req.DockTargetWindow = target;
17793 req.DockTargetNode = target_node;
17794 req.DockPayload = payload;
17795 req.DockSplitDir = split_dir;
17796 req.DockSplitRatio = split_ratio;
17797 req.DockSplitOuter = split_outer;
17798 ctx->DockContext.Requests.push_back(req);
17799 }
17800
17801 void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
17802 {
17803 ImGuiDockRequest req;
17804 req.Type = ImGuiDockRequestType_Undock;
17805 req.UndockTargetWindow = window;
17806 ctx->DockContext.Requests.push_back(req);
17807 }
17808
17809 void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
17810 {
17811 ImGuiDockRequest req;
17812 req.Type = ImGuiDockRequestType_Undock;
17813 req.UndockTargetNode = node;
17814 ctx->DockContext.Requests.push_back(req);
17815 }
17816
17817 void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
17818 {
17819 ImGuiDockContext* dc = &ctx->DockContext;
17820 for (ImGuiDockRequest& req : dc->Requests)
17821 if (req.DockTargetNode == node)
17822 req.Type = ImGuiDockRequestType_None;
17823 }
17824
17825 void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
17826 {
17827 IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
17828 IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
17829
17830 ImGuiContext& g = *ctx;
17831 IM_UNUSED(g);
17832
17833 ImGuiWindow* payload_window = req->DockPayload; // Optional
17834 ImGuiWindow* target_window = req->DockTargetWindow;
17835 ImGuiDockNode* node = req->DockTargetNode;
17836 if (payload_window)
17837 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);
17838 else
17839 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
17840
17841 // Decide which Tab will be selected at the end of the operation
17842 ImGuiID next_selected_id = 0;
17843 ImGuiDockNode* payload_node = NULL;
17844 if (payload_window)
17845 {
17846 payload_node = payload_window->DockNodeAsHost;
17847 payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
17848 if (payload_node && payload_node->IsLeafNode())
17849 next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
17850 if (payload_node == NULL)
17851 next_selected_id = payload_window->TabId;
17852 }
17853
17854 // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
17855 // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
17856 if (node)
17857 IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
17858 if (node && target_window && node == target_window->DockNodeAsHost)
17859 IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
17860
17861 // Create new node and add existing window to it
17862 if (node == NULL)
17863 {
17864 node = DockContextAddNode(ctx, 0);
17865 node->Pos = target_window->Pos;
17866 node->Size = target_window->Size;
17867 if (target_window->DockNodeAsHost == NULL)
17868 {
17869 DockNodeAddWindow(node, target_window, true);
17870 node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
17871 target_window->DockIsActive = true;
17872 }
17873 }
17874
17875 ImGuiDir split_dir = req->DockSplitDir;
17876 if (split_dir != ImGuiDir_None)
17877 {
17878 // Split into two, one side will be our payload node unless we are dropping a loose window
17879 const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17880 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
17881 const float split_ratio = req->DockSplitRatio;
17882 DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
17883 ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
17884 new_node->HostWindow = node->HostWindow;
17885 node = new_node;
17886 }
17887 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17888
17889 if (node != payload_node)
17890 {
17891 // 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!)
17892 if (node->Windows.Size > 0 && node->TabBar == NULL)
17893 {
17894 DockNodeAddTabBar(node);
17895 for (int n = 0; n < node->Windows.Size; n++)
17896 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
17897 }
17898
17899 if (payload_node != NULL)
17900 {
17901 // Transfer full payload node (with 1+ child windows or child nodes)
17902 if (payload_node->IsSplitNode())
17903 {
17904 if (node->Windows.Size > 0)
17905 {
17906 // 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.
17907 // In this situation, we move the windows of the target node into the currently visible node of the payload.
17908 // This allows us to preserve some of the underlying dock tree settings nicely.
17909 IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
17910 ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
17911 if (visible_node->TabBar)
17912 IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
17913 DockNodeMoveWindows(node, visible_node);
17914 DockNodeMoveWindows(visible_node, node);
17915 DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
17916 }
17917 if (node->IsCentralNode())
17918 {
17919 // Central node property needs to be moved to a leaf node, pick the last focused one.
17920 // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
17921 ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
17922 IM_ASSERT(last_focused_node != NULL);
17923 ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
17924 IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
17925 last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17926 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
17927 last_focused_root_node->CentralNode = last_focused_node;
17928 }
17929
17930 IM_ASSERT(node->Windows.Size == 0);
17931 DockNodeMoveChildNodes(node, payload_node);
17932 }
17933 else
17934 {
17935 const ImGuiID payload_dock_id = payload_node->ID;
17936 DockNodeMoveWindows(node, payload_node);
17937 DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
17938 }
17939 DockContextRemoveNode(ctx, payload_node, true);
17940 }
17941 else if (payload_window)
17942 {
17943 // Transfer single window
17944 const ImGuiID payload_dock_id = payload_window->DockId;
17945 node->VisibleWindow = payload_window;
17946 DockNodeAddWindow(node, payload_window, true);
17947 if (payload_dock_id != 0)
17948 DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
17949 }
17950 }
17951 else
17952 {
17953 // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
17954 node->WantHiddenTabBarUpdate = true;
17955 }
17956
17957 // Update selection immediately
17958 if (ImGuiTabBar* tab_bar = node->TabBar)
17959 tab_bar->NextSelectedTabId = next_selected_id;
17960 MarkIniSettingsDirty();
17961 }
17962
17963 // Problem:
17964 // Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
17965 // than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
17966 // with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
17967 // due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
17968 // Solution:
17969 // When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
17970 // Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
17971 static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
17972 {
17973 if (ref_viewport == NULL)
17974 return size;
17975
17976 ImGuiContext& g = *GImGui;
17977 ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
17978 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
17979 {
17980 const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
17981 max_size = ImTrunc(monitor->WorkSize * 0.90f);
17982 }
17983 return ImMin(size, max_size);
17984 }
17985
17986 void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
17987 {
17988 ImGuiContext& g = *ctx;
17989 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
17990 if (window->DockNode)
17991 DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
17992 else
17993 window->DockId = 0;
17994 window->Collapsed = false;
17995 window->DockIsActive = false;
17996 window->DockNodeIsVisible = window->DockTabIsVisible = false;
17997 window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
17998
17999 MarkIniSettingsDirty();
18000 }
18001
18002 void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
18003 {
18004 ImGuiContext& g = *ctx;
18005 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
18006 IM_ASSERT(node->IsLeafNode());
18007 IM_ASSERT(node->Windows.Size >= 1);
18008
18009 if (node->IsRootNode() || node->IsCentralNode())
18010 {
18011 // 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.
18012 ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
18013 new_node->Pos = node->Pos;
18014 new_node->Size = node->Size;
18015 new_node->SizeRef = node->SizeRef;
18016 DockNodeMoveWindows(new_node, node);
18017 DockSettingsRenameNodeReferences(node->ID, new_node->ID);
18018 node = new_node;
18019 }
18020 else
18021 {
18022 // Otherwise extract our node and merge our sibling back into the parent node.
18023 IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
18024 int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
18025 node->ParentNode->ChildNodes[index_in_parent] = NULL;
18026 DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
18027 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
18028 node->ParentNode = NULL;
18029 }
18030 for (ImGuiWindow* window : node->Windows)
18031 {
18032 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
18033 if (window->ParentWindow)
18034 window->ParentWindow->DC.ChildWindows.find_erase(window);
18035 UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
18036 }
18037 node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18038 node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
18039 node->WantMouseMove = true;
18040 MarkIniSettingsDirty();
18041 }
18042
18043 // This is mostly used for automation.
18044 bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
18045 {
18046 if (target != NULL && target_node == NULL)
18047 target_node = target->DockNode;
18048
18049 // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
18050 // (which would be functionally identical) we only show the outer one. Reflect this here.
18051 if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
18052 split_outer = true;
18053 ImGuiDockPreviewData split_data;
18054 DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
18055 if (split_data.DropRectsDraw[split_dir+1].IsInverted())
18056 return false;
18057 *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
18058 return true;
18059 }
18060
18061 //-----------------------------------------------------------------------------
18062 // Docking: ImGuiDockNode
18063 //-----------------------------------------------------------------------------
18064 // - DockNodeGetTabOrder()
18065 // - DockNodeAddWindow()
18066 // - DockNodeRemoveWindow()
18067 // - DockNodeMoveChildNodes()
18068 // - DockNodeMoveWindows()
18069 // - DockNodeApplyPosSizeToWindows()
18070 // - DockNodeHideHostWindow()
18071 // - ImGuiDockNodeFindInfoResults
18072 // - DockNodeFindInfo()
18073 // - DockNodeFindWindowByID()
18074 // - DockNodeUpdateFlagsAndCollapse()
18075 // - DockNodeUpdateHasCentralNodeFlag()
18076 // - DockNodeUpdateVisibleFlag()
18077 // - DockNodeStartMouseMovingWindow()
18078 // - DockNodeUpdate()
18079 // - DockNodeUpdateWindowMenu()
18080 // - DockNodeBeginAmendTabBar()
18081 // - DockNodeEndAmendTabBar()
18082 // - DockNodeUpdateTabBar()
18083 // - DockNodeAddTabBar()
18084 // - DockNodeRemoveTabBar()
18085 // - DockNodeIsDropAllowedOne()
18086 // - DockNodeIsDropAllowed()
18087 // - DockNodeCalcTabBarLayout()
18088 // - DockNodeCalcSplitRects()
18089 // - DockNodeCalcDropRectsAndTestMousePos()
18090 // - DockNodePreviewDockSetup()
18091 // - DockNodePreviewDockRender()
18092 //-----------------------------------------------------------------------------
18093
18094 ImGuiDockNode::ImGuiDockNode(ImGuiID id)
18095 {
18096 ID = id;
18097 SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
18098 ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
18099 TabBar = NULL;
18100 SplitAxis = ImGuiAxis_None;
18101
18102 State = ImGuiDockNodeState_Unknown;
18103 LastBgColor = IM_COL32_WHITE;
18104 HostWindow = VisibleWindow = NULL;
18105 CentralNode = OnlyNodeWithWindows = NULL;
18106 CountNodeWithWindows = 0;
18107 LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
18108 LastFocusedNodeId = 0;
18109 SelectedTabId = 0;
18110 WantCloseTabId = 0;
18111 RefViewportId = 0;
18112 AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
18113 AuthorityForViewport = ImGuiDataAuthority_Auto;
18114 IsVisible = true;
18115 IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
18116 IsBgDrawnThisFrame = false;
18117 WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
18118 }
18119
18120 ImGuiDockNode::~ImGuiDockNode()
18121 {
18122 IM_DELETE(TabBar);
18123 TabBar = NULL;
18124 ChildNodes[0] = ChildNodes[1] = NULL;
18125 }
18126
18127 int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
18128 {
18129 ImGuiTabBar* tab_bar = window->DockNode->TabBar;
18130 if (tab_bar == NULL)
18131 return -1;
18132 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
18133 return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
18134 }
18135
18136 static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
18137 {
18138 window->Hidden = true;
18139 window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
18140 }
18141
18142 static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
18143 {
18144 ImGuiContext& g = *GImGui; (void)g;
18145 if (window->DockNode)
18146 {
18147 // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
18148 IM_ASSERT(window->DockNode->ID != node->ID);
18149 DockNodeRemoveWindow(window->DockNode, window, 0);
18150 }
18151 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
18152 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
18153
18154 // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
18155 // 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).
18156 // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
18157 if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
18158 DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
18159
18160 node->Windows.push_back(window);
18161 node->WantHiddenTabBarUpdate = true;
18162 window->DockNode = node;
18163 window->DockId = node->ID;
18164 window->DockIsActive = (node->Windows.Size > 1);
18165 window->DockTabWantClose = false;
18166
18167 // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
18168 // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
18169 if (node->HostWindow == NULL && node->IsFloatingNode())
18170 {
18171 if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
18172 node->AuthorityForPos = ImGuiDataAuthority_Window;
18173 if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
18174 node->AuthorityForSize = ImGuiDataAuthority_Window;
18175 if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
18176 node->AuthorityForViewport = ImGuiDataAuthority_Window;
18177 }
18178
18179 // Add to tab bar if requested
18180 if (add_to_tab_bar)
18181 {
18182 if (node->TabBar == NULL)
18183 {
18184 DockNodeAddTabBar(node);
18185 node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
18186
18187 // Add existing windows
18188 for (int n = 0; n < node->Windows.Size - 1; n++)
18189 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
18190 }
18191 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
18192 }
18193
18194 DockNodeUpdateVisibleFlag(node);
18195
18196 // 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.
18197 if (node->HostWindow)
18198 UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
18199 }
18200
18201 static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
18202 {
18203 ImGuiContext& g = *GImGui;
18204 IM_ASSERT(window->DockNode == node);
18205 //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
18206 //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
18207 IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
18208 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
18209
18210 window->DockNode = NULL;
18211 window->DockIsActive = window->DockTabWantClose = false;
18212 window->DockId = save_dock_id;
18213 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
18214 if (window->ParentWindow)
18215 window->ParentWindow->DC.ChildWindows.find_erase(window);
18216 UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
18217
18218 if (node->HostWindow && node->HostWindow->ViewportOwned)
18219 {
18220 // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
18221 // But mid-frame, if we clear viewport we need to mark window as hidden as well.
18222 window->Viewport = NULL;
18223 window->ViewportId = 0;
18224 window->ViewportOwned = false;
18225 window->Hidden = true;
18226 }
18227
18228 // Remove window
18229 bool erased = false;
18230 for (int n = 0; n < node->Windows.Size; n++)
18231 if (node->Windows[n] == window)
18232 {
18233 node->Windows.erase(node->Windows.Data + n);
18234 erased = true;
18235 break;
18236 }
18237 if (!erased)
18238 IM_ASSERT(erased);
18239 if (node->VisibleWindow == window)
18240 node->VisibleWindow = NULL;
18241
18242 // Remove tab and possibly tab bar
18243 node->WantHiddenTabBarUpdate = true;
18244 if (node->TabBar)
18245 {
18246 TabBarRemoveTab(node->TabBar, window->TabId);
18247 const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
18248 if (node->Windows.Size < tab_count_threshold_for_tab_bar)
18249 DockNodeRemoveTabBar(node);
18250 }
18251
18252 if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
18253 {
18254 // Automatic dock node delete themselves if they are not holding at least one tab
18255 DockContextRemoveNode(&g, node, true);
18256 return;
18257 }
18258
18259 if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
18260 {
18261 ImGuiWindow* remaining_window = node->Windows[0];
18262 // Note: we used to transport viewport ownership here.
18263 remaining_window->Collapsed = node->HostWindow->Collapsed;
18264 }
18265
18266 // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
18267 DockNodeUpdateVisibleFlag(node);
18268 }
18269
18270 static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
18271 {
18272 IM_ASSERT(dst_node->Windows.Size == 0);
18273 dst_node->ChildNodes[0] = src_node->ChildNodes[0];
18274 dst_node->ChildNodes[1] = src_node->ChildNodes[1];
18275 if (dst_node->ChildNodes[0])
18276 dst_node->ChildNodes[0]->ParentNode = dst_node;
18277 if (dst_node->ChildNodes[1])
18278 dst_node->ChildNodes[1]->ParentNode = dst_node;
18279 dst_node->SplitAxis = src_node->SplitAxis;
18280 dst_node->SizeRef = src_node->SizeRef;
18281 src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
18282 }
18283
18284 static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
18285 {
18286 // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
18287 IM_ASSERT(src_node && dst_node && dst_node != src_node);
18288 ImGuiTabBar* src_tab_bar = src_node->TabBar;
18289 if (src_tab_bar != NULL)
18290 IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
18291
18292 // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
18293 bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
18294 if (move_tab_bar)
18295 {
18296 dst_node->TabBar = src_node->TabBar;
18297 src_node->TabBar = NULL;
18298 }
18299
18300 // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
18301 for (ImGuiWindow* window : src_node->Windows)
18302 {
18303 window->DockNode = NULL;
18304 window->DockIsActive = false;
18305 DockNodeAddWindow(dst_node, window, !move_tab_bar);
18306 }
18307 src_node->Windows.clear();
18308
18309 if (!move_tab_bar && src_node->TabBar)
18310 {
18311 if (dst_node->TabBar)
18312 dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
18313 DockNodeRemoveTabBar(src_node);
18314 }
18315 }
18316
18317 static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
18318 {
18319 for (ImGuiWindow* window : node->Windows)
18320 {
18321 SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
18322 SetWindowSize(window, node->Size, ImGuiCond_Always);
18323 }
18324 }
18325
18326 static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
18327 {
18328 if (node->HostWindow)
18329 {
18330 if (node->HostWindow->DockNodeAsHost == node)
18331 node->HostWindow->DockNodeAsHost = NULL;
18332 node->HostWindow = NULL;
18333 }
18334
18335 if (node->Windows.Size == 1)
18336 {
18337 node->VisibleWindow = node->Windows[0];
18338 node->Windows[0]->DockIsActive = false;
18339 }
18340
18341 if (node->TabBar)
18342 DockNodeRemoveTabBar(node);
18343 }
18344
18345 // Search function called once by root node in DockNodeUpdate()
18346 struct ImGuiDockNodeTreeInfo
18347 {
18348 ImGuiDockNode* CentralNode;
18349 ImGuiDockNode* FirstNodeWithWindows;
18350 int CountNodesWithWindows;
18351 //ImGuiWindowClass WindowClassForMerges;
18352
18353 ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
18354 };
18355
18356 static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
18357 {
18358 if (node->Windows.Size > 0)
18359 {
18360 if (info->FirstNodeWithWindows == NULL)
18361 info->FirstNodeWithWindows = node;
18362 info->CountNodesWithWindows++;
18363 }
18364 if (node->IsCentralNode())
18365 {
18366 IM_ASSERT(info->CentralNode == NULL); // Should be only one
18367 IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
18368 info->CentralNode = node;
18369 }
18370 if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
18371 return;
18372 if (node->ChildNodes[0])
18373 DockNodeFindInfo(node->ChildNodes[0], info);
18374 if (node->ChildNodes[1])
18375 DockNodeFindInfo(node->ChildNodes[1], info);
18376 }
18377
18378 static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
18379 {
18380 IM_ASSERT(id != 0);
18381 for (ImGuiWindow* window : node->Windows)
18382 if (window->ID == id)
18383 return window;
18384 return NULL;
18385 }
18386
18387 // - Remove inactive windows/nodes.
18388 // - Update visibility flag.
18389 static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
18390 {
18391 ImGuiContext& g = *GImGui;
18392 IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
18393
18394 // Inherit most flags
18395 if (node->ParentNode)
18396 node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18397
18398 // Recurse into children
18399 // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
18400 // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
18401 // 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)
18402 node->HasCentralNodeChild = false;
18403 if (node->ChildNodes[0])
18404 DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
18405 if (node->ChildNodes[1])
18406 DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
18407
18408 // Remove inactive windows, collapse nodes
18409 // Merge node flags overrides stored in windows
18410 node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18411 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18412 {
18413 ImGuiWindow* window = node->Windows[window_n];
18414 IM_ASSERT(window->DockNode == node);
18415
18416 bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
18417 bool remove = false;
18418 remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
18419 remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
18420 remove |= (window->DockTabWantClose);
18421 if (remove)
18422 {
18423 window->DockTabWantClose = false;
18424 if (node->Windows.Size == 1 && !node->IsCentralNode())
18425 {
18426 DockNodeHideHostWindow(node);
18427 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
18428 DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
18429 return;
18430 }
18431 DockNodeRemoveWindow(node, window, node->ID);
18432 window_n--;
18433 continue;
18434 }
18435
18436 // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
18437 //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
18438 node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
18439 }
18440 node->UpdateMergedFlags();
18441
18442 // Auto-hide tab bar option
18443 ImGuiDockNodeFlags node_flags = node->MergedFlags;
18444 if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
18445 node->WantHiddenTabBarToggle = true;
18446 node->WantHiddenTabBarUpdate = false;
18447
18448 // Cancel toggling if we know our tab bar is enforced to be hidden at all times
18449 if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
18450 node->WantHiddenTabBarToggle = false;
18451
18452 // Apply toggles at a single point of the frame (here!)
18453 if (node->Windows.Size > 1)
18454 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
18455 else if (node->WantHiddenTabBarToggle)
18456 node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
18457 node->WantHiddenTabBarToggle = false;
18458
18459 DockNodeUpdateVisibleFlag(node);
18460 }
18461
18462 // This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
18463 static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
18464 {
18465 node->HasCentralNodeChild = false;
18466 if (node->ChildNodes[0])
18467 DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
18468 if (node->ChildNodes[1])
18469 DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
18470 if (node->IsRootNode())
18471 {
18472 ImGuiDockNode* mark_node = node->CentralNode;
18473 while (mark_node)
18474 {
18475 mark_node->HasCentralNodeChild = true;
18476 mark_node = mark_node->ParentNode;
18477 }
18478 }
18479 }
18480
18481 static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
18482 {
18483 // Update visibility flag
18484 bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
18485 is_visible |= (node->Windows.Size > 0);
18486 is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
18487 is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
18488 node->IsVisible = is_visible;
18489 }
18490
18491 static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
18492 {
18493 ImGuiContext& g = *GImGui;
18494 IM_ASSERT(node->WantMouseMove == true);
18495 StartMouseMovingWindow(window);
18496 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
18497 g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
18498 node->WantMouseMove = false;
18499 }
18500
18501 // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
18502 static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
18503 {
18504 DockNodeUpdateFlagsAndCollapse(node);
18505
18506 // - Setup central node pointers
18507 // - 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!)
18508 // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
18509 ImGuiDockNodeTreeInfo info;
18510 DockNodeFindInfo(node, &info);
18511 node->CentralNode = info.CentralNode;
18512 node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
18513 node->CountNodeWithWindows = info.CountNodesWithWindows;
18514 if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
18515 node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
18516
18517 // Copy the window class from of our first window so it can be used for proper dock filtering.
18518 // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
18519 // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
18520 if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
18521 {
18522 node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
18523 for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
18524 if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
18525 {
18526 node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
18527 break;
18528 }
18529 }
18530
18531 ImGuiDockNode* mark_node = node->CentralNode;
18532 while (mark_node)
18533 {
18534 mark_node->HasCentralNodeChild = true;
18535 mark_node = mark_node->ParentNode;
18536 }
18537 }
18538
18539 static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
18540 {
18541 // Remove ourselves from any previous different host window
18542 // This can happen if a user mistakenly does (see #4295 for details):
18543 // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace
18544 // - N+1: NewFrame() // will create floating host window for that node
18545 // - N+1: DockSpace(id) // requalify node as dockspace, moving host window
18546 if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
18547 node->HostWindow->DockNodeAsHost = NULL;
18548
18549 host_window->DockNodeAsHost = node;
18550 node->HostWindow = host_window;
18551 }
18552
18553 static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
18554 {
18555 ImGuiContext& g = *GImGui;
18556 IM_ASSERT(node->LastFrameActive != g.FrameCount);
18557 node->LastFrameAlive = g.FrameCount;
18558 node->IsBgDrawnThisFrame = false;
18559
18560 node->CentralNode = node->OnlyNodeWithWindows = NULL;
18561 if (node->IsRootNode())
18562 DockNodeUpdateForRootNode(node);
18563
18564 // Remove tab bar if not needed
18565 if (node->TabBar && node->IsNoTabBar())
18566 DockNodeRemoveTabBar(node);
18567
18568 // 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)
18569 bool want_to_hide_host_window = false;
18570 if (node->IsFloatingNode())
18571 {
18572 if (node->Windows.Size <= 1 && node->IsLeafNode())
18573 if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
18574 want_to_hide_host_window = true;
18575 if (node->CountNodeWithWindows == 0)
18576 want_to_hide_host_window = true;
18577 }
18578 if (want_to_hide_host_window)
18579 {
18580 if (node->Windows.Size == 1)
18581 {
18582 // Floating window pos/size is authoritative
18583 ImGuiWindow* single_window = node->Windows[0];
18584 node->Pos = single_window->Pos;
18585 node->Size = single_window->SizeFull;
18586 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18587
18588 // Transfer focus immediately so when we revert to a regular window it is immediately selected
18589 if (node->HostWindow && g.NavWindow == node->HostWindow)
18590 FocusWindow(single_window);
18591 if (node->HostWindow)
18592 {
18593 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);
18594 single_window->Viewport = node->HostWindow->Viewport;
18595 single_window->ViewportId = node->HostWindow->ViewportId;
18596 if (node->HostWindow->ViewportOwned)
18597 {
18598 single_window->Viewport->ID = single_window->ID;
18599 single_window->Viewport->Window = single_window;
18600 single_window->ViewportOwned = true;
18601 }
18602 }
18603 node->RefViewportId = single_window->ViewportId;
18604 }
18605
18606 DockNodeHideHostWindow(node);
18607 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
18608 node->WantCloseAll = false;
18609 node->WantCloseTabId = 0;
18610 node->HasCloseButton = node->HasWindowMenuButton = false;
18611 node->LastFrameActive = g.FrameCount;
18612
18613 if (node->WantMouseMove && node->Windows.Size == 1)
18614 DockNodeStartMouseMovingWindow(node, node->Windows[0]);
18615 return;
18616 }
18617
18618 // In some circumstance we will defer creating the host window (so everything will be kept hidden),
18619 // while the expected visible window is resizing itself.
18620 // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
18621 // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
18622 // N+0: Begin(): window created (with no known size), node is created
18623 // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
18624 // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
18625 // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
18626 // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
18627 // In reality it isn't very important as user quickly ends up with size data in .ini file.
18628 if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
18629 {
18630 IM_ASSERT(node->Windows.Size > 0);
18631 ImGuiWindow* ref_window = NULL;
18632 if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
18633 ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
18634 if (ref_window == NULL)
18635 ref_window = node->Windows[0];
18636 if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
18637 {
18638 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
18639 return;
18640 }
18641 }
18642
18643 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
18644
18645 // Decide if the node will have a close button and a window menu button
18646 node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
18647 node->HasCloseButton = false;
18648 for (ImGuiWindow* window : node->Windows)
18649 {
18650 // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
18651 node->HasCloseButton |= window->HasCloseButton;
18652 window->DockIsActive = (node->Windows.Size > 1);
18653 }
18654 if ((node_flags & ImGuiDockNodeFlags_NoCloseButton) || !g.Style.DockingNodeHasCloseButton)
18655 node->HasCloseButton = false;
18656
18657 // Bind or create host window
18658 ImGuiWindow* host_window = NULL;
18659 bool beginned_into_host_window = false;
18660 if (node->IsDockSpace())
18661 {
18662 // [Explicit root dockspace node]
18663 IM_ASSERT(node->HostWindow);
18664 host_window = node->HostWindow;
18665 }
18666 else
18667 {
18668 // [Automatic root or child nodes]
18669 if (node->IsRootNode() && node->IsVisible)
18670 {
18671 ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
18672
18673 // Sync Pos
18674 if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
18675 SetNextWindowPos(ref_window->Pos);
18676 else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
18677 SetNextWindowPos(node->Pos);
18678
18679 // Sync Size
18680 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
18681 SetNextWindowSize(ref_window->SizeFull);
18682 else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
18683 SetNextWindowSize(node->Size);
18684
18685 // Sync Collapsed
18686 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
18687 SetNextWindowCollapsed(ref_window->Collapsed);
18688
18689 // Sync Viewport
18690 if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
18691 SetNextWindowViewport(ref_window->ViewportId);
18692 else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
18693 SetNextWindowViewport(node->RefViewportId);
18694
18695 SetNextWindowClass(&node->WindowClass);
18696
18697 // Begin into the host window
18698 char window_label[20];
18699 DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
18700 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
18701 window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
18702 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
18703 window_flags |= ImGuiWindowFlags_NoTitleBar;
18704
18705 SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
18706 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
18707 Begin(window_label, NULL, window_flags);
18708 PopStyleVar();
18709 beginned_into_host_window = true;
18710
18711 host_window = g.CurrentWindow;
18712 DockNodeSetupHostWindow(node, host_window);
18713 host_window->DC.CursorPos = host_window->Pos;
18714 node->Pos = host_window->Pos;
18715 node->Size = host_window->Size;
18716
18717 // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
18718 // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
18719 // 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.
18720 // 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
18721 // 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
18722 // after the dock host window, losing their top-most status.
18723 if (node->HostWindow->Appearing)
18724 BringWindowToDisplayFront(node->HostWindow);
18725
18726 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18727 }
18728 else if (node->ParentNode)
18729 {
18730 node->HostWindow = host_window = node->ParentNode->HostWindow;
18731 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18732 }
18733 if (node->WantMouseMove && node->HostWindow)
18734 DockNodeStartMouseMovingWindow(node, node->HostWindow);
18735 }
18736 node->RefViewportId = 0; // Clear when we have a host window
18737
18738 // Update focused node (the one whose title bar is highlight) within a node tree
18739 if (node->IsSplitNode())
18740 IM_ASSERT(node->TabBar == NULL);
18741 if (node->IsRootNode())
18742 if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
18743 while (p_window != NULL && p_window->DockNode != NULL)
18744 {
18745 ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
18746 if (p_node == node)
18747 {
18748 node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
18749 break;
18750 }
18751 p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
18752 }
18753
18754 // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
18755 ImGuiDockNode* central_node = node->CentralNode;
18756 const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
18757 bool central_node_hole_register_hit_test_hole = central_node_hole;
18758 if (central_node_hole)
18759 if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
18760 if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
18761 central_node_hole_register_hit_test_hole = false;
18762 if (central_node_hole_register_hit_test_hole)
18763 {
18764 // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
18765 // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
18766 // covering passthru node we'd have a gap on the edge not covered by the hole)
18767 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
18768 ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
18769 ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
18770 ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
18771 if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += g.WindowsBorderHoverPadding; }
18772 if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= g.WindowsBorderHoverPadding; }
18773 if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += g.WindowsBorderHoverPadding; }
18774 if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= g.WindowsBorderHoverPadding; }
18775 //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
18776 if (central_node_hole && !hole_rect.IsInverted())
18777 {
18778 SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
18779 if (host_window->ParentWindow)
18780 SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
18781 }
18782 }
18783
18784 // Update position/size, process and draw resizing splitters
18785 if (node->IsRootNode() && host_window)
18786 {
18787 DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
18788 PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
18789 PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
18790 PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
18791 DockNodeTreeUpdateSplitter(node);
18792 PopStyleColor(3);
18793 }
18794
18795 // Draw empty node background (currently can only be the Central Node)
18796 if (host_window && node->IsEmpty() && node->IsVisible)
18797 {
18798 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
18799 node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
18800 if (node->LastBgColor != 0)
18801 host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
18802 node->IsBgDrawnThisFrame = true;
18803 }
18804
18805 // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
18806 // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
18807 // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
18808 const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
18809 if (render_dockspace_bg && node->IsVisible)
18810 {
18811 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
18812 if (central_node_hole)
18813 RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
18814 else
18815 host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
18816 }
18817
18818 // Draw and populate Tab Bar
18819 if (host_window)
18820 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
18821 if (host_window && node->Windows.Size > 0)
18822 {
18823 DockNodeUpdateTabBar(node, host_window);
18824 }
18825 else
18826 {
18827 node->WantCloseAll = false;
18828 node->WantCloseTabId = 0;
18829 node->IsFocused = false;
18830 }
18831 if (node->TabBar && node->TabBar->SelectedTabId)
18832 node->SelectedTabId = node->TabBar->SelectedTabId;
18833 else if (node->Windows.Size > 0)
18834 node->SelectedTabId = node->Windows[0]->TabId;
18835
18836 // Draw payload drop target
18837 if (host_window && node->IsVisible)
18838 if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
18839 BeginDockableDragDropTarget(host_window);
18840
18841 // We update this after DockNodeUpdateTabBar()
18842 node->LastFrameActive = g.FrameCount;
18843
18844 // Recurse into children
18845 // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
18846 if (host_window)
18847 {
18848 if (node->ChildNodes[0])
18849 DockNodeUpdate(node->ChildNodes[0]);
18850 if (node->ChildNodes[1])
18851 DockNodeUpdate(node->ChildNodes[1]);
18852
18853 // Render outer borders last (after the tab bar)
18854 if (node->IsRootNode())
18855 RenderWindowOuterBorders(host_window);
18856 }
18857
18858 // End host window
18859 if (beginned_into_host_window) //-V1020
18860 End();
18861 }
18862
18863 // 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.
18864 static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
18865 {
18866 ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
18867 ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
18868 if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
18869 return d;
18870 return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
18871 }
18872
18873 // Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
18874 // This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
18875 // Custom overrides may want to decorate, group, sort entries.
18876 // Please note those are internal structures: if you copy this expect occasional breakage.
18877 // (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
18878 void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
18879 {
18880 IM_UNUSED(ctx);
18881 if (tab_bar->Tabs.Size == 1)
18882 {
18883 // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
18884 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
18885 node->WantHiddenTabBarToggle = true;
18886 }
18887 else
18888 {
18889 // Display a selectable list of windows in this docking node
18890 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
18891 {
18892 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
18893 if (tab->Flags & ImGuiTabItemFlags_Button)
18894 continue;
18895 if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
18896 TabBarQueueFocus(tab_bar, tab);
18897 SameLine();
18898 Text(" ");
18899 }
18900 }
18901 }
18902
18903 static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
18904 {
18905 // Try to position the menu so it is more likely to stays within the same viewport
18906 ImGuiContext& g = *GImGui;
18907 if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
18908 SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
18909 else
18910 SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
18911 if (BeginPopup("#WindowMenu"))
18912 {
18913 node->IsFocused = true;
18914 g.DockNodeWindowMenuHandler(&g, node, tab_bar);
18915 EndPopup();
18916 }
18917 }
18918
18919 // User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
18920 bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
18921 {
18922 if (node->TabBar == NULL || node->HostWindow == NULL)
18923 return false;
18924 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18925 return false;
18926 if (node->TabBar->ID == 0)
18927 return false;
18928 Begin(node->HostWindow->Name);
18929 PushOverrideID(node->ID);
18930 bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
18931 IM_UNUSED(ret);
18932 IM_ASSERT(ret);
18933 return true;
18934 }
18935
18936 void ImGui::DockNodeEndAmendTabBar()
18937 {
18938 EndTabBar();
18939 PopID();
18940 End();
18941 }
18942
18943 static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
18944 {
18945 // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
18946 ImGuiContext& g = *GImGui;
18947 if (g.NavWindowingTarget)
18948 return (g.NavWindowingTarget->DockNode == node);
18949
18950 // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
18951 if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
18952 {
18953 // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
18954 ImGuiWindow* parent_window = g.NavWindow->RootWindow;
18955 while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
18956 parent_window = parent_window->ParentWindow->RootWindow;
18957 ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
18958 for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
18959 if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
18960 return true;
18961 }
18962 return false;
18963 }
18964
18965 // Submit the tab bar corresponding to a dock node and various housekeeping details.
18966 static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
18967 {
18968 ImGuiContext& g = *GImGui;
18969 ImGuiStyle& style = g.Style;
18970
18971 const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
18972 node->WantCloseAll = false;
18973 node->WantCloseTabId = 0;
18974
18975 // Decide if we should use a focused title bar color
18976 bool is_focused = false;
18977 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18978 if (IsDockNodeTitleBarHighlighted(node, root_node))
18979 is_focused = true;
18980
18981 // Hidden tab bar will show a triangle on the upper-left (in Begin)
18982 if (node->IsHiddenTabBar() || node->IsNoTabBar())
18983 {
18984 node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
18985 node->IsFocused = is_focused;
18986 if (is_focused)
18987 node->LastFrameFocused = g.FrameCount;
18988 if (node->VisibleWindow)
18989 {
18990 // Notify root of visible window (used to display title in OS task bar)
18991 if (is_focused || root_node->VisibleWindow == NULL)
18992 root_node->VisibleWindow = node->VisibleWindow;
18993 if (node->TabBar)
18994 node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
18995 }
18996 return;
18997 }
18998
18999 // 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
19000 bool backup_skip_item = host_window->SkipItems;
19001 if (!node->IsDockSpace())
19002 {
19003 host_window->SkipItems = false;
19004 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
19005 }
19006
19007 // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
19008 // 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,
19009 // as docked windows themselves will override the stack with their own root ID.
19010 PushOverrideID(node->ID);
19011 ImGuiTabBar* tab_bar = node->TabBar;
19012 bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
19013 if (tab_bar == NULL)
19014 {
19015 DockNodeAddTabBar(node);
19016 tab_bar = node->TabBar;
19017 }
19018
19019 ImGuiID focus_tab_id = 0;
19020 node->IsFocused = is_focused;
19021
19022 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
19023 const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
19024
19025 // In a dock node, the Collapse Button turns into the Window Menu button.
19026 // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
19027 if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
19028 {
19029 ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
19030 DockNodeWindowMenuUpdate(node, tab_bar);
19031 if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
19032 focus_tab_id = tab_bar->NextSelectedTabId;
19033 is_focused |= node->IsFocused;
19034 }
19035
19036 // Layout
19037 ImRect title_bar_rect, tab_bar_rect;
19038 ImVec2 window_menu_button_pos;
19039 ImVec2 close_button_pos;
19040 DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
19041
19042 // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
19043 const int tabs_count_old = tab_bar->Tabs.Size;
19044 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19045 {
19046 ImGuiWindow* window = node->Windows[window_n];
19047 if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
19048 TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
19049 }
19050
19051 // Title bar
19052 if (is_focused)
19053 node->LastFrameFocused = g.FrameCount;
19054 ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
19055 ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
19056 host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
19057
19058 // Docking/Collapse button
19059 if (has_window_menu_button)
19060 {
19061 if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
19062 OpenPopup("#WindowMenu");
19063 if (IsItemActive())
19064 focus_tab_id = tab_bar->SelectedTabId;
19065 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
19066 SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
19067 }
19068
19069 // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
19070 int tabs_unsorted_start = tab_bar->Tabs.Size;
19071 for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
19072 {
19073 // 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?
19074 tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
19075 tabs_unsorted_start = tab_n;
19076 }
19077 if (tab_bar->Tabs.Size > tabs_unsorted_start)
19078 {
19079 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)" : "");
19080 for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
19081 {
19082 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19083 IM_UNUSED(tab);
19084 IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
19085 }
19086 IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
19087 if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
19088 ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
19089 }
19090
19091 // Apply NavWindow focus back to the tab bar
19092 if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
19093 tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
19094
19095 // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
19096 if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
19097 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
19098 else if (tab_bar->Tabs.Size > tabs_count_old)
19099 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
19100
19101 // Begin tab bar
19102 ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
19103 tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
19104 tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyMixed; // Enforce default policy. Since 1.92.2 this is now reasonable. May expose later if needed. (#8800, #3421)
19105 tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
19106 if (!host_window->Collapsed && is_focused)
19107 tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
19108 tab_bar->ID = GetID("#TabBar");
19109 tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
19110 tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
19111 BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
19112 //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
19113
19114 // Backup style colors
19115 ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
19116 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19117 backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
19118
19119 // Submit actual tabs
19120 node->VisibleWindow = NULL;
19121 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19122 {
19123 ImGuiWindow* window = node->Windows[window_n];
19124 if (window->LastFrameActive + 1 < g.FrameCount && node_was_active)
19125 continue; // FIXME: Not sure if that's still taken/useful.
19126
19127 ImGuiTabItemFlags tab_item_flags = 0;
19128 tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
19129 if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
19130 tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
19131 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
19132 tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
19133
19134 // Apply stored style overrides for the window
19135 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19136 g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
19137
19138 // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
19139 bool tab_open = true;
19140 TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
19141 if (!tab_open)
19142 node->WantCloseTabId = window->TabId;
19143 if (tab_bar->VisibleTabId == window->TabId)
19144 node->VisibleWindow = window;
19145
19146 // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
19147 window->DC.DockTabItemStatusFlags = g.LastItemData.StatusFlags;
19148 window->DC.DockTabItemRect = g.LastItemData.Rect;
19149
19150 // Update navigation ID on menu layer
19151 if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
19152 host_window->NavLastIds[1] = window->TabId;
19153 }
19154
19155 // Restore style colors
19156 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19157 g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
19158
19159 // Notify root of visible window (used to display title in OS task bar)
19160 if (node->VisibleWindow)
19161 if (is_focused || root_node->VisibleWindow == NULL)
19162 root_node->VisibleWindow = node->VisibleWindow;
19163
19164 // Close button (after VisibleWindow was updated)
19165 // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
19166 const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
19167 const bool close_button_is_visible = node->HasCloseButton;
19168 //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)
19169 if (close_button_is_visible)
19170 {
19171 if (!close_button_is_enabled)
19172 {
19173 PushItemFlag(ImGuiItemFlags_Disabled, true);
19174 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
19175 }
19176 if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
19177 {
19178 node->WantCloseAll = true;
19179 for (int n = 0; n < tab_bar->Tabs.Size; n++)
19180 TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
19181 }
19182 //if (IsItemActive())
19183 // focus_tab_id = tab_bar->SelectedTabId;
19184 if (!close_button_is_enabled)
19185 {
19186 PopStyleColor();
19187 PopItemFlag();
19188 }
19189 }
19190
19191 // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
19192 // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
19193 ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
19194 if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
19195 {
19196 // AllowOverlap mode required for appending into dock node tab bar,
19197 // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
19198 bool held;
19199 KeepAliveID(title_bar_id);
19200 ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
19201 if (g.HoveredId == title_bar_id)
19202 {
19203 g.LastItemData.ID = title_bar_id;
19204 }
19205 if (held)
19206 {
19207 if (IsMouseClicked(0))
19208 focus_tab_id = tab_bar->SelectedTabId;
19209
19210 // Forward moving request to selected window
19211 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
19212 StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
19213 }
19214 }
19215
19216 // Forward focus from host node to selected window
19217 //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
19218 // focus_tab_id = tab_bar->SelectedTabId;
19219
19220 // When clicked on a tab we requested focus to the docked child
19221 // This overrides the value set by "forward focus from host node to selected window".
19222 if (tab_bar->NextSelectedTabId)
19223 focus_tab_id = tab_bar->NextSelectedTabId;
19224
19225 // Apply navigation focus
19226 if (focus_tab_id != 0)
19227 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
19228 if (tab->Window)
19229 {
19230 FocusWindow(tab->Window);
19231 NavInitWindow(tab->Window, false);
19232 }
19233
19234 EndTabBar();
19235 PopID();
19236
19237 // Restore SkipItems flag
19238 if (!node->IsDockSpace())
19239 {
19240 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
19241 host_window->SkipItems = backup_skip_item;
19242 }
19243 }
19244
19245 static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
19246 {
19247 IM_ASSERT(node->TabBar == NULL);
19248 node->TabBar = IM_NEW(ImGuiTabBar);
19249 }
19250
19251 static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
19252 {
19253 if (node->TabBar == NULL)
19254 return;
19255 IM_DELETE(node->TabBar);
19256 node->TabBar = NULL;
19257 }
19258
19259 static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
19260 {
19261 if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
19262 return false;
19263
19264 ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
19265 ImGuiWindowClass* payload_class = &payload->WindowClass;
19266 if (host_class->ClassId != payload_class->ClassId)
19267 {
19268 bool pass = false;
19269 if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
19270 pass = true;
19271 if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
19272 pass = true;
19273 if (!pass)
19274 return false;
19275 }
19276
19277 // Prevent docking any window created above a popup
19278 // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
19279 // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
19280 // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
19281 // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
19282 ImGuiContext& g = *GImGui;
19283 for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
19284 if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
19285 if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window)) // Payload is created from within a popup begin stack.
19286 return false;
19287
19288 return true;
19289 }
19290
19291 static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
19292 {
19293 if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
19294 return true;
19295
19296 const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
19297 for (int payload_n = 0; payload_n < payload_count; payload_n++)
19298 {
19299 ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
19300 if (DockNodeIsDropAllowedOne(payload, host_window))
19301 return true;
19302 }
19303 return false;
19304 }
19305
19306 // window menu button == collapse button when not in a dock node.
19307 // FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
19308 static 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)
19309 {
19310 ImGuiContext& g = *GImGui;
19311 ImGuiStyle& style = g.Style;
19312
19313 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);
19314 if (out_title_rect) { *out_title_rect = r; }
19315
19316 r.Min.x += style.WindowBorderSize;
19317 r.Max.x -= style.WindowBorderSize;
19318
19319 float button_sz = g.FontSize;
19320 r.Min.x += style.FramePadding.x;
19321 r.Max.x -= style.FramePadding.x;
19322 ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
19323 if (node->HasCloseButton)
19324 {
19325 if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
19326 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
19327 }
19328 if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
19329 {
19330 r.Min.x += button_sz + style.ItemInnerSpacing.x;
19331 }
19332 else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
19333 {
19334 window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
19335 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
19336 }
19337 if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
19338 if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
19339 }
19340
19341 void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
19342 {
19343 ImGuiContext& g = *GImGui;
19344 const float dock_spacing = g.Style.ItemInnerSpacing.x;
19345 const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
19346 pos_new[axis ^ 1] = pos_old[axis ^ 1];
19347 size_new[axis ^ 1] = size_old[axis ^ 1];
19348
19349 // Distribute size on given axis (with a desired size or equally)
19350 const float w_avail = size_old[axis] - dock_spacing;
19351 if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
19352 {
19353 size_new[axis] = size_new_desired[axis];
19354 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
19355 }
19356 else
19357 {
19358 size_new[axis] = IM_TRUNC(w_avail * 0.5f);
19359 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
19360 }
19361
19362 // Position each node
19363 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
19364 {
19365 pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
19366 }
19367 else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
19368 {
19369 pos_new[axis] = pos_old[axis];
19370 pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
19371 }
19372 }
19373
19374 // Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
19375 bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
19376 {
19377 ImGuiContext& g = *GImGui;
19378
19379 const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
19380 const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
19381 float hs_w; // Half-size, longer axis
19382 float hs_h; // Half-size, smaller axis
19383 ImVec2 off; // Distance from edge or center
19384 if (outer_docking)
19385 {
19386 //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
19387 //hs_h = ImTrunc(hs_w * 0.15f);
19388 //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
19389 hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
19390 hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
19391 off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
19392 }
19393 else
19394 {
19395 hs_w = ImTrunc(hs_for_central_nodes);
19396 hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
19397 off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
19398 }
19399
19400 ImVec2 c = ImTrunc(parent.GetCenter());
19401 if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
19402 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); }
19403 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); }
19404 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); }
19405 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); }
19406
19407 if (test_mouse_pos == NULL)
19408 return false;
19409
19410 ImRect hit_r = out_r;
19411 if (!outer_docking)
19412 {
19413 // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
19414 hit_r.Expand(ImTrunc(hs_w * 0.30f));
19415 ImVec2 mouse_delta = (*test_mouse_pos - c);
19416 float mouse_delta_len2 = ImLengthSqr(mouse_delta);
19417 float r_threshold_center = hs_w * 1.4f;
19418 float r_threshold_sides = hs_w * (1.4f + 1.2f);
19419 if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
19420 return (dir == ImGuiDir_None);
19421 if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
19422 return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
19423 }
19424 return hit_r.Contains(*test_mouse_pos);
19425 }
19426
19427 // host_node may be NULL if the window doesn't have a DockNode already.
19428 // FIXME-DOCK: This is misnamed since it's also doing the filtering.
19429 static 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)
19430 {
19431 ImGuiContext& g = *GImGui;
19432
19433 // There is an edge case when docking into a dockspace which only has inactive nodes.
19434 // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
19435 // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
19436 if (payload_node == NULL)
19437 payload_node = payload_window->DockNodeAsHost;
19438 ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
19439 if (ref_node_for_rect)
19440 IM_ASSERT(ref_node_for_rect->IsVisible == true);
19441
19442 // Filter, figure out where we are allowed to dock
19443 ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
19444 ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
19445 data->IsCenterAvailable = true;
19446 if (is_outer_docking)
19447 data->IsCenterAvailable = false;
19448 else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
19449 data->IsCenterAvailable = false;
19450 else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
19451 data->IsCenterAvailable = false;
19452 else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
19453 data->IsCenterAvailable = false;
19454 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
19455 data->IsCenterAvailable = false;
19456 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
19457 data->IsCenterAvailable = false;
19458
19459 data->IsSidesAvailable = true;
19460 if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
19461 data->IsSidesAvailable = false;
19462 else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
19463 data->IsSidesAvailable = false;
19464 else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
19465 data->IsSidesAvailable = false;
19466
19467 // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
19468 data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
19469 data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
19470 data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
19471 data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
19472
19473 // Calculate drop shapes geometry for allowed splitting directions
19474 IM_ASSERT(ImGuiDir_None == -1);
19475 data->SplitNode = host_node;
19476 data->SplitDir = ImGuiDir_None;
19477 data->IsSplitDirExplicit = false;
19478 if (!host_window->Collapsed)
19479 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
19480 {
19481 if (dir == ImGuiDir_None && !data->IsCenterAvailable)
19482 continue;
19483 if (dir != ImGuiDir_None && !data->IsSidesAvailable)
19484 continue;
19485 if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
19486 {
19487 data->SplitDir = (ImGuiDir)dir;
19488 data->IsSplitDirExplicit = true;
19489 }
19490 }
19491
19492 // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
19493 data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
19494 if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
19495 data->IsDropAllowed = false;
19496
19497 // Calculate split area
19498 data->SplitRatio = 0.0f;
19499 if (data->SplitDir != ImGuiDir_None)
19500 {
19501 ImGuiDir split_dir = data->SplitDir;
19502 ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
19503 ImVec2 pos_new, pos_old = data->FutureNode.Pos;
19504 ImVec2 size_new, size_old = data->FutureNode.Size;
19505 DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
19506
19507 // Calculate split ratio so we can pass it down the docking request
19508 float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
19509 data->FutureNode.Pos = pos_new;
19510 data->FutureNode.Size = size_new;
19511 data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
19512 }
19513 }
19514
19515 static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
19516 {
19517 ImGuiContext& g = *GImGui;
19518 IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
19519
19520 // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
19521 // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
19522 const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
19523
19524 // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
19525 int overlay_draw_lists_count = 0;
19526 ImDrawList* overlay_draw_lists[2];
19527 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
19528 if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
19529 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
19530
19531 // Draw main preview rectangle
19532 const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
19533 const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
19534 const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
19535 const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
19536
19537 // Display area preview
19538 const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
19539 if (data->IsDropAllowed)
19540 {
19541 ImRect overlay_rect = data->FutureNode.Rect();
19542 if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
19543 overlay_rect.Min.y += GetFrameHeight();
19544 if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
19545 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19546 overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
19547 }
19548
19549 // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
19550 if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
19551 {
19552 // Compute target tab bar geometry so we can locate our preview tabs
19553 ImRect tab_bar_rect;
19554 DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
19555 ImVec2 tab_pos = tab_bar_rect.Min;
19556 if (host_node && host_node->TabBar)
19557 {
19558 if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
19559 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.
19560 else
19561 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
19562 }
19563 else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
19564 {
19565 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
19566 }
19567
19568 // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
19569 if (root_payload->DockNodeAsHost)
19570 IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
19571 ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
19572 const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
19573 for (int payload_n = 0; payload_n < payload_count; payload_n++)
19574 {
19575 // DockNode's TabBar may have non-window Tabs manually appended by user
19576 ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
19577 if (tab_bar_with_payload && payload_window == NULL)
19578 continue;
19579 if (!DockNodeIsDropAllowedOne(payload_window, host_window))
19580 continue;
19581
19582 // Calculate the tab bounding box for each payload window
19583 ImVec2 tab_size = TabItemCalcSize(payload_window);
19584 ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
19585 tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
19586 const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
19587 const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
19588 PushStyleColor(ImGuiCol_Text, overlay_col_text);
19589 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19590 {
19591 ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
19592 if (!tab_bar_rect.Contains(tab_bb))
19593 overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
19594 TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
19595 TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
19596 if (!tab_bar_rect.Contains(tab_bb))
19597 overlay_draw_lists[overlay_n]->PopClipRect();
19598 }
19599 PopStyleColor();
19600 }
19601 }
19602
19603 // Display drop boxes
19604 const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
19605 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
19606 {
19607 if (!data->DropRectsDraw[dir + 1].IsInverted())
19608 {
19609 ImRect draw_r = data->DropRectsDraw[dir + 1];
19610 ImRect draw_r_in = draw_r;
19611 draw_r_in.Expand(-2.0f);
19612 ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
19613 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19614 {
19615 ImVec2 center = ImFloor(draw_r_in.GetCenter());
19616 overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
19617 overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
19618 if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
19619 overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
19620 if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
19621 overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
19622 }
19623 }
19624
19625 // Stop after ImGuiDir_None
19626 if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
19627 return;
19628 }
19629 }
19630
19631 //-----------------------------------------------------------------------------
19632 // Docking: ImGuiDockNode Tree manipulation functions
19633 //-----------------------------------------------------------------------------
19634 // - DockNodeTreeSplit()
19635 // - DockNodeTreeMerge()
19636 // - DockNodeTreeUpdatePosSize()
19637 // - DockNodeTreeUpdateSplitterFindTouchingNode()
19638 // - DockNodeTreeUpdateSplitter()
19639 // - DockNodeTreeFindFallbackLeafNode()
19640 // - DockNodeTreeFindNodeByPos()
19641 //-----------------------------------------------------------------------------
19642
19643 void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
19644 {
19645 ImGuiContext& g = *GImGui;
19646 IM_ASSERT(split_axis != ImGuiAxis_None);
19647
19648 ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
19649 child_0->ParentNode = parent_node;
19650
19651 ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
19652 child_1->ParentNode = parent_node;
19653
19654 ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
19655 DockNodeMoveChildNodes(child_inheritor, parent_node);
19656 parent_node->ChildNodes[0] = child_0;
19657 parent_node->ChildNodes[1] = child_1;
19658 parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
19659 parent_node->SplitAxis = split_axis;
19660 parent_node->VisibleWindow = NULL;
19661 parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
19662
19663 float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
19664 size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
19665 IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
19666 child_0->SizeRef = child_1->SizeRef = parent_node->Size;
19667 child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
19668 child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
19669
19670 DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
19671 DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
19672 DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
19673 DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
19674
19675 // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
19676 child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
19677 child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
19678 child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19679 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19680 child_0->UpdateMergedFlags();
19681 child_1->UpdateMergedFlags();
19682 parent_node->UpdateMergedFlags();
19683 if (child_inheritor->IsCentralNode())
19684 DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
19685 }
19686
19687 void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
19688 {
19689 // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
19690 ImGuiContext& g = *GImGui;
19691 ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
19692 ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
19693 IM_ASSERT(child_0 || child_1);
19694 IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
19695 if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
19696 {
19697 IM_ASSERT(parent_node->TabBar == NULL);
19698 IM_ASSERT(parent_node->Windows.Size == 0);
19699 }
19700 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);
19701
19702 ImVec2 backup_last_explicit_size = parent_node->SizeRef;
19703 DockNodeMoveChildNodes(parent_node, merge_lead_child);
19704 if (child_0)
19705 {
19706 DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
19707 DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
19708 }
19709 if (child_1)
19710 {
19711 DockNodeMoveWindows(parent_node, child_1);
19712 DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
19713 }
19714 DockNodeApplyPosSizeToWindows(parent_node);
19715 parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
19716 parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
19717 parent_node->SizeRef = backup_last_explicit_size;
19718
19719 // Flags transfer
19720 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
19721 parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19722 parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19723 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
19724 parent_node->UpdateMergedFlags();
19725
19726 if (child_0)
19727 {
19728 ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
19729 IM_DELETE(child_0);
19730 }
19731 if (child_1)
19732 {
19733 ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
19734 IM_DELETE(child_1);
19735 }
19736 }
19737
19738 // Update Pos/Size for a node hierarchy (don't affect child Windows yet)
19739 // (Depth-first, Pre-Order)
19740 void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
19741 {
19742 // During the regular dock node update we write to all nodes.
19743 // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
19744 ImGuiContext& g = *GImGui;
19745 const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
19746 if (write_to_node)
19747 {
19748 node->Pos = pos;
19749 node->Size = size;
19750 }
19751
19752 if (node->IsLeafNode())
19753 return;
19754
19755 ImGuiDockNode* child_0 = node->ChildNodes[0];
19756 ImGuiDockNode* child_1 = node->ChildNodes[1];
19757 ImVec2 child_0_pos = pos, child_1_pos = pos;
19758 ImVec2 child_0_size = size, child_1_size = size;
19759
19760 const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
19761 const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
19762 const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
19763 const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
19764
19765 if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
19766 {
19767 const float spacing = g.Style.DockingSeparatorSize;
19768 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
19769 const float size_avail = ImMax(size[axis] - spacing, 0.0f);
19770
19771 // Size allocation policy
19772 // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
19773 const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
19774
19775 // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
19776 // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
19777 // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
19778
19779 // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
19780 if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
19781 {
19782 child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
19783 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
19784 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
19785 }
19786 else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
19787 {
19788 child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
19789 child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
19790 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
19791 }
19792 else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
19793 {
19794 // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
19795 // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
19796 float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
19797 child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
19798 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
19799 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
19800 }
19801
19802 // 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
19803 else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
19804 {
19805 child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
19806 child_1_size[axis] = (size_avail - child_0_size[axis]);
19807 }
19808 else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
19809 {
19810 child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
19811 child_0_size[axis] = (size_avail - child_1_size[axis]);
19812 }
19813 else
19814 {
19815 // 4) Otherwise distribute according to the relative ratio of each SizeRef value
19816 float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
19817 child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
19818 child_1_size[axis] = (size_avail - child_0_size[axis]);
19819 }
19820
19821 child_1_pos[axis] += spacing + child_0_size[axis];
19822 }
19823
19824 if (only_write_to_single_node == NULL)
19825 child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
19826
19827 const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
19828 const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
19829 if (child_0_recurse)
19830 DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
19831 if (child_1_recurse)
19832 DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
19833 }
19834
19835 static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
19836 {
19837 if (node->IsLeafNode())
19838 {
19839 touching_nodes->push_back(node);
19840 return;
19841 }
19842 if (node->ChildNodes[0]->IsVisible)
19843 if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
19844 DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
19845 if (node->ChildNodes[1]->IsVisible)
19846 if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
19847 DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
19848 }
19849
19850 // (Depth-First, Pre-Order)
19851 void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
19852 {
19853 if (node->IsLeafNode())
19854 return;
19855
19856 ImGuiContext& g = *GImGui;
19857
19858 ImGuiDockNode* child_0 = node->ChildNodes[0];
19859 ImGuiDockNode* child_1 = node->ChildNodes[1];
19860 if (child_0->IsVisible && child_1->IsVisible)
19861 {
19862 // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
19863 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
19864 IM_ASSERT(axis != ImGuiAxis_None);
19865 ImRect bb;
19866 bb.Min = child_0->Pos;
19867 bb.Max = child_1->Pos;
19868 bb.Min[axis] += child_0->Size[axis];
19869 bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
19870 //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
19871
19872 const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
19873 const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
19874 if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
19875 {
19876 ImGuiWindow* window = g.CurrentWindow;
19877 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
19878 }
19879 else
19880 {
19881 //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
19882 //bb.Max[axis] -= 1;
19883 PushID(node->ID);
19884
19885 // Find resizing limits by gathering list of nodes that are touching the splitter line.
19886 ImVector<ImGuiDockNode*> touching_nodes[2];
19887 float min_size = g.Style.WindowMinSize[axis];
19888 float resize_limits[2];
19889 resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
19890 resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
19891
19892 ImGuiID splitter_id = GetID("##Splitter");
19893 if (g.ActiveId == splitter_id) // Only process when splitter is active
19894 {
19895 DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
19896 DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
19897 for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
19898 resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
19899 for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
19900 resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
19901
19902 // [DEBUG] Render touching nodes & limits
19903 /*
19904 ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19905 for (int n = 0; n < 2; n++)
19906 {
19907 for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
19908 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));
19909 if (axis == ImGuiAxis_X)
19910 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);
19911 else
19912 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);
19913 }
19914 */
19915 }
19916
19917 // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
19918 float cur_size_0 = child_0->Size[axis];
19919 float cur_size_1 = child_1->Size[axis];
19920 float min_size_0 = resize_limits[0] - child_0->Pos[axis];
19921 float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
19922 ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
19923 if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, g.WindowsBorderHoverPadding, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
19924 {
19925 if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
19926 {
19927 child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
19928 child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
19929 child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
19930
19931 // Lock the size of every node that is a sibling of the node we are touching
19932 // This might be less desirable if we can merge sibling of a same axis into the same parental level.
19933 for (int side_n = 0; side_n < 2; side_n++)
19934 for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
19935 {
19936 ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
19937 //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19938 //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
19939 while (touching_node->ParentNode != node)
19940 {
19941 if (touching_node->ParentNode->SplitAxis == axis)
19942 {
19943 // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
19944 ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
19945 node_to_preserve->WantLockSizeOnce = true;
19946 //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
19947 //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
19948 }
19949 touching_node = touching_node->ParentNode;
19950 }
19951 }
19952
19953 DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
19954 DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
19955 MarkIniSettingsDirty();
19956 }
19957 }
19958 PopID();
19959 }
19960 }
19961
19962 if (child_0->IsVisible)
19963 DockNodeTreeUpdateSplitter(child_0);
19964 if (child_1->IsVisible)
19965 DockNodeTreeUpdateSplitter(child_1);
19966 }
19967
19968 ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
19969 {
19970 if (node->IsLeafNode())
19971 return node;
19972 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
19973 return leaf_node;
19974 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
19975 return leaf_node;
19976 return NULL;
19977 }
19978
19979 ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
19980 {
19981 if (!node->IsVisible)
19982 return NULL;
19983
19984 const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
19985 ImRect r(node->Pos, node->Pos + node->Size);
19986 r.Expand(dock_spacing * 0.5f);
19987 bool inside = r.Contains(pos);
19988 if (!inside)
19989 return NULL;
19990
19991 if (node->IsLeafNode())
19992 return node;
19993 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
19994 return hovered_node;
19995 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
19996 return hovered_node;
19997
19998 // This means we are hovering over the splitter/spacing of a parent node
19999 return node;
20000 }
20001
20002 //-----------------------------------------------------------------------------
20003 // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
20004 //-----------------------------------------------------------------------------
20005 // - SetWindowDock() [Internal]
20006 // - DockSpace()
20007 // - DockSpaceOverViewport()
20008 //-----------------------------------------------------------------------------
20009
20010 // [Internal] Called via SetNextWindowDockID()
20011 void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
20012 {
20013 // Test condition (NB: bit 0 is always true) and clear flags for next time
20014 if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
20015 return;
20016 window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
20017
20018 if (window->DockId == dock_id)
20019 return;
20020
20021 // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
20022 ImGuiContext& g = *GImGui;
20023 if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
20024 if (new_node->IsSplitNode())
20025 {
20026 // Policy: Find central node or latest focused node. We first move back to our root node.
20027 new_node = DockNodeGetRootNode(new_node);
20028 if (new_node->CentralNode)
20029 {
20030 IM_ASSERT(new_node->CentralNode->IsCentralNode());
20031 dock_id = new_node->CentralNode->ID;
20032 }
20033 else
20034 {
20035 dock_id = new_node->LastFocusedNodeId;
20036 }
20037 }
20038
20039 if (window->DockId == dock_id)
20040 return;
20041
20042 if (window->DockNode)
20043 DockNodeRemoveWindow(window->DockNode, window, 0);
20044 window->DockId = dock_id;
20045 }
20046
20047 // Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
20048 // The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
20049 // DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
20050 // When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
20051 ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
20052 {
20053 ImGuiContext& g = *GImGui;
20054 ImGuiWindow* window = GetCurrentWindowRead();
20055 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
20056 return 0;
20057
20058 // Early out if parent window is hidden/collapsed
20059 // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
20060 // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
20061 if (window->SkipItems)
20062 flags |= ImGuiDockNodeFlags_KeepAliveOnly;
20063 if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
20064 window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
20065
20066 IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags!
20067 IM_ASSERT((flags & ImGuiDockNodeFlags_CentralNode) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145)
20068
20069 IM_ASSERT(dockspace_id != 0);
20070 ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
20071 if (node == NULL)
20072 {
20073 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
20074 node = DockContextAddNode(&g, dockspace_id);
20075 node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
20076 }
20077 if (window_class && window_class->ClassId != node->WindowClass.ClassId)
20078 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);
20079 node->SharedFlags = flags;
20080 node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
20081
20082 // When a DockSpace transitioned form implicit to explicit this may be called a second time
20083 // 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.
20084 if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
20085 {
20086 IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
20087 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
20088 return dockspace_id;
20089 }
20090 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
20091
20092 // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
20093 if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
20094 {
20095 node->LastFrameAlive = g.FrameCount;
20096 return dockspace_id;
20097 }
20098
20099 const ImVec2 content_avail = GetContentRegionAvail();
20100 ImVec2 size = ImTrunc(size_arg);
20101 if (size.x <= 0.0f)
20102 size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
20103 if (size.y <= 0.0f)
20104 size.y = ImMax(content_avail.y + size.y, 4.0f);
20105 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
20106
20107 node->Pos = window->DC.CursorPos;
20108 node->Size = node->SizeRef = size;
20109 SetNextWindowPos(node->Pos);
20110 SetNextWindowSize(node->Size);
20111 g.NextWindowData.PosUndock = false;
20112
20113 // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
20114 // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
20115 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
20116 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
20117 window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
20118 window_flags |= ImGuiWindowFlags_NoBackground;
20119
20120 char title[256];
20121 ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
20122
20123 PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
20124 Begin(title, NULL, window_flags);
20125 PopStyleVar();
20126
20127 ImGuiWindow* host_window = g.CurrentWindow;
20128 DockNodeSetupHostWindow(node, host_window);
20129 host_window->ChildId = window->GetID(title);
20130 node->OnlyNodeWithWindows = NULL;
20131
20132 IM_ASSERT(node->IsRootNode());
20133
20134 // We need to handle the rare case were a central node is missing.
20135 // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
20136 // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
20137 // 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.
20138 // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
20139 // as it doesn't make sense for an empty dockspace to not have this property.
20140 if (node->IsLeafNode() && !node->IsCentralNode())
20141 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20142
20143 // Update the node
20144 DockNodeUpdate(node);
20145
20146 End();
20147
20148 ImRect bb(node->Pos, node->Pos + size);
20149 ItemSize(size);
20150 ItemAdd(bb, dockspace_id, NULL, 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?)
20151 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
20152 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
20153
20154 return dockspace_id;
20155 }
20156
20157 // Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
20158 // The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
20159 // 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.
20160 // 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.
20161 ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
20162 {
20163 if (viewport == NULL)
20164 viewport = GetMainViewport();
20165
20166 // Submit a window filling the entire viewport
20167 SetNextWindowPos(viewport->WorkPos);
20168 SetNextWindowSize(viewport->WorkSize);
20169 SetNextWindowViewport(viewport->ID);
20170
20171 ImGuiWindowFlags host_window_flags = 0;
20172 host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
20173 host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
20174 if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
20175 host_window_flags |= ImGuiWindowFlags_NoBackground;
20176
20177 // FIXME-OPT: When using ImGuiDockNodeFlags_KeepAliveOnly with DockSpaceOverViewport() we might be able to spare submitting the window,
20178 // since DockSpace() with that flag doesn't need a window. We'd only need to compute the default ID accordingly.
20179 if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly)
20180 host_window_flags |= ImGuiWindowFlags_NoMouseInputs;
20181
20182 char label[32];
20183 ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
20184
20185 PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
20186 PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
20187 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
20188 Begin(label, NULL, host_window_flags);
20189 PopStyleVar(3);
20190
20191 // Submit the dockspace
20192 if (dockspace_id == 0)
20193 dockspace_id = GetID("DockSpace");
20194 DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
20195
20196 End();
20197
20198 return dockspace_id;
20199 }
20200
20201 //-----------------------------------------------------------------------------
20202 // Docking: Builder Functions
20203 //-----------------------------------------------------------------------------
20204 // Very early end-user API to manipulate dock nodes.
20205 // Only available in imgui_internal.h. Expect this API to change/break!
20206 // It is expected that those functions are all called _before_ the dockspace node submission.
20207 //-----------------------------------------------------------------------------
20208 // - DockBuilderDockWindow()
20209 // - DockBuilderGetNode()
20210 // - DockBuilderSetNodePos()
20211 // - DockBuilderSetNodeSize()
20212 // - DockBuilderAddNode()
20213 // - DockBuilderRemoveNode()
20214 // - DockBuilderRemoveNodeChildNodes()
20215 // - DockBuilderRemoveNodeDockedWindows()
20216 // - DockBuilderSplitNode()
20217 // - DockBuilderCopyNodeRec()
20218 // - DockBuilderCopyNode()
20219 // - DockBuilderCopyWindowSettings()
20220 // - DockBuilderCopyDockSpace()
20221 // - DockBuilderFinish()
20222 //-----------------------------------------------------------------------------
20223
20224 void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
20225 {
20226 // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
20227 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20228 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
20229 ImGuiID window_id = ImHashStr(window_name);
20230 if (ImGuiWindow* window = FindWindowByID(window_id))
20231 {
20232 // Apply to created window
20233 ImGuiID prev_node_id = window->DockId;
20234 SetWindowDock(window, node_id, ImGuiCond_Always);
20235 if (window->DockId != prev_node_id)
20236 window->DockOrder = -1;
20237 }
20238 else
20239 {
20240 // Apply to settings
20241 ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
20242 if (settings == NULL)
20243 settings = CreateNewWindowSettings(window_name);
20244 if (settings->DockId != node_id)
20245 settings->DockOrder = -1;
20246 settings->DockId = node_id;
20247 }
20248 }
20249
20250 ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
20251 {
20252 ImGuiContext& g = *GImGui;
20253 return DockContextFindNodeByID(&g, node_id);
20254 }
20255
20256 void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
20257 {
20258 ImGuiContext& g = *GImGui;
20259 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
20260 if (node == NULL)
20261 return;
20262 node->Pos = pos;
20263 node->AuthorityForPos = ImGuiDataAuthority_DockNode;
20264 }
20265
20266 void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
20267 {
20268 ImGuiContext& g = *GImGui;
20269 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
20270 if (node == NULL)
20271 return;
20272 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
20273 node->Size = node->SizeRef = size;
20274 node->AuthorityForSize = ImGuiDataAuthority_DockNode;
20275 }
20276
20277 // Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
20278 // - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
20279 // - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
20280 // - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
20281 // For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
20282 // - Use (id == 0) to let the system allocate a node identifier.
20283 // - Existing node with a same id will be removed.
20284 ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
20285 {
20286 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20287 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
20288
20289 if (node_id != 0)
20290 DockBuilderRemoveNode(node_id);
20291
20292 ImGuiDockNode* node = NULL;
20293 if (flags & ImGuiDockNodeFlags_DockSpace)
20294 {
20295 DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
20296 node = DockContextFindNodeByID(&g, node_id);
20297 }
20298 else
20299 {
20300 node = DockContextAddNode(&g, node_id);
20301 node->SetLocalFlags(flags);
20302 }
20303 node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
20304 return node->ID;
20305 }
20306
20307 void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
20308 {
20309 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20310 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
20311
20312 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
20313 if (node == NULL)
20314 return;
20315 DockBuilderRemoveNodeDockedWindows(node_id, true);
20316 DockBuilderRemoveNodeChildNodes(node_id);
20317 // Node may have moved or deleted if e.g. any merge happened
20318 node = DockContextFindNodeByID(&g, node_id);
20319 if (node == NULL)
20320 return;
20321 if (node->IsCentralNode() && node->ParentNode)
20322 node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20323 DockContextRemoveNode(&g, node, true);
20324 }
20325
20326 // root_id = 0 to remove all, root_id != 0 to remove child of given node.
20327 void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
20328 {
20329 ImGuiContext& g = *GImGui;
20330 ImGuiDockContext* dc = &g.DockContext;
20331
20332 ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
20333 if (root_id && root_node == NULL)
20334 return;
20335 bool has_central_node = false;
20336
20337 ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
20338 ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
20339
20340 // Process active windows
20341 ImVector<ImGuiDockNode*> nodes_to_remove;
20342 for (int n = 0; n < dc->Nodes.Data.Size; n++)
20343 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20344 {
20345 bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
20346 if (want_removal)
20347 {
20348 if (node->IsCentralNode())
20349 has_central_node = true;
20350 if (root_id != 0)
20351 DockContextQueueNotifyRemovedNode(&g, node);
20352 if (root_node)
20353 {
20354 DockNodeMoveWindows(root_node, node);
20355 DockSettingsRenameNodeReferences(node->ID, root_node->ID);
20356 }
20357 nodes_to_remove.push_back(node);
20358 }
20359 }
20360
20361 // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
20362 // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
20363 if (root_node)
20364 {
20365 root_node->AuthorityForPos = backup_root_node_authority_for_pos;
20366 root_node->AuthorityForSize = backup_root_node_authority_for_size;
20367 }
20368
20369 // Apply to settings
20370 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20371 if (ImGuiID window_settings_dock_id = settings->DockId)
20372 for (int n = 0; n < nodes_to_remove.Size; n++)
20373 if (nodes_to_remove[n]->ID == window_settings_dock_id)
20374 {
20375 settings->DockId = root_id;
20376 break;
20377 }
20378
20379 // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
20380 if (nodes_to_remove.Size > 1)
20381 ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
20382 for (int n = 0; n < nodes_to_remove.Size; n++)
20383 DockContextRemoveNode(&g, nodes_to_remove[n], false);
20384
20385 if (root_id == 0)
20386 {
20387 dc->Nodes.Clear();
20388 dc->Requests.clear();
20389 }
20390 else if (has_central_node)
20391 {
20392 root_node->CentralNode = root_node;
20393 root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20394 }
20395 }
20396
20397 void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
20398 {
20399 // Clear references in settings
20400 ImGuiContext& g = *GImGui;
20401 if (clear_settings_refs)
20402 {
20403 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20404 {
20405 bool want_removal = (root_id == 0) || (settings->DockId == root_id);
20406 if (!want_removal && settings->DockId != 0)
20407 if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
20408 if (DockNodeGetRootNode(node)->ID == root_id)
20409 want_removal = true;
20410 if (want_removal)
20411 settings->DockId = 0;
20412 }
20413 }
20414
20415 // Clear references in windows
20416 for (int n = 0; n < g.Windows.Size; n++)
20417 {
20418 ImGuiWindow* window = g.Windows[n];
20419 bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
20420 if (want_removal)
20421 {
20422 const ImGuiID backup_dock_id = window->DockId;
20423 IM_UNUSED(backup_dock_id);
20424 DockContextProcessUndockWindow(&g, window, clear_settings_refs);
20425 if (!clear_settings_refs)
20426 IM_ASSERT(window->DockId == backup_dock_id);
20427 }
20428 }
20429 }
20430
20431 // 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.
20432 // Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
20433 // FIXME-DOCK: We are not exposing nor using split_outer.
20434 ImGuiID 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)
20435 {
20436 ImGuiContext& g = *GImGui;
20437 IM_ASSERT(split_dir != ImGuiDir_None);
20438 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
20439
20440 ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
20441 if (node == NULL)
20442 {
20443 IM_ASSERT(node != NULL);
20444 return 0;
20445 }
20446
20447 ImGuiDockRequest req;
20448 req.Type = ImGuiDockRequestType_Split;
20449 req.DockTargetWindow = NULL;
20450 req.DockTargetNode = node;
20451 req.DockPayload = NULL;
20452 req.DockSplitDir = split_dir;
20453 req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
20454 req.DockSplitOuter = false;
20455 DockContextProcessDock(&g, &req);
20456
20457 ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
20458 ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
20459 if (out_id_at_dir)
20460 *out_id_at_dir = id_at_dir;
20461 if (out_id_at_opposite_dir)
20462 *out_id_at_opposite_dir = id_at_opposite_dir;
20463 return id_at_dir;
20464 }
20465
20466 static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
20467 {
20468 ImGuiContext& g = *GImGui;
20469 ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
20470 dst_node->SharedFlags = src_node->SharedFlags;
20471 dst_node->LocalFlags = src_node->LocalFlags;
20472 dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
20473 dst_node->Pos = src_node->Pos;
20474 dst_node->Size = src_node->Size;
20475 dst_node->SizeRef = src_node->SizeRef;
20476 dst_node->SplitAxis = src_node->SplitAxis;
20477 dst_node->UpdateMergedFlags();
20478
20479 out_node_remap_pairs->push_back(src_node->ID);
20480 out_node_remap_pairs->push_back(dst_node->ID);
20481
20482 for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
20483 if (src_node->ChildNodes[child_n])
20484 {
20485 dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
20486 dst_node->ChildNodes[child_n]->ParentNode = dst_node;
20487 }
20488
20489 IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
20490 return dst_node;
20491 }
20492
20493 void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
20494 {
20495 ImGuiContext& g = *GImGui;
20496 IM_ASSERT(src_node_id != 0);
20497 IM_ASSERT(dst_node_id != 0);
20498 IM_ASSERT(out_node_remap_pairs != NULL);
20499
20500 DockBuilderRemoveNode(dst_node_id);
20501
20502 ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
20503 IM_ASSERT(src_node != NULL);
20504
20505 out_node_remap_pairs->clear();
20506 DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
20507
20508 IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
20509 }
20510
20511 void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
20512 {
20513 ImGuiWindow* src_window = FindWindowByName(src_name);
20514 if (src_window == NULL)
20515 return;
20516 if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
20517 {
20518 dst_window->Pos = src_window->Pos;
20519 dst_window->Size = src_window->Size;
20520 dst_window->SizeFull = src_window->SizeFull;
20521 dst_window->Collapsed = src_window->Collapsed;
20522 }
20523 else
20524 {
20525 ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
20526 if (!dst_settings)
20527 dst_settings = CreateNewWindowSettings(dst_name);
20528 ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
20529 if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
20530 {
20531 dst_settings->ViewportPos = window_pos_2ih;
20532 dst_settings->ViewportId = src_window->ViewportId;
20533 dst_settings->Pos = ImVec2ih(0, 0);
20534 }
20535 else
20536 {
20537 dst_settings->Pos = window_pos_2ih;
20538 }
20539 dst_settings->Size = ImVec2ih(src_window->SizeFull);
20540 dst_settings->Collapsed = src_window->Collapsed;
20541 }
20542 }
20543
20544 // FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
20545 void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
20546 {
20547 ImGuiContext& g = *GImGui;
20548 IM_ASSERT(src_dockspace_id != 0);
20549 IM_ASSERT(dst_dockspace_id != 0);
20550 IM_ASSERT(in_window_remap_pairs != NULL);
20551 IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
20552
20553 // Duplicate entire dock
20554 // 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,
20555 // whereas we could attempt to at least keep them together in a new, same floating node.
20556 ImVector<ImGuiID> node_remap_pairs;
20557 DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
20558
20559 // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
20560 // (The windows associated to src_dockspace_id are staying in place)
20561 ImVector<ImGuiID> src_windows;
20562 for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
20563 {
20564 const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
20565 const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
20566 ImGuiID src_window_id = ImHashStr(src_window_name);
20567 src_windows.push_back(src_window_id);
20568
20569 // Search in the remapping tables
20570 ImGuiID src_dock_id = 0;
20571 if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
20572 src_dock_id = src_window->DockId;
20573 else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
20574 src_dock_id = src_window_settings->DockId;
20575 ImGuiID dst_dock_id = 0;
20576 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
20577 if (node_remap_pairs[dock_remap_n] == src_dock_id)
20578 {
20579 dst_dock_id = node_remap_pairs[dock_remap_n + 1];
20580 //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
20581 break;
20582 }
20583
20584 if (dst_dock_id != 0)
20585 {
20586 // Docked windows gets redocked into the new node hierarchy.
20587 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);
20588 DockBuilderDockWindow(dst_window_name, dst_dock_id);
20589 }
20590 else
20591 {
20592 // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
20593 // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
20594 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
20595 DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
20596 }
20597 }
20598
20599 // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
20600 // Find those windows and move to them to the cloned dock node. This may be optional?
20601 // Dock those are a second step as undocking would invalidate source dock nodes.
20602 struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
20603 ImVector<DockRemainingWindowTask> dock_remaining_windows;
20604 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
20605 if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
20606 {
20607 ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
20608 ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
20609 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
20610 {
20611 ImGuiWindow* window = node->Windows[window_n];
20612 if (src_windows.contains(window->ID))
20613 continue;
20614
20615 // Docked windows gets redocked into the new node hierarchy.
20616 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
20617 dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
20618 }
20619 }
20620 for (const DockRemainingWindowTask& task : dock_remaining_windows)
20621 DockBuilderDockWindow(task.Window->Name, task.DockId);
20622 }
20623
20624 // FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
20625 void ImGui::DockBuilderFinish(ImGuiID root_id)
20626 {
20627 ImGuiContext& g = *GImGui;
20628 //DockContextRebuild(&g);
20629 DockContextBuildAddWindowsToNodes(&g, root_id);
20630 }
20631
20632 //-----------------------------------------------------------------------------
20633 // Docking: Begin/End Support Functions (called from Begin/End)
20634 //-----------------------------------------------------------------------------
20635 // - GetWindowAlwaysWantOwnTabBar()
20636 // - DockContextBindNodeToWindow()
20637 // - BeginDocked()
20638 // - BeginDockableDragDropSource()
20639 // - BeginDockableDragDropTarget()
20640 //-----------------------------------------------------------------------------
20641
20642 bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
20643 {
20644 ImGuiContext& g = *GImGui;
20645 if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
20646 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
20647 if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
20648 return true;
20649 return false;
20650 }
20651
20652 static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
20653 {
20654 ImGuiContext& g = *ctx;
20655 ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
20656 IM_ASSERT(window->DockNode == NULL);
20657
20658 // We should not be docking into a split node (SetWindowDock should avoid this)
20659 if (node && node->IsSplitNode())
20660 {
20661 DockContextProcessUndockWindow(ctx, window);
20662 return NULL;
20663 }
20664
20665 // Create node
20666 if (node == NULL)
20667 {
20668 node = DockContextAddNode(ctx, window->DockId);
20669 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
20670 node->LastFrameAlive = g.FrameCount;
20671 }
20672
20673 // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
20674 // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
20675 // 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.
20676 // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
20677 if (!node->IsVisible)
20678 {
20679 ImGuiDockNode* ancestor_node = node;
20680 while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
20681 ancestor_node = ancestor_node->ParentNode;
20682 IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
20683 DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
20684 DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
20685 }
20686
20687 // Add window to node
20688 bool node_was_visible = node->IsVisible;
20689 DockNodeAddWindow(node, window, true);
20690 node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
20691 IM_ASSERT(node == window->DockNode);
20692 return node;
20693 }
20694
20695 static void StoreDockStyleForWindow(ImGuiWindow* window)
20696 {
20697 ImGuiContext& g = *GImGui;
20698 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
20699 window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
20700 }
20701
20702 void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
20703 {
20704 ImGuiContext& g = *GImGui;
20705
20706 // Clear fields ahead so most early-out paths don't have to do it
20707 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
20708
20709 const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
20710 if (auto_dock_node)
20711 {
20712 if (window->DockId == 0)
20713 {
20714 IM_ASSERT(window->DockNode == NULL);
20715 window->DockId = DockContextGenNodeID(&g);
20716 }
20717 }
20718 else
20719 {
20720 // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
20721 bool want_undock = false;
20722 want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
20723 want_undock |= (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
20724 if (want_undock)
20725 {
20726 DockContextProcessUndockWindow(&g, window);
20727 return;
20728 }
20729 }
20730
20731 // Bind to our dock node
20732 ImGuiDockNode* node = window->DockNode;
20733 if (node != NULL)
20734 IM_ASSERT(window->DockId == node->ID);
20735 if (window->DockId != 0 && node == NULL)
20736 {
20737 node = DockContextBindNodeToWindow(&g, window);
20738 if (node == NULL)
20739 return;
20740 }
20741
20742 #if 0
20743 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
20744 if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
20745 {
20746 DockContextProcessUndockWindow(ctx, window);
20747 return;
20748 }
20749 #endif
20750
20751 // Undock if our dockspace node disappeared
20752 // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
20753 if (node->LastFrameAlive < g.FrameCount)
20754 {
20755 // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
20756 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
20757 if (root_node->LastFrameAlive < g.FrameCount)
20758 DockContextProcessUndockWindow(&g, window);
20759 else
20760 window->DockIsActive = true;
20761 return;
20762 }
20763
20764 // Store style overrides
20765 StoreDockStyleForWindow(window);
20766
20767 // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
20768 // and never create neither a host window neither a tab bar.
20769 // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
20770 if (node->HostWindow == NULL)
20771 {
20772 if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
20773 window->DockIsActive = true;
20774 if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
20775 DockNodeHideWindowDuringHostWindowCreation(window);
20776 return;
20777 }
20778
20779 // We can have zero-sized nodes (e.g. children of a small-size dockspace)
20780 IM_ASSERT(node->HostWindow);
20781 IM_ASSERT(node->IsLeafNode());
20782 IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
20783 node->State = ImGuiDockNodeState_HostWindowVisible;
20784
20785 // Undock if we are submitted earlier than the host window
20786 if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
20787 {
20788 DockContextProcessUndockWindow(&g, window);
20789 return;
20790 }
20791
20792 // Position/Size window
20793 SetNextWindowPos(node->Pos);
20794 SetNextWindowSize(node->Size);
20795 g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
20796 window->DockIsActive = true;
20797 window->DockNodeIsVisible = true;
20798 window->DockTabIsVisible = false;
20799 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
20800 return;
20801
20802 // When the window is selected we mark it as visible.
20803 if (node->VisibleWindow == window)
20804 window->DockTabIsVisible = true;
20805
20806 // Update window flag
20807 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
20808 window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
20809 window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
20810 if (node->IsHiddenTabBar() || node->IsNoTabBar())
20811 window->Flags |= ImGuiWindowFlags_NoTitleBar;
20812 else
20813 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!
20814
20815 // Save new dock order only if the window has been visible once already
20816 // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
20817 if (node->TabBar && window->WasActive)
20818 window->DockOrder = (short)DockNodeGetTabOrder(window);
20819
20820 if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
20821 *p_open = false;
20822
20823 // Update ChildId to allow returning from Child to Parent with Escape
20824 ImGuiWindow* parent_window = window->DockNode->HostWindow;
20825 window->ChildId = parent_window->GetID(window->Name);
20826 }
20827
20828 void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
20829 {
20830 ImGuiContext& g = *GImGui;
20831 IM_ASSERT(g.ActiveId == window->MoveId);
20832 IM_ASSERT(g.MovingWindow == window);
20833 IM_ASSERT(g.CurrentWindow == window);
20834
20835 // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
20836 if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
20837 {
20838 // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
20839 // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
20840 // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
20841 IM_ASSERT(g.NextWindowData.HasFlags == 0);
20842 if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
20843 SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
20844 return;
20845 }
20846
20847 g.LastItemData.ID = window->MoveId;
20848 window = window->RootWindowDockTree;
20849 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
20850 bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
20851 ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
20852 if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
20853 {
20854 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
20855 EndDragDropSource();
20856 StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
20857 }
20858 }
20859
20860 void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
20861 {
20862 ImGuiContext& g = *GImGui;
20863
20864 //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
20865 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
20866 if (!g.DragDropActive)
20867 return;
20868 //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20869 if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
20870 return;
20871
20872 // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
20873 // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
20874 const ImGuiPayload* payload = &g.DragDropPayload;
20875 if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
20876 {
20877 EndDragDropTarget();
20878 return;
20879 }
20880
20881 ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
20882 if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
20883 {
20884 // Select target node
20885 // (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)
20886 bool dock_into_floating_window = false;
20887 ImGuiDockNode* node = NULL;
20888 if (window->DockNodeAsHost)
20889 {
20890 // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
20891 node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
20892
20893 // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
20894 // In this case we need to fallback into any leaf mode, possibly the central node.
20895 // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
20896 if (node && node->IsDockSpace() && node->IsRootNode())
20897 node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
20898 }
20899 else
20900 {
20901 if (window->DockNode)
20902 node = window->DockNode;
20903 else
20904 dock_into_floating_window = true; // Dock into a regular window
20905 }
20906
20907 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()));
20908 const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
20909
20910 // Preview docking request and find out split direction/ratio
20911 //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.
20912 const bool do_preview = payload->IsPreview() || payload->IsDelivery();
20913 if (do_preview && (node != NULL || dock_into_floating_window))
20914 {
20915 // 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.
20916 ImGuiDockPreviewData split_inner;
20917 ImGuiDockPreviewData split_outer;
20918 ImGuiDockPreviewData* split_data = &split_inner;
20919 if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
20920 if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
20921 {
20922 DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
20923 if (split_outer.IsSplitDirExplicit)
20924 split_data = &split_outer;
20925 }
20926 if (!node || node->IsLeafNode())
20927 DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
20928 if (split_data == &split_outer)
20929 split_inner.IsDropAllowed = false;
20930
20931 // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
20932 DockNodePreviewDockRender(window, node, payload_window, &split_inner);
20933 DockNodePreviewDockRender(window, node, payload_window, &split_outer);
20934
20935 // Queue docking request
20936 if (split_data->IsDropAllowed && payload->IsDelivery())
20937 DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
20938 }
20939 }
20940 EndDragDropTarget();
20941 }
20942
20943 //-----------------------------------------------------------------------------
20944 // Docking: Settings
20945 //-----------------------------------------------------------------------------
20946 // - DockSettingsRenameNodeReferences()
20947 // - DockSettingsRemoveNodeReferences()
20948 // - DockSettingsFindNodeSettings()
20949 // - DockSettingsHandler_ApplyAll()
20950 // - DockSettingsHandler_ReadOpen()
20951 // - DockSettingsHandler_ReadLine()
20952 // - DockSettingsHandler_DockNodeToSettings()
20953 // - DockSettingsHandler_WriteAll()
20954 //-----------------------------------------------------------------------------
20955
20956 static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
20957 {
20958 ImGuiContext& g = *GImGui;
20959 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
20960 for (int window_n = 0; window_n < g.Windows.Size; window_n++)
20961 {
20962 ImGuiWindow* window = g.Windows[window_n];
20963 if (window->DockId == old_node_id && window->DockNode == NULL)
20964 window->DockId = new_node_id;
20965 }
20966 //// FIXME-OPT: We could remove this loop by storing the index in the map
20967 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20968 if (settings->DockId == old_node_id)
20969 settings->DockId = new_node_id;
20970 }
20971
20972 // Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
20973 static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
20974 {
20975 ImGuiContext& g = *GImGui;
20976 int found = 0;
20977 //// FIXME-OPT: We could remove this loop by storing the index in the map
20978 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20979 for (int node_n = 0; node_n < node_ids_count; node_n++)
20980 if (settings->DockId == node_ids[node_n])
20981 {
20982 settings->DockId = 0;
20983 settings->DockOrder = -1;
20984 if (++found < node_ids_count)
20985 break;
20986 return;
20987 }
20988 }
20989
20990 static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
20991 {
20992 // FIXME-OPT
20993 ImGuiDockContext* dc = &ctx->DockContext;
20994 for (int n = 0; n < dc->NodesSettings.Size; n++)
20995 if (dc->NodesSettings[n].ID == id)
20996 return &dc->NodesSettings[n];
20997 return NULL;
20998 }
20999
21000 // Clear settings data
21001 static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
21002 {
21003 ImGuiDockContext* dc = &ctx->DockContext;
21004 dc->NodesSettings.clear();
21005 DockContextClearNodes(ctx, 0, true);
21006 }
21007
21008 // Recreate nodes based on settings data
21009 static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
21010 {
21011 // Prune settings at boot time only
21012 ImGuiDockContext* dc = &ctx->DockContext;
21013 if (ctx->Windows.Size == 0)
21014 DockContextPruneUnusedSettingsNodes(ctx);
21015 DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
21016 DockContextBuildAddWindowsToNodes(ctx, 0);
21017 }
21018
21019 static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
21020 {
21021 if (strcmp(name, "Data") != 0)
21022 return NULL;
21023 return (void*)1;
21024 }
21025
21026 static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
21027 {
21028 char c = 0;
21029 int x = 0, y = 0;
21030 int r = 0;
21031
21032 // Parsing, e.g.
21033 // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
21034 // " DockNode ID=0x00000002 Parent=0x00000001 "
21035 // Important: this code expect currently fields in a fixed order.
21036 ImGuiDockNodeSettings node;
21037 line = ImStrSkipBlank(line);
21038 if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
21039 else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
21040 else return;
21041 if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
21042 if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
21043 if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
21044 if (node.ParentNodeId == 0)
21045 {
21046 if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
21047 if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
21048 }
21049 else
21050 {
21051 if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
21052 }
21053 if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
21054 if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
21055 if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
21056 if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
21057 if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
21058 if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
21059 if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
21060 if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
21061 if (node.ParentNodeId != 0)
21062 if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
21063 node.Depth = parent_settings->Depth + 1;
21064 ctx->DockContext.NodesSettings.push_back(node);
21065 }
21066
21067 static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
21068 {
21069 ImGuiDockNodeSettings node_settings;
21070 IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
21071 node_settings.ID = node->ID;
21072 node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
21073 node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
21074 node_settings.SelectedTabId = node->SelectedTabId;
21075 node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
21076 node_settings.Depth = (char)depth;
21077 node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
21078 node_settings.Pos = ImVec2ih(node->Pos);
21079 node_settings.Size = ImVec2ih(node->Size);
21080 node_settings.SizeRef = ImVec2ih(node->SizeRef);
21081 dc->NodesSettings.push_back(node_settings);
21082 if (node->ChildNodes[0])
21083 DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
21084 if (node->ChildNodes[1])
21085 DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
21086 }
21087
21088 static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
21089 {
21090 ImGuiContext& g = *ctx;
21091 ImGuiDockContext* dc = &ctx->DockContext;
21092 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
21093 return;
21094
21095 // Gather settings data
21096 // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
21097 dc->NodesSettings.resize(0);
21098 dc->NodesSettings.reserve(dc->Nodes.Data.Size);
21099 for (int n = 0; n < dc->Nodes.Data.Size; n++)
21100 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
21101 if (node->IsRootNode())
21102 DockSettingsHandler_DockNodeToSettings(dc, node, 0);
21103
21104 int max_depth = 0;
21105 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
21106 max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
21107
21108 // Write to text buffer
21109 buf->appendf("[%s][Data]\n", handler->TypeName);
21110 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
21111 {
21112 const int line_start_pos = buf->size(); (void)line_start_pos;
21113 const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
21114 buf->appendf("%*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
21115 buf->appendf(" ID=0x%08X", node_settings->ID);
21116 if (node_settings->ParentNodeId)
21117 {
21118 buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
21119 }
21120 else
21121 {
21122 if (node_settings->ParentWindowId)
21123 buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
21124 buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
21125 }
21126 if (node_settings->SplitAxis != ImGuiAxis_None)
21127 buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
21128 if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
21129 buf->appendf(" NoResize=1");
21130 if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
21131 buf->appendf(" CentralNode=1");
21132 if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
21133 buf->appendf(" NoTabBar=1");
21134 if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
21135 buf->appendf(" HiddenTabBar=1");
21136 if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
21137 buf->appendf(" NoWindowMenuButton=1");
21138 if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
21139 buf->appendf(" NoCloseButton=1");
21140 if (node_settings->SelectedTabId)
21141 buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
21142
21143 // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
21144 if (g.IO.ConfigDebugIniSettings)
21145 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
21146 {
21147 buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
21148 if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
21149 buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
21150 // Iterate settings so we can give info about windows that didn't exist during the session.
21151 int contains_window = 0;
21152 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
21153 if (settings->DockId == node_settings->ID)
21154 {
21155 if (contains_window++ == 0)
21156 buf->appendf(" ; contains ");
21157 buf->appendf("'%s' ", settings->GetName());
21158 }
21159 }
21160
21161 buf->appendf("\n");
21162 }
21163 buf->appendf("\n");
21164 }
21165
21166
21167 //-----------------------------------------------------------------------------
21168 // [SECTION] PLATFORM DEPENDENT HELPERS
21169 //-----------------------------------------------------------------------------
21170 // - Default clipboard handlers
21171 // - Default shell function handlers
21172 // - Default IME handlers
21173 //-----------------------------------------------------------------------------
21174
21175 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
21176
21177 #ifdef _MSC_VER
21178 #pragma comment(lib, "user32")
21179 #pragma comment(lib, "kernel32")
21180 #endif
21181
21182 // Win32 clipboard implementation
21183 // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
21184 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21185 {
21186 ImGuiContext& g = *ctx;
21187 g.ClipboardHandlerData.clear();
21188 if (!::OpenClipboard(NULL))
21189 return NULL;
21190 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
21191 if (wbuf_handle == NULL)
21192 {
21193 ::CloseClipboard();
21194 return NULL;
21195 }
21196 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
21197 {
21198 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
21199 g.ClipboardHandlerData.resize(buf_len);
21200 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
21201 }
21202 ::GlobalUnlock(wbuf_handle);
21203 ::CloseClipboard();
21204 return g.ClipboardHandlerData.Data;
21205 }
21206
21207 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
21208 {
21209 if (!::OpenClipboard(NULL))
21210 return;
21211 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
21212 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
21213 if (wbuf_handle == NULL)
21214 {
21215 ::CloseClipboard();
21216 return;
21217 }
21218 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
21219 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
21220 ::GlobalUnlock(wbuf_handle);
21221 ::EmptyClipboard();
21222 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
21223 ::GlobalFree(wbuf_handle);
21224 ::CloseClipboard();
21225 }
21226
21227 #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
21228
21229 #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
21230 static PasteboardRef main_clipboard = 0;
21231
21232 // OSX clipboard implementation
21233 // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
21234 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
21235 {
21236 if (!main_clipboard)
21237 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
21238 PasteboardClear(main_clipboard);
21239 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text));
21240 if (cf_data)
21241 {
21242 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
21243 CFRelease(cf_data);
21244 }
21245 }
21246
21247 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21248 {
21249 ImGuiContext& g = *ctx;
21250 if (!main_clipboard)
21251 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
21252 PasteboardSynchronize(main_clipboard);
21253
21254 ItemCount item_count = 0;
21255 PasteboardGetItemCount(main_clipboard, &item_count);
21256 for (ItemCount i = 0; i < item_count; i++)
21257 {
21258 PasteboardItemID item_id = 0;
21259 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
21260 CFArrayRef flavor_type_array = 0;
21261 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
21262 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
21263 {
21264 CFDataRef cf_data;
21265 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
21266 {
21267 g.ClipboardHandlerData.clear();
21268 int length = (int)CFDataGetLength(cf_data);
21269 g.ClipboardHandlerData.resize(length + 1);
21270 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
21271 g.ClipboardHandlerData[length] = 0;
21272 CFRelease(cf_data);
21273 return g.ClipboardHandlerData.Data;
21274 }
21275 }
21276 }
21277 return NULL;
21278 }
21279
21280 #else
21281
21282 // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
21283 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21284 {
21285 ImGuiContext& g = *ctx;
21286 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
21287 }
21288
21289 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text)
21290 {
21291 ImGuiContext& g = *ctx;
21292 g.ClipboardHandlerData.clear();
21293 const char* text_end = text + ImStrlen(text);
21294 g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
21295 memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
21296 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
21297 }
21298
21299 #endif // Default clipboard handlers
21300
21301 //-----------------------------------------------------------------------------
21302
21303 #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21304 #if defined(__APPLE__) && TARGET_OS_IPHONE
21305 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21306 #endif
21307 #if defined(__3DS__)
21308 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21309 #endif
21310 #if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
21311 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21312 #endif
21313 #endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21314
21315 #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21316 #ifdef _WIN32
21317 #include <shellapi.h> // ShellExecuteA()
21318 #ifdef _MSC_VER
21319 #pragma comment(lib, "shell32")
21320 #endif
21321 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
21322 {
21323 const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
21324 ImVector<wchar_t> path_wbuf;
21325 path_wbuf.resize(path_wsize);
21326 ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize);
21327 return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32;
21328 }
21329 #else
21330 #include <sys/wait.h>
21331 #include <unistd.h>
21332 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
21333 {
21334 #if defined(__APPLE__)
21335 const char* args[] { "open", "--", path, NULL };
21336 #else
21337 const char* args[] { "xdg-open", path, NULL };
21338 #endif
21339 pid_t pid = fork();
21340 if (pid < 0)
21341 return false;
21342 if (!pid)
21343 {
21344 execvp(args[0], const_cast<char **>(args));
21345 exit(-1);
21346 }
21347 else
21348 {
21349 int status;
21350 waitpid(pid, &status, 0);
21351 return WEXITSTATUS(status) == 0;
21352 }
21353 }
21354 #endif
21355 #else
21356 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
21357 #endif // Default shell handlers
21358
21359 //-----------------------------------------------------------------------------
21360
21361 // Win32 API IME support (for Asian languages, etc.)
21362 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
21363
21364 #include <imm.h>
21365 #ifdef _MSC_VER
21366 #pragma comment(lib, "imm32")
21367 #endif
21368
21369 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
21370 {
21371 // Notify OS Input Method Editor of text input position
21372 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
21373 if (hwnd == 0)
21374 return;
21375
21376 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
21377 if (HIMC himc = ::ImmGetContext(hwnd))
21378 {
21379 COMPOSITIONFORM composition_form = {};
21380 composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
21381 composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
21382 composition_form.dwStyle = CFS_FORCE_POSITION;
21383 ::ImmSetCompositionWindow(himc, &composition_form);
21384 CANDIDATEFORM candidate_form = {};
21385 candidate_form.dwStyle = CFS_CANDIDATEPOS;
21386 candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
21387 candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
21388 ::ImmSetCandidateWindow(himc, &candidate_form);
21389 ::ImmReleaseContext(hwnd, himc);
21390 }
21391 }
21392
21393 #else
21394
21395 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
21396
21397 #endif // Default IME handlers
21398
21399 //-----------------------------------------------------------------------------
21400 // [SECTION] METRICS/DEBUGGER WINDOW
21401 //-----------------------------------------------------------------------------
21402 // - MetricsHelpMarker() [Internal]
21403 // - DebugRenderViewportThumbnail() [Internal]
21404 // - RenderViewportsThumbnails() [Internal]
21405 // - DebugRenderKeyboardPreview() [Internal]
21406 // - DebugTextEncoding()
21407 // - DebugFlashStyleColorStop() [Internal]
21408 // - DebugFlashStyleColor()
21409 // - UpdateDebugToolFlashStyleColor() [Internal]
21410 // - ShowFontAtlas() [Internal but called by Demo!]
21411 // - DebugNodeTexture() [Internal]
21412 // - ShowMetricsWindow()
21413 // - DebugNodeColumns() [Internal]
21414 // - DebugNodeDockNode() [Internal]
21415 // - DebugNodeDrawList() [Internal]
21416 // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
21417 // - DebugNodeFont() [Internal]
21418 // - DebugNodeFontGlyph() [Internal]
21419 // - DebugNodeStorage() [Internal]
21420 // - DebugNodeTabBar() [Internal]
21421 // - DebugNodeViewport() [Internal]
21422 // - DebugNodeWindow() [Internal]
21423 // - DebugNodeWindowSettings() [Internal]
21424 // - DebugNodeWindowsList() [Internal]
21425 // - DebugNodeWindowsListByBeginStackParent() [Internal]
21426 // - ShowFontSelector()
21427 //-----------------------------------------------------------------------------
21428
21429 #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
21430 // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
21431 static void MetricsHelpMarker(const char* desc)
21432 {
21433 ImGui::TextDisabled("(?)");
21434 if (ImGui::BeginItemTooltip())
21435 {
21436 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
21437 ImGui::TextUnformatted(desc);
21438 ImGui::PopTextWrapPos();
21439 ImGui::EndTooltip();
21440 }
21441 }
21442 #endif
21443
21444 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21445
21446 void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
21447 {
21448 ImGuiContext& g = *GImGui;
21449 ImGuiWindow* window = g.CurrentWindow;
21450
21451 ImVec2 scale = bb.GetSize() / viewport->Size;
21452 ImVec2 off = bb.Min - viewport->Pos * scale;
21453 float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
21454 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
21455 for (ImGuiWindow* thumb_window : g.Windows)
21456 {
21457 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
21458 continue;
21459 if (thumb_window->Viewport != viewport)
21460 continue;
21461
21462 ImRect thumb_r = thumb_window->Rect();
21463 ImRect title_r = thumb_window->TitleBarRect();
21464 thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale));
21465 title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
21466 thumb_r.ClipWithFull(bb);
21467 title_r.ClipWithFull(bb);
21468 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
21469 window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
21470 window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
21471 window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
21472 window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
21473 }
21474 draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
21475 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
21476 window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
21477 }
21478
21479 static void RenderViewportsThumbnails()
21480 {
21481 ImGuiContext& g = *GImGui;
21482 ImGuiWindow* window = g.CurrentWindow;
21483
21484 // Draw monitor and calculate their boundaries
21485 float SCALE = 1.0f / 8.0f;
21486 ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21487 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
21488 bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
21489 ImVec2 p = window->DC.CursorPos;
21490 ImVec2 off = p - bb_full.Min * SCALE;
21491 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
21492 {
21493 ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
21494 window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
21495 window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
21496 }
21497
21498 // Draw viewports
21499 for (ImGuiViewportP* viewport : g.Viewports)
21500 {
21501 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
21502 ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
21503 }
21504 ImGui::Dummy(bb_full.GetSize() * SCALE);
21505 }
21506
21507 static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
21508 {
21509 const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
21510 const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
21511 return b->LastFocusedStampCount - a->LastFocusedStampCount;
21512 }
21513
21514 // Draw an arbitrary US keyboard layout to visualize translated keys
21515 void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
21516 {
21517 const float scale = ImGui::GetFontSize() / 13.0f;
21518 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
21519 const float key_rounding = 3.0f * scale;
21520 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
21521 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
21522 const float key_face_rounding = 2.0f * scale;
21523 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
21524 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
21525 const float key_row_offset = 9.0f * scale;
21526
21527 ImVec2 board_min = GetCursorScreenPos();
21528 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);
21529 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
21530
21531 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
21532 const KeyLayoutData keys_to_display[] =
21533 {
21534 { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
21535 { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
21536 { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
21537 };
21538
21539 // Elements rendered manually via ImDrawList API are not clipped automatically.
21540 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
21541 Dummy(board_max - board_min);
21542 if (!IsItemVisible())
21543 return;
21544 draw_list->PushClipRect(board_min, board_max, true);
21545 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
21546 {
21547 const KeyLayoutData* key_data = &keys_to_display[n];
21548 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);
21549 ImVec2 key_max = key_min + key_size;
21550 draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
21551 draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
21552 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
21553 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
21554 draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
21555 draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
21556 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
21557 draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
21558 if (IsKeyDown(key_data->Key))
21559 draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
21560 }
21561 draw_list->PopClipRect();
21562 }
21563
21564 // Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
21565 void ImGui::DebugTextEncoding(const char* str)
21566 {
21567 Text("Text: \"%s\"", str);
21568 if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
21569 return;
21570 TableSetupColumn("Offset");
21571 TableSetupColumn("UTF-8");
21572 TableSetupColumn("Glyph");
21573 TableSetupColumn("Codepoint");
21574 TableHeadersRow();
21575 for (const char* p = str; *p != 0; )
21576 {
21577 unsigned int c;
21578 const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
21579 TableNextColumn();
21580 Text("%d", (int)(p - str));
21581 TableNextColumn();
21582 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
21583 {
21584 if (byte_index > 0)
21585 SameLine();
21586 Text("0x%02X", (int)(unsigned char)p[byte_index]);
21587 }
21588 TableNextColumn();
21589 TextUnformatted(p, p + c_utf8_len);
21590 if (!GetFont()->IsGlyphInFont((ImWchar)c))
21591 {
21592 SameLine();
21593 TextUnformatted("[missing]");
21594 }
21595 TableNextColumn();
21596 Text("U+%04X", (int)c);
21597 p += c_utf8_len;
21598 }
21599 EndTable();
21600 }
21601
21602 static void DebugFlashStyleColorStop()
21603 {
21604 ImGuiContext& g = *GImGui;
21605 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
21606 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
21607 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
21608 }
21609
21610 // Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
21611 void ImGui::DebugFlashStyleColor(ImGuiCol idx)
21612 {
21613 ImGuiContext& g = *GImGui;
21614 DebugFlashStyleColorStop();
21615 g.DebugFlashStyleColorTime = 0.5f;
21616 g.DebugFlashStyleColorIdx = idx;
21617 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
21618 }
21619
21620 void ImGui::UpdateDebugToolFlashStyleColor()
21621 {
21622 ImGuiContext& g = *GImGui;
21623 if (g.DebugFlashStyleColorTime <= 0.0f)
21624 return;
21625 ColorConvertHSVtoRGB(ImCos(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
21626 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
21627 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
21628 DebugFlashStyleColorStop();
21629 }
21630
21631 static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21632 {
21633 union { void* ptr; int integer; } tex_id_opaque;
21634 memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21635 if (sizeof(tex_id) >= sizeof(void*))
21636 ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21637 else
21638 ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21639 return buf;
21640 }
21641
21642 static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref)
21643 {
21644 char* buf_end = buf + buf_size;
21645 if (tex_ref._TexData != NULL)
21646 buf += ImFormatString(buf, buf_end - buf, "#%03d: ", tex_ref._TexData->UniqueID);
21647 return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), tex_ref.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID()
21648 }
21649
21650 #ifdef IMGUI_ENABLE_FREETYPE
21651 namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); }
21652 #endif
21653
21654 // [DEBUG] List fonts in a font atlas and display its texture
21655 void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
21656 {
21657 ImGuiContext& g = *GImGui;
21658 ImGuiIO& io = g.IO;
21659 ImGuiStyle& style = g.Style;
21660
21661 BeginDisabled();
21662 CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures);
21663 EndDisabled();
21664 ShowFontSelector("Font");
21665 //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0);
21666 if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f"))
21667 style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work.
21668 SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize());
21669 SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.");
21670 DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f);
21671 //BeginDisabled(io.ConfigDpiScaleFonts);
21672 DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f);
21673 //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.");
21674 //EndDisabled();
21675 if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
21676 {
21677 BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!");
21678 BulletText("For instructions, see:");
21679 SameLine();
21680 TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md");
21681 }
21682 BulletText("Load a nice font for better results!");
21683 BulletText("Please submit feedback:");
21684 SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465");
21685 BulletText("Read FAQ for more details:");
21686 SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/");
21687 //EndDisabled();
21688
21689 SeparatorText("Font List");
21690
21691 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21692 Checkbox("Show font preview", &cfg->ShowFontPreview);
21693
21694 // Font loaders
21695 if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL"))
21696 {
21697 const ImFontLoader* loader_current = atlas->FontLoader;
21698 BeginDisabled(!atlas->RendererHasTextures);
21699 #ifdef IMGUI_ENABLE_STB_TRUETYPE
21700 const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype();
21701 if (RadioButton("stb_truetype", loader_current == loader_stbtruetype))
21702 atlas->SetFontLoader(loader_stbtruetype);
21703 #else
21704 BeginDisabled();
21705 RadioButton("stb_truetype", false);
21706 SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE");
21707 EndDisabled();
21708 #endif
21709 SameLine();
21710 #ifdef IMGUI_ENABLE_FREETYPE
21711 const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader();
21712 if (RadioButton("FreeType", loader_current == loader_freetype))
21713 atlas->SetFontLoader(loader_freetype);
21714 if (loader_current == loader_freetype)
21715 {
21716 unsigned int loader_flags = atlas->FontLoaderFlags;
21717 Text("Shared FreeType Loader Flags: 0x%08X", loader_flags);
21718 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
21719 {
21720 for (ImFont* font : atlas->Fonts)
21721 ImFontAtlasFontDestroyOutput(atlas, font);
21722 atlas->FontLoaderFlags = loader_flags;
21723 for (ImFont* font : atlas->Fonts)
21724 ImFontAtlasFontInitOutput(atlas, font);
21725 }
21726 }
21727 #else
21728 BeginDisabled();
21729 RadioButton("FreeType", false);
21730 SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp.");
21731 EndDisabled();
21732 #endif
21733 EndDisabled();
21734 TreePop();
21735 }
21736
21737 // Font list
21738 for (ImFont* font : atlas->Fonts)
21739 {
21740 PushID(font);
21741 DebugNodeFont(font);
21742 PopID();
21743 }
21744
21745 SeparatorText("Font Atlas");
21746 if (Button("Compact"))
21747 atlas->CompactCache();
21748 SameLine();
21749 if (Button("Grow"))
21750 ImFontAtlasTextureGrow(atlas);
21751 SameLine();
21752 if (Button("Clear All"))
21753 ImFontAtlasBuildClear(atlas);
21754 SetItemTooltip("Destroy cache and custom rectangles.");
21755
21756 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
21757 {
21758 ImTextureData* tex = atlas->TexList[tex_n];
21759 if (tex_n > 0)
21760 SameLine();
21761 Text("Tex: %dx%d", tex->Width, tex->Height);
21762 }
21763 const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface);
21764 const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface);
21765 Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt);
21766 Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt);
21767
21768 ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid;
21769 if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles
21770 {
21771 PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f);
21772 if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12)))
21773 {
21774 for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex)
21775 if (entry.IsUsed)
21776 {
21777 ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation);
21778 ImFontAtlasRect r = {};
21779 atlas->GetCustomRect(id, &r);
21780 const char* buf;
21781 ImFormatStringToTempBuffer(&buf, NULL, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y);
21782 TableNextColumn();
21783 Selectable(buf);
21784 if (IsItemHovered())
21785 highlight_r_id = id;
21786 TableNextColumn();
21787 Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
21788 }
21789 EndTable();
21790 }
21791 PopStyleVar();
21792 TreePop();
21793 }
21794
21795 // Texture list
21796 // (ensure the last texture always use the same ID, so we can keep it open neatly)
21797 ImFontAtlasRect highlight_r;
21798 if (highlight_r_id != ImFontAtlasRectId_Invalid)
21799 atlas->GetCustomRect(highlight_r_id, &highlight_r);
21800 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
21801 {
21802 if (tex_n == atlas->TexList.Size - 1)
21803 SetNextItemOpen(true, ImGuiCond_Once);
21804 DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL);
21805 }
21806 }
21807
21808 void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect)
21809 {
21810 ImGuiContext& g = *GImGui;
21811 PushID(int_id);
21812 if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height))
21813 {
21814 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21815 Checkbox("Show used rect", &cfg->ShowTextureUsedRect);
21816 PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize));
21817 ImVec2 p = GetCursorScreenPos();
21818 if (tex->WantDestroyNextFrame)
21819 Dummy(ImVec2((float)tex->Width, (float)tex->Height));
21820 else
21821 ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f));
21822 if (cfg->ShowTextureUsedRect)
21823 GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255));
21824 if (highlight_rect != NULL)
21825 {
21826 ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height);
21827 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);
21828 RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f);
21829 GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255));
21830 }
21831 PopStyleVar();
21832
21833 char texid_desc[30];
21834 Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors);
21835 Text("TexID = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->GetTexRef()), tex->BackendUserData);
21836 TreePop();
21837 }
21838 PopID();
21839 }
21840
21841 void ImGui::ShowMetricsWindow(bool* p_open)
21842 {
21843 ImGuiContext& g = *GImGui;
21844 ImGuiIO& io = g.IO;
21845 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21846 if (cfg->ShowDebugLog)
21847 ShowDebugLogWindow(&cfg->ShowDebugLog);
21848 if (cfg->ShowIDStackTool)
21849 ShowIDStackToolWindow(&cfg->ShowIDStackTool);
21850
21851 if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
21852 {
21853 End();
21854 return;
21855 }
21856
21857 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
21858 DebugBreakClearData();
21859
21860 // Basic info
21861 Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
21862 if (g.ContextName[0] != 0)
21863 {
21864 SameLine();
21865 Text("(Context Name: \"%s\")", g.ContextName);
21866 }
21867 Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
21868 Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
21869 Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
21870 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
21871
21872 Separator();
21873
21874 // Debugging enums
21875 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
21876 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
21877 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
21878 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
21879 if (cfg->ShowWindowsRectsType < 0)
21880 cfg->ShowWindowsRectsType = WRT_WorkRect;
21881 if (cfg->ShowTablesRectsType < 0)
21882 cfg->ShowTablesRectsType = TRT_WorkRect;
21883
21884 struct Funcs
21885 {
21886 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
21887 {
21888 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
21889 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
21890 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
21891 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
21892 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
21893 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
21894 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
21895 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); }
21896 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); }
21897 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
21898 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
21899 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); }
21900 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); }
21901 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); }
21902 IM_ASSERT(0);
21903 return ImRect();
21904 }
21905
21906 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
21907 {
21908 if (rect_type == WRT_OuterRect) { return window->Rect(); }
21909 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
21910 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
21911 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
21912 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
21913 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
21914 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
21915 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
21916 IM_ASSERT(0);
21917 return ImRect();
21918 }
21919 };
21920
21921 #ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
21922 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");
21923 #endif
21924
21925 // Tools
21926 if (TreeNode("Tools"))
21927 {
21928 // Debug Break features
21929 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
21930 SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
21931 SameLine();
21932 MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
21933 if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
21934 DebugStartItemPicker();
21935 Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
21936
21937 SeparatorText("Visualize");
21938
21939 Checkbox("Show Debug Log", &cfg->ShowDebugLog);
21940 SameLine();
21941 MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
21942
21943 Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
21944 SameLine();
21945 MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
21946
21947 Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
21948 Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
21949 SameLine();
21950 SetNextItemWidth(GetFontSize() * 12);
21951 cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
21952 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
21953 {
21954 BulletText("'%s':", g.NavWindow->Name);
21955 Indent();
21956 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
21957 {
21958 ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
21959 Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
21960 }
21961 Unindent();
21962 }
21963
21964 Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
21965 SameLine();
21966 SetNextItemWidth(GetFontSize() * 12);
21967 cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
21968 if (cfg->ShowTablesRects && g.NavWindow != NULL)
21969 {
21970 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
21971 {
21972 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
21973 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
21974 continue;
21975
21976 BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
21977 if (IsItemHovered())
21978 GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
21979 Indent();
21980 char buf[128];
21981 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
21982 {
21983 if (rect_n >= TRT_ColumnsRect)
21984 {
21985 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
21986 continue;
21987 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
21988 {
21989 ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
21990 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
21991 Selectable(buf);
21992 if (IsItemHovered())
21993 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
21994 }
21995 }
21996 else
21997 {
21998 ImRect r = Funcs::GetTableRect(table, rect_n, -1);
21999 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
22000 Selectable(buf);
22001 if (IsItemHovered())
22002 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
22003 }
22004 }
22005 Unindent();
22006 }
22007 }
22008 Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
22009
22010 SeparatorText("Validate");
22011
22012 Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
22013 SameLine();
22014 MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
22015
22016 Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
22017 SameLine();
22018 MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
22019 if (cfg->ShowTextEncodingViewer)
22020 {
22021 static char buf[64] = "";
22022 SetNextItemWidth(-FLT_MIN);
22023 InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
22024 if (buf[0] != 0)
22025 DebugTextEncoding(buf);
22026 }
22027
22028 TreePop();
22029 }
22030
22031 // Windows
22032 if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
22033 {
22034 //SetNextItemOpen(true, ImGuiCond_Once);
22035 DebugNodeWindowsList(&g.Windows, "By display order");
22036 DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
22037 if (TreeNode("By submission order (begin stack)"))
22038 {
22039 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
22040 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
22041 temp_buffer.resize(0);
22042 for (ImGuiWindow* window : g.Windows)
22043 if (window->LastFrameActive + 1 >= g.FrameCount)
22044 temp_buffer.push_back(window);
22045 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); } };
22046 ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
22047 DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
22048 TreePop();
22049 }
22050
22051 TreePop();
22052 }
22053
22054 // DrawLists
22055 int drawlist_count = 0;
22056 for (ImGuiViewportP* viewport : g.Viewports)
22057 drawlist_count += viewport->DrawDataP.CmdLists.Size;
22058 if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
22059 {
22060 Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
22061 Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
22062 for (ImGuiViewportP* viewport : g.Viewports)
22063 {
22064 bool viewport_has_drawlist = false;
22065 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
22066 {
22067 if (!viewport_has_drawlist)
22068 Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
22069 viewport_has_drawlist = true;
22070 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
22071 }
22072 }
22073 TreePop();
22074 }
22075
22076 // Viewports
22077 if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
22078 {
22079 cfg->HighlightMonitorIdx = -1;
22080 bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
22081 SameLine();
22082 MetricsHelpMarker("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.");
22083 if (open)
22084 {
22085 for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
22086 {
22087 DebugNodePlatformMonitor(&g.PlatformIO.Monitors[i], "Monitor", i);
22088 if (IsItemHovered())
22089 cfg->HighlightMonitorIdx = i;
22090 }
22091 DebugNodePlatformMonitor(&g.FallbackMonitor, "Fallback", 0);
22092 TreePop();
22093 }
22094
22095 SetNextItemOpen(true, ImGuiCond_Once);
22096 if (TreeNode("Windows Minimap"))
22097 {
22098 RenderViewportsThumbnails();
22099 TreePop();
22100 }
22101 cfg->HighlightViewportID = 0;
22102
22103 BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
22104 if (TreeNode("Inferred Z order (front-to-back)"))
22105 {
22106 static ImVector<ImGuiViewportP*> viewports;
22107 viewports.resize(g.Viewports.Size);
22108 memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
22109 if (viewports.Size > 1)
22110 ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
22111 for (ImGuiViewportP* viewport : viewports)
22112 {
22113 BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
22114 viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
22115 (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
22116 viewport->Window ? viewport->Window->Name : "N/A");
22117 if (IsItemHovered())
22118 cfg->HighlightViewportID = viewport->ID;
22119 }
22120 TreePop();
22121 }
22122
22123 for (ImGuiViewportP* viewport : g.Viewports)
22124 DebugNodeViewport(viewport);
22125 TreePop();
22126 }
22127
22128 // Details for Fonts
22129 for (ImFontAtlas* atlas : g.FontAtlases)
22130 if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size))
22131 {
22132 ShowFontAtlas(atlas);
22133 TreePop();
22134 }
22135
22136 // Details for Popups
22137 if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
22138 {
22139 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
22140 {
22141 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
22142 ImGuiWindow* window = popup_data.Window;
22143 BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
22144 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
22145 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
22146 }
22147 TreePop();
22148 }
22149
22150 // Details for TabBars
22151 if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
22152 {
22153 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
22154 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
22155 {
22156 PushID(tab_bar);
22157 DebugNodeTabBar(tab_bar, "TabBar");
22158 PopID();
22159 }
22160 TreePop();
22161 }
22162
22163 // Details for Tables
22164 if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
22165 {
22166 for (int n = 0; n < g.Tables.GetMapSize(); n++)
22167 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
22168 DebugNodeTable(table);
22169 TreePop();
22170 }
22171
22172 // Details for InputText
22173 if (TreeNode("InputText"))
22174 {
22175 DebugNodeInputTextState(&g.InputTextState);
22176 TreePop();
22177 }
22178
22179 // Details for TypingSelect
22180 if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
22181 {
22182 DebugNodeTypingSelectState(&g.TypingSelectState);
22183 TreePop();
22184 }
22185
22186 // Details for MultiSelect
22187 if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
22188 {
22189 ImGuiBoxSelectState* bs = &g.BoxSelectState;
22190 BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
22191 for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
22192 if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
22193 DebugNodeMultiSelectState(state);
22194 TreePop();
22195 }
22196
22197 // Details for Docking
22198 #ifdef IMGUI_HAS_DOCK
22199 if (TreeNode("Docking"))
22200 {
22201 static bool root_nodes_only = true;
22202 ImGuiDockContext* dc = &g.DockContext;
22203 Checkbox("List root nodes", &root_nodes_only);
22204 Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
22205 if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
22206 SameLine();
22207 if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
22208 for (int n = 0; n < dc->Nodes.Data.Size; n++)
22209 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
22210 if (!root_nodes_only || node->IsRootNode())
22211 DebugNodeDockNode(node, "Node");
22212 TreePop();
22213 }
22214 #endif // #ifdef IMGUI_HAS_DOCK
22215
22216 // Settings
22217 if (TreeNode("Settings"))
22218 {
22219 if (SmallButton("Clear"))
22220 ClearIniSettings();
22221 SameLine();
22222 if (SmallButton("Save to memory"))
22223 SaveIniSettingsToMemory();
22224 SameLine();
22225 if (SmallButton("Save to disk"))
22226 SaveIniSettingsToDisk(g.IO.IniFilename);
22227 SameLine();
22228 if (g.IO.IniFilename)
22229 Text("\"%s\"", g.IO.IniFilename);
22230 else
22231 TextUnformatted("<NULL>");
22232 Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
22233 Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
22234 if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
22235 {
22236 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
22237 BulletText("\"%s\"", handler.TypeName);
22238 TreePop();
22239 }
22240 if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
22241 {
22242 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
22243 DebugNodeWindowSettings(settings);
22244 TreePop();
22245 }
22246
22247 if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
22248 {
22249 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
22250 DebugNodeTableSettings(settings);
22251 TreePop();
22252 }
22253
22254 #ifdef IMGUI_HAS_DOCK
22255 if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
22256 {
22257 ImGuiDockContext* dc = &g.DockContext;
22258 Text("In SettingsWindows:");
22259 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
22260 if (settings->DockId != 0)
22261 BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
22262 Text("In SettingsNodes:");
22263 for (int n = 0; n < dc->NodesSettings.Size; n++)
22264 {
22265 ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
22266 const char* selected_tab_name = NULL;
22267 if (settings->SelectedTabId)
22268 {
22269 if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
22270 selected_tab_name = window->Name;
22271 else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
22272 selected_tab_name = window_settings->GetName();
22273 }
22274 BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
22275 }
22276 TreePop();
22277 }
22278 #endif // #ifdef IMGUI_HAS_DOCK
22279
22280 if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
22281 {
22282 InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
22283 TreePop();
22284 }
22285 TreePop();
22286 }
22287
22288 // Settings
22289 if (TreeNode("Memory allocations"))
22290 {
22291 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
22292 Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
22293 if (SmallButton("GC now")) { g.GcCompactAll = true; }
22294 Text("Recent frames with allocations:");
22295 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
22296 for (int n = buf_size - 1; n >= 0; n--)
22297 {
22298 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
22299 BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
22300 if (n == 0)
22301 {
22302 SameLine();
22303 Text("<- %d frames ago", g.FrameCount - entry->FrameCount);
22304 }
22305 }
22306 TreePop();
22307 }
22308
22309 if (TreeNode("Inputs"))
22310 {
22311 Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
22312 {
22313 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
22314 Indent();
22315 Text("Keys down:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
22316 Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
22317 Text("Keys released:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
22318 Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
22319 Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
22320 DebugRenderKeyboardPreview(GetWindowDrawList());
22321 Unindent();
22322 }
22323
22324 Text("MOUSE STATE");
22325 {
22326 Indent();
22327 if (IsMousePosValid())
22328 Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
22329 else
22330 Text("Mouse pos: <INVALID>");
22331 Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
22332 int count = IM_ARRAYSIZE(io.MouseDown);
22333 Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
22334 Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
22335 Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
22336 Text("Mouse wheel: %.1f", io.MouseWheel);
22337 Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
22338 Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
22339 Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
22340 Unindent();
22341 }
22342
22343 Text("MOUSE WHEELING");
22344 {
22345 Indent();
22346 Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
22347 Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
22348 Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
22349 Unindent();
22350 }
22351
22352 Text("KEY OWNERS");
22353 {
22354 Indent();
22355 if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
22356 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
22357 {
22358 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
22359 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
22360 continue;
22361 Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
22362 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
22363 DebugLocateItemOnHover(owner_data->OwnerCurr);
22364 }
22365 EndChild();
22366 Unindent();
22367 }
22368 Text("SHORTCUT ROUTING");
22369 SameLine();
22370 MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
22371 {
22372 Indent();
22373 if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
22374 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
22375 {
22376 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
22377 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
22378 {
22379 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
22380 ImGuiKeyChord key_chord = key | routing_data->Mods;
22381 Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
22382 DebugLocateItemOnHover(routing_data->RoutingCurr);
22383 if (g.IO.ConfigDebugIsDebuggerPresent)
22384 {
22385 SameLine();
22386 if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
22387 g.DebugBreakInShortcutRouting = key_chord;
22388 }
22389 idx = routing_data->NextEntryIndex;
22390 }
22391 }
22392 EndChild();
22393 Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
22394 Unindent();
22395 }
22396 TreePop();
22397 }
22398
22399 if (TreeNode("Internal state"))
22400 {
22401 Text("WINDOWING");
22402 Indent();
22403 Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
22404 Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
22405 Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
22406 Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
22407 Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
22408 Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
22409 Unindent();
22410
22411 Text("ITEMS");
22412 Indent();
22413 Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
22414 DebugLocateItemOnHover(g.ActiveId);
22415 Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
22416 Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
22417 Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
22418 Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
22419 Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
22420 DebugLocateItemOnHover(g.DragDropPayload.SourceId);
22421 Unindent();
22422
22423 Text("NAV,FOCUS");
22424 Indent();
22425 Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
22426 Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
22427 DebugLocateItemOnHover(g.NavId);
22428 Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
22429 Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
22430 Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
22431 Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
22432 Text("NavActivateFlags: %04X", g.NavActivateFlags);
22433 Text("NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav);
22434 Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
22435 Text("NavFocusRoute[] = ");
22436 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
22437 {
22438 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
22439 SameLine(0.0f, 0.0f);
22440 Text("0x%08X/", focus_scope.ID);
22441 SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
22442 }
22443 Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
22444 Unindent();
22445
22446 TreePop();
22447 }
22448
22449 // Overlay: Display windows Rectangles and Begin Order
22450 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
22451 {
22452 for (ImGuiWindow* window : g.Windows)
22453 {
22454 if (!window->WasActive)
22455 continue;
22456 ImDrawList* draw_list = GetForegroundDrawList(window);
22457 if (cfg->ShowWindowsRects)
22458 {
22459 ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
22460 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
22461 }
22462 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
22463 {
22464 char buf[32];
22465 ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
22466 float font_size = GetFontSize();
22467 draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
22468 draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
22469 }
22470 }
22471 }
22472
22473 // Overlay: Display Tables Rectangles
22474 if (cfg->ShowTablesRects)
22475 {
22476 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
22477 {
22478 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
22479 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
22480 continue;
22481 ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
22482 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
22483 {
22484 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
22485 {
22486 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
22487 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
22488 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
22489 draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
22490 }
22491 }
22492 else
22493 {
22494 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
22495 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
22496 }
22497 }
22498 }
22499
22500 #ifdef IMGUI_HAS_DOCK
22501 // Overlay: Display Docking info
22502 if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
22503 {
22504 char buf[64] = "";
22505 char* p = buf;
22506 ImGuiDockNode* node = g.DebugHoveredDockNode;
22507 ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
22508 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
22509 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
22510 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
22511 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
22512 int depth = DockNodeGetDepth(node);
22513 overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
22514 ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
22515 overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
22516 overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
22517 }
22518 #endif // #ifdef IMGUI_HAS_DOCK
22519
22520 End();
22521 }
22522
22523 void ImGui::DebugBreakClearData()
22524 {
22525 // Those fields are scattered in their respective subsystem to stay in hot-data locations
22526 ImGuiContext& g = *GImGui;
22527 g.DebugBreakInWindow = 0;
22528 g.DebugBreakInTable = 0;
22529 g.DebugBreakInShortcutRouting = ImGuiKey_None;
22530 }
22531
22532 void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
22533 {
22534 if (!BeginItemTooltip())
22535 return;
22536 Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
22537 Separator();
22538 TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
22539 Separator();
22540 TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
22541 EndTooltip();
22542 }
22543
22544 // Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
22545 // In order to reduce interferences with the contents we are trying to debug into.
22546 bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
22547 {
22548 ImGuiWindow* window = GetCurrentWindow();
22549 if (window->SkipItems)
22550 return false;
22551
22552 ImGuiContext& g = *GImGui;
22553 const ImGuiID id = window->GetID(label);
22554 const ImVec2 label_size = CalcTextSize(label, NULL, true);
22555 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
22556 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
22557
22558 const ImRect bb(pos, pos + size);
22559 ItemSize(size, 0.0f);
22560 if (!ItemAdd(bb, id))
22561 return false;
22562
22563 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
22564 bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
22565 bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
22566 DebugBreakButtonTooltip(false, description_of_location);
22567
22568 ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
22569 ImVec4 hsv;
22570 ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
22571 ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
22572
22573 RenderNavCursor(bb, id);
22574 RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
22575 RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
22576
22577 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
22578 return pressed;
22579 }
22580
22581 // [DEBUG] Display contents of Columns
22582 void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
22583 {
22584 if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
22585 return;
22586 BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
22587 for (ImGuiOldColumnData& column : columns->Columns)
22588 BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
22589 TreePop();
22590 }
22591
22592 static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
22593 {
22594 using namespace ImGui;
22595 PushID(label);
22596 PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
22597 Text("%s:", label);
22598 if (!enabled)
22599 BeginDisabled();
22600 CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
22601 CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
22602 CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
22603 CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
22604 CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
22605 CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
22606 CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
22607 CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
22608 CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
22609 CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
22610 CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
22611 CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
22612 CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
22613 CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
22614 CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
22615 if (!enabled)
22616 EndDisabled();
22617 PopStyleVar();
22618 PopID();
22619 }
22620
22621 // [DEBUG] Display contents of ImDockNode
22622 void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
22623 {
22624 ImGuiContext& g = *GImGui;
22625 const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
22626 const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted
22627 if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
22628 bool open;
22629 ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
22630 if (node->Windows.Size > 0)
22631 open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
22632 else
22633 open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%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");
22634 if (!is_alive) { PopStyleColor(); }
22635 if (is_active && IsItemHovered())
22636 if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
22637 GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
22638 if (open)
22639 {
22640 IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
22641 IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
22642 BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
22643 node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
22644 DebugNodeWindow(node->HostWindow, "HostWindow");
22645 DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
22646 BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
22647 BulletText("Misc:%s%s%s%s%s%s%s",
22648 node->IsDockSpace() ? " IsDockSpace" : "",
22649 node->IsCentralNode() ? " IsCentralNode" : "",
22650 is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
22651 node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
22652 node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
22653 if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
22654 {
22655 if (BeginTable("flags", 4))
22656 {
22657 TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
22658 TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
22659 TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
22660 TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
22661 EndTable();
22662 }
22663 TreePop();
22664 }
22665 if (node->ParentNode)
22666 DebugNodeDockNode(node->ParentNode, "ParentNode");
22667 if (node->ChildNodes[0])
22668 DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
22669 if (node->ChildNodes[1])
22670 DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
22671 if (node->TabBar)
22672 DebugNodeTabBar(node->TabBar, "TabBar");
22673 DebugNodeWindowsList(&node->Windows, "Windows");
22674
22675 TreePop();
22676 }
22677 }
22678
22679 // [DEBUG] Display contents of ImDrawList
22680 // Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
22681 void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
22682 {
22683 ImGuiContext& g = *GImGui;
22684 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22685 int cmd_count = draw_list->CmdBuffer.Size;
22686 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
22687 cmd_count--;
22688 bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
22689 if (draw_list == GetWindowDrawList())
22690 {
22691 SameLine();
22692 TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
22693 if (node_open)
22694 TreePop();
22695 return;
22696 }
22697
22698 ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
22699 if (window && IsItemHovered() && fg_draw_list)
22700 fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
22701 if (!node_open)
22702 return;
22703
22704 if (window && !window->WasActive)
22705 TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
22706
22707 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
22708 {
22709 if (pcmd->UserCallback)
22710 {
22711 BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
22712 continue;
22713 }
22714
22715 char texid_desc[30];
22716 FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TexRef);
22717 char buf[300];
22718 ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
22719 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
22720 bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
22721 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
22722 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
22723 if (!pcmd_node_open)
22724 continue;
22725
22726 // Calculate approximate coverage area (touched pixel count)
22727 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
22728 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
22729 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
22730 float total_area = 0.0f;
22731 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
22732 {
22733 ImVec2 triangle[3];
22734 for (int n = 0; n < 3; n++, idx_n++)
22735 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
22736 total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
22737 }
22738
22739 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
22740 ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
22741 Selectable(buf);
22742 if (IsItemHovered() && fg_draw_list)
22743 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
22744
22745 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
22746 ImGuiListClipper clipper;
22747 clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
22748 while (clipper.Step())
22749 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
22750 {
22751 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
22752 ImVec2 triangle[3];
22753 for (int n = 0; n < 3; n++, idx_i++)
22754 {
22755 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
22756 triangle[n] = v.pos;
22757 buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
22758 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
22759 }
22760
22761 Selectable(buf, false);
22762 if (fg_draw_list && IsItemHovered())
22763 {
22764 ImDrawListFlags backup_flags = fg_draw_list->Flags;
22765 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
22766 fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
22767 fg_draw_list->Flags = backup_flags;
22768 }
22769 }
22770 TreePop();
22771 }
22772 TreePop();
22773 }
22774
22775 // [DEBUG] Display mesh/aabb of a ImDrawCmd
22776 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
22777 {
22778 IM_ASSERT(show_mesh || show_aabb);
22779
22780 // Draw wire-frame version of all triangles
22781 ImRect clip_rect = draw_cmd->ClipRect;
22782 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
22783 ImDrawListFlags backup_flags = out_draw_list->Flags;
22784 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
22785 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
22786 {
22787 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
22788 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
22789
22790 ImVec2 triangle[3];
22791 for (int n = 0; n < 3; n++, idx_n++)
22792 vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
22793 if (show_mesh)
22794 out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
22795 }
22796 // Draw bounding boxes
22797 if (show_aabb)
22798 {
22799 out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
22800 out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
22801 }
22802 out_draw_list->Flags = backup_flags;
22803 }
22804
22805 // [DEBUG] Compute mask of inputs with the same codepoint.
22806 static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint)
22807 {
22808 int mask = 0, count = 0;
22809 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22810 {
22811 ImFontConfig* src = font->Sources[src_n];
22812 if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint))
22813 continue;
22814 mask |= (1 << src_n);
22815 count++;
22816 }
22817 return count > 1 ? mask : 0;
22818 }
22819
22820 // [DEBUG] Display details for a single font, called by ShowStyleEditor().
22821 void ImGui::DebugNodeFont(ImFont* font)
22822 {
22823 ImGuiContext& g = *GImGui;
22824 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22825 ImFontAtlas* atlas = font->ContainerAtlas;
22826 bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size);
22827
22828 // Display preview text
22829 if (!opened)
22830 Indent();
22831 Indent();
22832 if (cfg->ShowFontPreview)
22833 {
22834 PushFont(font, 0.0f);
22835 Text("The quick brown fox jumps over the lazy dog");
22836 PopFont();
22837 }
22838 if (!opened)
22839 {
22840 Unindent();
22841 Unindent();
22842 return;
22843 }
22844 if (SmallButton("Set as default"))
22845 GetIO().FontDefault = font;
22846 SameLine();
22847 BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked);
22848 if (SmallButton("Remove"))
22849 atlas->RemoveFont(font);
22850 EndDisabled();
22851 SameLine();
22852 if (SmallButton("Clear bakes"))
22853 ImFontAtlasFontDiscardBakes(atlas, font, 0);
22854 SameLine();
22855 if (SmallButton("Clear unused"))
22856 ImFontAtlasFontDiscardBakes(atlas, font, 2);
22857
22858 // Display details
22859 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
22860 SetNextItemWidth(GetFontSize() * 8);
22861 DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
22862 /*SameLine(); MetricsHelpMarker(
22863 "Note that the default embedded font is NOT meant to be scaled.\n\n"
22864 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
22865 "You may oversample them to get some flexibility with scaling. "
22866 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
22867 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/
22868 #endif
22869
22870 char c_str[5];
22871 ImTextCharToUtf8(c_str, font->FallbackChar);
22872 Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar);
22873 ImTextCharToUtf8(c_str, font->EllipsisChar);
22874 Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar);
22875
22876 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22877 {
22878 ImFontConfig* src = font->Sources[src_n];
22879 if (TreeNode(src, "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)",
22880 src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y))
22881 {
22882 const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
22883 Text("Loader: '%s'", loader->Name ? loader->Name : "N/A");
22884 #ifdef IMGUI_ENABLE_FREETYPE
22885 if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0)
22886 {
22887 unsigned int loader_flags = src->FontLoaderFlags;
22888 Text("FreeType Loader Flags: 0x%08X", loader_flags);
22889 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
22890 {
22891 ImFontAtlasFontDestroyOutput(atlas, font);
22892 src->FontLoaderFlags = loader_flags;
22893 ImFontAtlasFontInitOutput(atlas, font);
22894 }
22895 }
22896 #endif
22897 TreePop();
22898 }
22899 }
22900 if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool"))
22901 {
22902 TextWrapped("- First Input that contains the glyph is used.\n"
22903 "- 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!");
22904 if (BeginTable("table", 2))
22905 {
22906 for (unsigned int c = 0; c < 0x10000; c++)
22907 if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c))
22908 {
22909 unsigned int c_end = c + 1;
22910 while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask)
22911 c_end++;
22912 if (TableNextColumn() && TreeNode((void*)(intptr_t)c, "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(overlap_mask)))
22913 {
22914 char utf8_buf[5];
22915 for (unsigned int n = c; n < c_end; n++)
22916 {
22917 ImTextCharToUtf8(utf8_buf, n);
22918 BulletText("Codepoint U+%04X (%s)", n, utf8_buf);
22919 }
22920 TreePop();
22921 }
22922 TableNextColumn();
22923 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22924 if (overlap_mask & (1 << src_n))
22925 {
22926 Text("%d ", src_n);
22927 SameLine();
22928 }
22929 c = c_end - 1;
22930 }
22931 EndTable();
22932 }
22933 TreePop();
22934 }
22935
22936 // Display all glyphs of the fonts in separate pages of 256 characters
22937 for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++)
22938 {
22939 ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n];
22940 if (baked->ContainerFont != font)
22941 continue;
22942 PushID(baked_n);
22943 if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : ""))
22944 {
22945 if (SmallButton("Load all"))
22946 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++)
22947 baked->FindGlyph((ImWchar)base);
22948
22949 const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface);
22950 Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent);
22951 Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt);
22952 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
22953 {
22954 ImFontConfig* src = font->Sources[src_n];
22955 int oversample_h, oversample_v;
22956 ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v);
22957 BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
22958 src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y);
22959 }
22960
22961 DebugNodeFontGlyphesForSrcMask(font, baked, ~0);
22962 TreePop();
22963 }
22964 PopID();
22965 }
22966 TreePop();
22967 Unindent();
22968 }
22969
22970 void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask)
22971 {
22972 ImDrawList* draw_list = GetWindowDrawList();
22973 const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
22974 const float cell_size = baked->Size * 1;
22975 const float cell_spacing = GetStyle().ItemSpacing.y;
22976 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
22977 {
22978 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
22979 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
22980 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
22981 if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191))
22982 {
22983 base += 8192 - 256;
22984 continue;
22985 }
22986
22987 int count = 0;
22988 for (unsigned int n = 0; n < 256; n++)
22989 if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL)
22990 if (src_mask & (1 << glyph->SourceIdx))
22991 count++;
22992 if (count <= 0)
22993 continue;
22994 if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
22995 continue;
22996
22997 // Draw a 16x16 grid of glyphs
22998 ImVec2 base_pos = GetCursorScreenPos();
22999 for (unsigned int n = 0; n < 256; n++)
23000 {
23001 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
23002 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
23003 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
23004 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
23005 const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL;
23006 draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
23007 if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0)
23008 continue;
23009 font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
23010 if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
23011 {
23012 DebugNodeFontGlyph(font, glyph);
23013 EndTooltip();
23014 }
23015 }
23016 Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
23017 TreePop();
23018 }
23019 }
23020
23021 void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph)
23022 {
23023 Text("Codepoint: U+%04X", glyph->Codepoint);
23024 Separator();
23025 Text("Visible: %d", glyph->Visible);
23026 Text("AdvanceX: %.1f", glyph->AdvanceX);
23027 Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
23028 Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
23029 if (glyph->PackId >= 0)
23030 {
23031 ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId);
23032 Text("PackId: 0x%X (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);
23033 }
23034 Text("SourceIdx: %d", glyph->SourceIdx);
23035 }
23036
23037 // [DEBUG] Display contents of ImGuiStorage
23038 void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
23039 {
23040 if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
23041 return;
23042 for (const ImGuiStoragePair& p : storage->Data)
23043 {
23044 BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
23045 DebugLocateItemOnHover(p.key);
23046 }
23047 TreePop();
23048 }
23049
23050 // [DEBUG] Display contents of ImGuiTabBar
23051 void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
23052 {
23053 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
23054 char buf[256];
23055 char* p = buf;
23056 const char* buf_end = buf + IM_ARRAYSIZE(buf);
23057 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
23058 p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
23059 for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
23060 {
23061 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
23062 p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
23063 }
23064 p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
23065 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
23066 bool open = TreeNode(label, "%s", buf);
23067 if (!is_active) { PopStyleColor(); }
23068 if (is_active && IsItemHovered())
23069 {
23070 ImDrawList* draw_list = GetForegroundDrawList();
23071 draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
23072 draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
23073 draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
23074 }
23075 if (open)
23076 {
23077 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
23078 {
23079 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
23080 PushID(tab);
23081 if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
23082 if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
23083 Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
23084 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
23085 PopID();
23086 }
23087 TreePop();
23088 }
23089 }
23090
23091 void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
23092 {
23093 ImGuiContext& g = *GImGui;
23094 SetNextItemOpen(true, ImGuiCond_Once);
23095 bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
23096 if (IsItemHovered())
23097 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
23098 if (open)
23099 {
23100 ImGuiWindowFlags flags = viewport->Flags;
23101 BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nFrameBufferScale: (%.2f,%.2f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
23102 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
23103 viewport->FramebufferScale.x, viewport->FramebufferScale.y,
23104 viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y,
23105 viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
23106 if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
23107 BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
23108 //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
23109 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
23110 (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
23111 (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
23112 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
23113 (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
23114 (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
23115 (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
23116 (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
23117 (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
23118 (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
23119 (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
23120 (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
23121 (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
23122 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
23123 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
23124 TreePop();
23125 }
23126 }
23127
23128 void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx)
23129 {
23130 BulletText("%s %d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
23131 label, idx, monitor->DpiScale * 100.0f,
23132 monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y,
23133 monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y);
23134 }
23135
23136 void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
23137 {
23138 if (window == NULL)
23139 {
23140 BulletText("%s: NULL", label);
23141 return;
23142 }
23143
23144 ImGuiContext& g = *GImGui;
23145 const bool is_active = window->WasActive;
23146 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
23147 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
23148 const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
23149 if (!is_active) { PopStyleColor(); }
23150 if (IsItemHovered() && is_active)
23151 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
23152 if (!open)
23153 return;
23154
23155 if (window->MemoryCompacted)
23156 TextDisabled("Note: some memory buffers have been compacted/freed.");
23157
23158 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
23159 g.DebugBreakInWindow = window->ID;
23160
23161 ImGuiWindowFlags flags = window->Flags;
23162 DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
23163 BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
23164 BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
23165 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
23166 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
23167 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
23168 if (flags & ImGuiWindowFlags_ChildWindow)
23169 BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
23170 (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "",
23171 (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
23172 (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
23173 (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
23174 BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
23175 BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
23176 BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
23177 BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
23178 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
23179 {
23180 ImRect r = window->NavRectRel[layer];
23181 if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
23182 BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
23183 else
23184 BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
23185 DebugLocateItemOnHover(window->NavLastIds[layer]);
23186 }
23187 const ImVec2* pr = window->NavPreferredScoringPosRel;
23188 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
23189 BulletText("NavPreferredScoringPosRel[%d] = (%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
23190 BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
23191
23192 BulletText("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);
23193 BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
23194 BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
23195 if (window->DockNode || window->DockNodeAsHost)
23196 DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
23197
23198 if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
23199 if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
23200 if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
23201 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
23202 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
23203 if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
23204 {
23205 for (ImGuiOldColumns& columns : window->ColumnsStorage)
23206 DebugNodeColumns(&columns);
23207 TreePop();
23208 }
23209 DebugNodeStorage(&window->StateStorage, "Storage");
23210 TreePop();
23211 }
23212
23213 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
23214 {
23215 if (settings->WantDelete)
23216 BeginDisabled();
23217 Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
23218 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
23219 if (settings->WantDelete)
23220 EndDisabled();
23221 }
23222
23223 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
23224 {
23225 if (!TreeNode(label, "%s (%d)", label, windows->Size))
23226 return;
23227 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
23228 {
23229 PushID((*windows)[i]);
23230 DebugNodeWindow((*windows)[i], "Window");
23231 PopID();
23232 }
23233 TreePop();
23234 }
23235
23236 // FIXME-OPT: This is technically suboptimal, but it is simpler this way.
23237 void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
23238 {
23239 for (int i = 0; i < windows_size; i++)
23240 {
23241 ImGuiWindow* window = windows[i];
23242 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
23243 continue;
23244 char buf[20];
23245 ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
23246 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
23247 DebugNodeWindow(window, buf);
23248 TreePush(buf);
23249 DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
23250 TreePop();
23251 }
23252 }
23253
23254 //-----------------------------------------------------------------------------
23255 // [SECTION] DEBUG LOG WINDOW
23256 //-----------------------------------------------------------------------------
23257
23258 void ImGui::DebugLog(const char* fmt, ...)
23259 {
23260 va_list args;
23261 va_start(args, fmt);
23262 DebugLogV(fmt, args);
23263 va_end(args);
23264 }
23265
23266 void ImGui::DebugLogV(const char* fmt, va_list args)
23267 {
23268 ImGuiContext& g = *GImGui;
23269 const int old_size = g.DebugLogBuf.size();
23270 if (g.ContextName[0] != 0)
23271 g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
23272 else
23273 g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
23274 g.DebugLogBuf.appendfv(fmt, args);
23275 g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
23276 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
23277 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
23278 #ifdef IMGUI_ENABLE_TEST_ENGINE
23279 // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
23280 const int new_size = g.DebugLogBuf.size();
23281 const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
23282 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
23283 IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
23284 #endif
23285 }
23286
23287 // FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
23288 static void SameLineOrWrap(const ImVec2& size)
23289 {
23290 ImGuiContext& g = *GImGui;
23291 ImGuiWindow* window = g.CurrentWindow;
23292 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
23293 if (window->WorkRect.Contains(ImRect(pos, pos + size)))
23294 ImGui::SameLine();
23295 }
23296
23297 static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
23298 {
23299 ImGuiContext& g = *GImGui;
23300 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
23301 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
23302
23303 bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0);
23304 if (highlight_errors)
23305 ImGui::PushStyleColor(ImGuiCol_Text, ImLerp(g.Style.Colors[ImGuiCol_Text], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.30f));
23306 if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
23307 {
23308 g.DebugLogAutoDisableFrames = 2;
23309 g.DebugLogAutoDisableFlags |= flags;
23310 }
23311 if (highlight_errors)
23312 {
23313 ImGui::PopStyleColor();
23314 ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors);
23315 }
23316 else
23317 {
23318 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
23319 }
23320 }
23321
23322 void ImGui::ShowDebugLogWindow(bool* p_open)
23323 {
23324 ImGuiContext& g = *GImGui;
23325 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
23326 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
23327 if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
23328 {
23329 End();
23330 return;
23331 }
23332
23333 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
23334 CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
23335 SetItemTooltip("(except InputRouting which is spammy)");
23336
23337 ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError);
23338 ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
23339 ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
23340 ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
23341 ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
23342 ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
23343 ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont);
23344 ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
23345 ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
23346 ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
23347 ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
23348 ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
23349
23350 if (SmallButton("Clear"))
23351 {
23352 g.DebugLogBuf.clear();
23353 g.DebugLogIndex.clear();
23354 g.DebugLogSkippedErrors = 0;
23355 }
23356 SameLine();
23357 if (SmallButton("Copy"))
23358 SetClipboardText(g.DebugLogBuf.c_str());
23359 SameLine();
23360 if (SmallButton("Configure Outputs.."))
23361 OpenPopup("Outputs");
23362 if (BeginPopup("Outputs"))
23363 {
23364 CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
23365 #ifndef IMGUI_ENABLE_TEST_ENGINE
23366 BeginDisabled();
23367 #endif
23368 CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
23369 #ifndef IMGUI_ENABLE_TEST_ENGINE
23370 EndDisabled();
23371 #endif
23372 EndPopup();
23373 }
23374
23375 BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
23376
23377 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
23378 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
23379
23380 ImGuiListClipper clipper;
23381 clipper.Begin(g.DebugLogIndex.size());
23382 while (clipper.Step())
23383 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
23384 DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
23385 g.DebugLogFlags = backup_log_flags;
23386 if (GetScrollY() >= GetScrollMaxY())
23387 SetScrollHereY(1.0f);
23388 EndChild();
23389
23390 End();
23391 }
23392
23393 // Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
23394 void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
23395 {
23396 TextUnformatted(line_begin, line_end);
23397 if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
23398 return;
23399 ImGuiContext& g = *GImGui;
23400 ImRect text_rect = g.LastItemData.Rect;
23401 for (const char* p = line_begin; p <= line_end - 10; p++)
23402 {
23403 ImGuiID id = 0;
23404 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10]))
23405 continue;
23406 ImVec2 p0 = CalcTextSize(line_begin, p);
23407 ImVec2 p1 = CalcTextSize(p, p + 10);
23408 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
23409 if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
23410 DebugLocateItemOnHover(id);
23411 p += 10;
23412 }
23413 }
23414
23415 //-----------------------------------------------------------------------------
23416 // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
23417 //-----------------------------------------------------------------------------
23418
23419 // Draw a small cross at current CursorPos in current window's DrawList
23420 void ImGui::DebugDrawCursorPos(ImU32 col)
23421 {
23422 ImGuiContext& g = *GImGui;
23423 ImGuiWindow* window = g.CurrentWindow;
23424 ImVec2 pos = window->DC.CursorPos;
23425 window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
23426 window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
23427 }
23428
23429 // Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
23430 void ImGui::DebugDrawLineExtents(ImU32 col)
23431 {
23432 ImGuiContext& g = *GImGui;
23433 ImGuiWindow* window = g.CurrentWindow;
23434 float curr_x = window->DC.CursorPos.x;
23435 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
23436 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
23437 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
23438 window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
23439 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
23440 }
23441
23442 // Draw last item rect in ForegroundDrawList (so it is always visible)
23443 void ImGui::DebugDrawItemRect(ImU32 col)
23444 {
23445 ImGuiContext& g = *GImGui;
23446 ImGuiWindow* window = g.CurrentWindow;
23447 GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
23448 }
23449
23450 // [DEBUG] Locate item position/rectangle given an ID.
23451 static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
23452
23453 void ImGui::DebugLocateItem(ImGuiID target_id)
23454 {
23455 ImGuiContext& g = *GImGui;
23456 g.DebugLocateId = target_id;
23457 g.DebugLocateFrames = 2;
23458 g.DebugBreakInLocateId = false;
23459 }
23460
23461 // FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
23462 void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
23463 {
23464 if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
23465 return;
23466 ImGuiContext& g = *GImGui;
23467 DebugLocateItem(target_id);
23468 GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
23469
23470 // Can't easily use a context menu here because it will mess with focus, active id etc.
23471 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
23472 {
23473 DebugBreakButtonTooltip(false, "in ItemAdd()");
23474 if (IsKeyChordPressed(g.DebugBreakKeyChord))
23475 g.DebugBreakInLocateId = true;
23476 }
23477 }
23478
23479 void ImGui::DebugLocateItemResolveWithLastItem()
23480 {
23481 ImGuiContext& g = *GImGui;
23482
23483 // [DEBUG] Debug break requested by user
23484 if (g.DebugBreakInLocateId)
23485 IM_DEBUG_BREAK();
23486
23487 ImGuiLastItemData item_data = g.LastItemData;
23488 g.DebugLocateId = 0;
23489 ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
23490 ImRect r = item_data.Rect;
23491 r.Expand(3.0f);
23492 ImVec2 p1 = g.IO.MousePos;
23493 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);
23494 draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
23495 draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
23496 }
23497
23498 void ImGui::DebugStartItemPicker()
23499 {
23500 ImGuiContext& g = *GImGui;
23501 g.DebugItemPickerActive = true;
23502 }
23503
23504 // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
23505 void ImGui::UpdateDebugToolItemPicker()
23506 {
23507 ImGuiContext& g = *GImGui;
23508 g.DebugItemPickerBreakId = 0;
23509 if (!g.DebugItemPickerActive)
23510 return;
23511
23512 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
23513 SetMouseCursor(ImGuiMouseCursor_Hand);
23514 if (IsKeyPressed(ImGuiKey_Escape))
23515 g.DebugItemPickerActive = false;
23516 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
23517 if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
23518 {
23519 g.DebugItemPickerBreakId = hovered_id;
23520 g.DebugItemPickerActive = false;
23521 }
23522 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
23523 if (change_mapping && IsMouseClicked(mouse_button))
23524 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
23525 SetNextWindowBgAlpha(0.70f);
23526 if (!BeginTooltip())
23527 return;
23528 Text("HoveredId: 0x%08X", hovered_id);
23529 Text("Press ESC to abort picking.");
23530 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
23531 if (change_mapping)
23532 Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
23533 else
23534 TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
23535 EndTooltip();
23536 }
23537
23538 // [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
23539 void ImGui::UpdateDebugToolStackQueries()
23540 {
23541 ImGuiContext& g = *GImGui;
23542 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23543
23544 // Clear hook when id stack tool is not visible
23545 g.DebugHookIdInfoId = 0;
23546 tool->QueryHookActive = false;
23547 if (g.FrameCount != tool->LastActiveFrame + 1)
23548 return;
23549
23550 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
23551 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
23552 const ImGuiID query_main_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
23553 if (tool->QueryMainId != query_main_id)
23554 {
23555 tool->QueryMainId = query_main_id;
23556 tool->StackLevel = -1;
23557 tool->Results.resize(0);
23558 tool->ResultPathsBuf.resize(0);
23559 }
23560 if (query_main_id == 0)
23561 return;
23562
23563 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
23564 int stack_level = tool->StackLevel;
23565 if (stack_level >= 0 && stack_level < tool->Results.Size)
23566 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
23567 tool->StackLevel++;
23568
23569 // Update hook
23570 stack_level = tool->StackLevel;
23571 if (stack_level == -1)
23572 {
23573 g.DebugHookIdInfoId = query_main_id;
23574 tool->QueryHookActive = true;
23575 }
23576 else if (stack_level >= 0 && stack_level < tool->Results.Size)
23577 {
23578 g.DebugHookIdInfoId = tool->Results[stack_level].ID;
23579 tool->Results[stack_level].QueryFrameCount++;
23580 tool->QueryHookActive = true;
23581 }
23582 }
23583
23584 // [DEBUG] ID Stack tool: hooks called by GetID() family functions
23585 void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
23586 {
23587 ImGuiContext& g = *GImGui;
23588 ImGuiWindow* window = g.CurrentWindow;
23589 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23590 if (tool->QueryHookActive == false)
23591 {
23592 IM_ASSERT(id == 0);
23593 return;
23594 }
23595
23596 // Step 0: stack query
23597 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
23598 if (tool->StackLevel == -1)
23599 {
23600 IM_ASSERT(tool->Results.Size == 0);
23601 tool->StackLevel++;
23602 tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
23603 for (int n = 0; n < window->IDStack.Size + 1; n++)
23604 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
23605 return;
23606 }
23607
23608 // Step 1+: query for individual level
23609 IM_ASSERT(tool->StackLevel >= 0);
23610 if (tool->StackLevel != window->IDStack.Size)
23611 return;
23612 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
23613 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
23614
23615 if (info->DescOffset == -1)
23616 {
23617 const char* result = NULL;
23618 const char* result_end = NULL;
23619 switch (data_type)
23620 {
23621 case ImGuiDataType_S32:
23622 ImFormatStringToTempBuffer(&result, &result_end, "%d", (int)(intptr_t)data_id);
23623 break;
23624 case ImGuiDataType_String:
23625 ImFormatStringToTempBuffer(&result, &result_end, "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id);
23626 break;
23627 case ImGuiDataType_Pointer:
23628 ImFormatStringToTempBuffer(&result, &result_end, "(void*)0x%p", data_id);
23629 break;
23630 case ImGuiDataType_ID:
23631 // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
23632 ImFormatStringToTempBuffer(&result, &result_end, "0x%08X [override]", id);
23633 break;
23634 default:
23635 IM_ASSERT(0);
23636 }
23637 info->DescOffset = tool->ResultPathsBuf.size();
23638 tool->ResultPathsBuf.append(result, result_end + 1); // Include zero terminator
23639 }
23640 info->QuerySuccess = true;
23641 info->DataType = (ImS8)data_type;
23642 }
23643
23644 static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
23645 {
23646 ImGuiStackLevelInfo* info = &tool->Results[n];
23647 ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
23648 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
23649 return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name));
23650 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
23651 return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&tool->ResultPathsBuf.Buf[info->DescOffset]));
23652 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
23653 return (*buf = 0);
23654 #ifdef IMGUI_ENABLE_TEST_ENGINE
23655 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
23656 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", ImHashSkipUncontributingPrefix(label));
23657 #endif
23658 return ImFormatString(buf, buf_size, "???");
23659 }
23660
23661 // ID Stack Tool: Display UI
23662 void ImGui::ShowIDStackToolWindow(bool* p_open)
23663 {
23664 ImGuiContext& g = *GImGui;
23665 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
23666 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
23667 if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
23668 {
23669 End();
23670 return;
23671 }
23672
23673 // Display hovered/active status
23674 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23675
23676 // Build and display path
23677 tool->ResultTempBuf.resize(0);
23678 for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++)
23679 {
23680 char level_desc[256];
23681 StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
23682 tool->ResultTempBuf.append(stack_n == 0 ? "//" : "/");
23683 for (const char* p = level_desc; *p != 0; )
23684 {
23685 unsigned int c;
23686 const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL);
23687 if (c == '/')
23688 tool->ResultTempBuf.append("\\");
23689 if (c < 256 || !tool->OptHexEncodeNonAsciiChars)
23690 tool->ResultTempBuf.append(p, p_next);
23691 else for (; p < p_next; p++)
23692 tool->ResultTempBuf.appendf("\\x%02x", (unsigned char)*p);
23693 p = p_next;
23694 }
23695 }
23696 Text("0x%08X", tool->QueryMainId);
23697 SameLine();
23698 MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
23699
23700 // CTRL+C to copy path
23701 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
23702 PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f);
23703 Checkbox("Hex-encode non-ASCII", &tool->OptHexEncodeNonAsciiChars);
23704 SameLine();
23705 Checkbox("Ctrl+C: copy path", &tool->OptCopyToClipboardOnCtrlC);
23706 PopStyleVar();
23707 SameLine();
23708 TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
23709 if (tool->OptCopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
23710 {
23711 tool->CopyToClipboardLastTime = (float)g.Time;
23712 SetClipboardText(tool->ResultTempBuf.c_str());
23713 }
23714
23715 Text("- Path \"%s\"", tool->ResultTempBuf.c_str());
23716 #ifdef IMGUI_ENABLE_TEST_ENGINE
23717 Text("- Label \"%s\"", tool->QueryMainId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryMainId) : "");
23718 #endif
23719
23720 Separator();
23721
23722 // Display decorated stack
23723 tool->LastActiveFrame = g.FrameCount;
23724 if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
23725 {
23726 const float id_width = CalcTextSize("0xDDDDDDDD").x;
23727 TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
23728 TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
23729 TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
23730 TableHeadersRow();
23731 for (int n = 0; n < tool->Results.Size; n++)
23732 {
23733 ImGuiStackLevelInfo* info = &tool->Results[n];
23734 TableNextColumn();
23735 Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
23736 TableNextColumn();
23737 StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
23738 TextUnformatted(g.TempBuffer.Data);
23739 TableNextColumn();
23740 Text("0x%08X", info->ID);
23741 if (n == tool->Results.Size - 1)
23742 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
23743 }
23744 EndTable();
23745 }
23746 End();
23747 }
23748
23749 #else
23750
23751 void ImGui::ShowMetricsWindow(bool*) {}
23752 void ImGui::ShowFontAtlas(ImFontAtlas*) {}
23753 void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
23754 void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
23755 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
23756 void ImGui::DebugNodeFont(ImFont*) {}
23757 void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {}
23758 void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
23759 void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
23760 void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
23761 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
23762 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
23763 void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
23764
23765 void ImGui::ShowDebugLogWindow(bool*) {}
23766 void ImGui::ShowIDStackToolWindow(bool*) {}
23767 void ImGui::DebugStartItemPicker() {}
23768 void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
23769
23770 #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
23771
23772 #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
23773 // Demo helper function to select among loaded fonts.
23774 // Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.
23775 void ImGui::ShowFontSelector(const char* label)
23776 {
23777 ImGuiIO& io = GetIO();
23778 ImFont* font_current = GetFont();
23779 if (BeginCombo(label, font_current->GetDebugName()))
23780 {
23781 for (ImFont* font : io.Fonts->Fonts)
23782 {
23783 PushID((void*)font);
23784 if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav))
23785 io.FontDefault = font;
23786 if (font == font_current)
23787 SetItemDefaultFocus();
23788 PopID();
23789 }
23790 EndCombo();
23791 }
23792 SameLine();
23793 if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
23794 MetricsHelpMarker(
23795 "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
23796 "- Read FAQ and docs/FONTS.md for more details.");
23797 else
23798 MetricsHelpMarker(
23799 "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
23800 "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
23801 "- Read FAQ and docs/FONTS.md for more details.\n"
23802 "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
23803 }
23804 #endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
23805
23806 //-----------------------------------------------------------------------------
23807
23808 // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
23809 // 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.
23810 #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
23811 #include "imgui_user.inl"
23812 #endif
23813
23814 //-----------------------------------------------------------------------------
23815
23816 #endif // #ifndef IMGUI_DISABLE