Debian Codegraph @

extern/imgui_patched/imgui.cpp

raw
1 // dear imgui, v1.92.2b
2 // (main code and documentation)
3
4 // Help:
5 // - See links below.
6 // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7 // - Read top of imgui.cpp for more details, links and comments.
8
9 // Resources:
10 // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11 // - Homepage ................... https://github.com/ocornut/imgui
12 // - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13 // - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!)
14 // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15 // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16 // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17 // - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18 // - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19 // - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20 // - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21 // - Issues & support ........... https://github.com/ocornut/imgui/issues
22 // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24 // For first-time users having issues compiling/linking/running:
25 // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26 // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27 // Since 1.92, we encourage font loading questions to also be posted in 'Issues'.
28
29 // Copyright (c) 2014-2025 Omar Cornut
30 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
31 // See LICENSE.txt for copyright and licensing details (standard MIT License).
32 // This library is free but needs your support to sustain development and maintenance.
33 // Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
34 // PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
35 // Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
36
37 // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
38 // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
39 // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
40 // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
41 // to a better solution or official support for them.
42
43 /*
44
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 - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED.
416 IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/
417 As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+).
418 If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes.
419 - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this!
420 - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f):
421 This WILL NOT map correctly to the new system! Because font will rasterize as requested size.
422 - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required.
423 - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch.
424 - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized.
425 - PushFont() API now has a REQUIRED size parameter.
426 - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize).
427 - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value.
428 - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site.
429 - Kept inline single parameter function. Will obsolete.
430 - Fonts: **IMPORTANT** on Font Merging:
431 - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph.
432 Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font.
433 - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before!
434 - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1.
435 After the update and when using a new backend, those glyphs may now loaded from Font Source 1!
436 - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source:
437 // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
438 static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
439 ImFontConfig cfg1;
440 cfg1.GlyphExcludeRanges = exclude_ranges;
441 io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
442 // Add Font Source 2, which expects to use the range above
443 ImFontConfig cfg2;
444 cfg2.MergeMode = true;
445 io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
446 - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde
447 - Fonts: **IMPORTANT** on Thread Safety:
448 - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded.
449 - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont().
450 - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font".
451 - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'.
452 - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded().
453 - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete).
454 - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling.
455 - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese().
456 - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327)
457 - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't.
458 - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors.
459 - Fonts: obsoleted ImFont::Scale which is not useful anymore.
460 - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things:
461 - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef.
462 - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef.
463 - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]
464 - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount.
465 - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size.
466 - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance().
467 - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels().
468 - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.)
469 - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags.
470 If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader().
471 - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()
472 - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader()
473 - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1]
474 - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV().
475 - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h.
476 - old:
477 const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id);
478 ImVec2 uv0, uv1;
479 atlas->GetCustomRectUV(r, &uv0, &uv1);
480 ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1);
481 - new;
482 ImFontAtlasRect r;
483 atlas->GetCustomRect(custom_rect_id, &r);
484 ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
485 - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple.
486 - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code.
487 - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
488 - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture().
489 - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more.
490 - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition()
491 - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....);
492 - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....);
493 The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function.
494 - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete).
495 - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092)
496 - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead.
497 - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name.
498 - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387)
499 - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238)
500 - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0));
501 - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1));
502 - new: void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1));
503 - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton().
504 - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize.
505 - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable.
506 - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified.
507 - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg().
508 - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount.
509 - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX.
510 - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior.
511 prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior.
512 the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls:
513 - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937)
514 - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions.
515 As a result, old .ini data may be partially lost (docking and tables information particularly).
516 Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data.
517 - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
518 - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
519 - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
520 - pre-1.87 backends are not supported:
521 - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
522 - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
523 - for more reference:
524 - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
525 - read https://github.com/ocornut/imgui/issues/4921
526 - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
527 - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
528 - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
529 - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
530 - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
531 moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
532 kept legacy names (will obsolete) + code that copies settings once the first time. Dynamically changing the old value won't work. Switch to using the new value!
533 - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
534 this removes the requirement to redefine it for backends which are e.g. storing descriptor sets or other 64-bits structures when building on 32-bits archs. It therefore simplify various building scripts/helpers.
535 you may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID' when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
536 in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
537 - May warn: ImGui::Image((void*)MyTextureData, ...);
538 - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
539 - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
540 - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
541 - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
542 - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
543 although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
544 - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
545 it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
546 - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
547 - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
548 - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
549 - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line.
550 - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660)
551 - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
552 - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278)
553 - access those via GetPlatformIO() instead of GetIO().
554 some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol.
555 - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder:
556 - old ImageButton() before 1.89 used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID)
557 - new ImageButton() since 1.89 requires an explicit 'const char* str_id'
558 - old ImageButton() before 1.89 had frame_padding' override argument.
559 - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar().
560 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
561 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
562 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
563 - you can use: GetContentRegionAvail().x
564 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
565 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
566 - instead of: GetContentRegionMax()
567 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
568 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
569 - you can use: GetContentRegionAvail() // when called from left edge of window
570 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
571 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
572 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
573 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
574 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
575 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
576 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
577 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
578 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
579 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
580 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
581 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
582 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
583 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
584 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
585 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
586 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
587 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
588 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
589 - old: CaptureKeyboardFromApp(bool)
590 - new: SetNextFrameWantCaptureKeyboard(bool)
591 - old: CaptureMouseFromApp(bool)
592 - new: SetNextFrameWantCaptureMouse(bool)
593 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
594 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
595 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
596 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
597 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
598 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
599 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
600 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
601 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
602 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
603 for various reasons those changes makes sense. They are being made because making some of those API public.
604 only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
605 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
606 - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
607 - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
608 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
609 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
610 - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
611 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
612 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
613 - old: TreeNode("##Hidden"); SameLine(); Text("Hello"); // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
614 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
615 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
616 You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
617 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
618 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
619 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
620 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
621 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
622 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
623 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
624 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
625 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
626 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
627 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
628 those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
629 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
630 - old: BeginChild("Name", size, true)
631 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
632 - old: BeginChild("Name", size, false)
633 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
634 **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'**
635 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
636 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
637 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
638 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
639 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
640 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
641 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
642 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
643 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
644 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
645 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
646 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
647 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
648 - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
649 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
650 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
651 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
652 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
653 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
654 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
655 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
656 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
657 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
658 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
659 - ListBoxFooter() -> use EndListBox()
660 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
661 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
662 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
663 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
664 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
665 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
666 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
667 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
668 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
669 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
670 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
671 it has been frequently requested by people to use our own. We had an opt-in define which was
672 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
673 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
674 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
675 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
676 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
677 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
678 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
679 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
680 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
681 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
682 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
683 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
684 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
685 exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
686 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
687 this will require uses of legacy backend-dependent indices to be casted, e.g.
688 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
689 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
690 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
691 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
692 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
693 - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
694 - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
695 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
696 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
697 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
698 - previously this would make the window content size ~200x200:
699 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
700 - instead, please submit an item:
701 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
702 - alternative:
703 Begin(...) + Dummy(ImVec2(200,200)) + End();
704 - content size is now only extended when submitting an item!
705 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
706 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
707 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
708 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
709 - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
710 - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
711 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
712 - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
713 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
714 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
715 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
716 - Official backends from 1.87+ -> no issue.
717 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
718 - Custom backends not writing to io.NavInputs[] -> no issue.
719 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
720 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
721 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
722 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
723 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
724 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
725 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
726 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputting text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
727 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
728 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
729 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
730 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
731 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
732 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
733 read https://github.com/ocornut/imgui/issues/4921 for details.
734 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
735 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
736 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
737 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes).
738 - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
739 - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
740 - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
741 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
742 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
743 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
744 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
745 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
746 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
747 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
748 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
749 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
750 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
751 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
752 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
753 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
754 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
755 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
756 - if you are using official backends from the source tree: you have nothing to do.
757 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
758 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
759 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
760 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
761 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
762 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
763 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
764 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
765 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
766 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
767 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
768 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
769 the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
770 legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
771 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
772 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
773 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
774 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
775 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
776 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
777 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
778 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
779 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
780 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
781 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
782 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
783 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
784 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
785 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
786 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
787 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
788 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
789 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
790 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
791 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
792 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
793 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
794 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
795 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
796 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
797 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
798 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
799 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
800 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
801 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
802 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
803 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
804 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
805 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
806 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
807 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
808 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
809 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
810 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
811 - if you omitted the 'power' parameter (likely!), you are not affected.
812 - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
813 - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
814 see https://github.com/ocornut/imgui/issues/3361 for all details.
815 kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
816 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
817 - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
818 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
819 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
820 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
821 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
822 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
823 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
824 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
825 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
826 - ShowTestWindow() -> use ShowDemoWindow()
827 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
828 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
829 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
830 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
831 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
832 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
833 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
834 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
835 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
836 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
837 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
838 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
839 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
840 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
841 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
842 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
843 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
844 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
845 - ImFont::Glyph -> use ImFontGlyph
846 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
847 if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
848 The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
849 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
850 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
851 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
852 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
853 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
854 overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
855 This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
856 Please reach out if you are affected.
857 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
858 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
859 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
860 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
861 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
862 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
863 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
864 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
865 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
866 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
867 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
868 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
869 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
870 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
871 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
872 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
873 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
874 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
875 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
876 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
877 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
878 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
879 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
880 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
881 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
882 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
883 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
884 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
885 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
886 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
887 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
888 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
889 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
890 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
891 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
892 To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
893 If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
894 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
895 consistent with other functions. Kept redirection functions (will obsolete).
896 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
897 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
898 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
899 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
900 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
901 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
902 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
903 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
904 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
905 - removed Shutdown() function, as DestroyContext() serve this purpose.
906 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
907 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
908 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
909 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
910 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
911 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
912 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
913 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
914 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
915 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
916 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
917 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
918 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
919 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
920 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
921 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
922 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
923 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
924 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
925 Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
926 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
927 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
928 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
929 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
930 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
931 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
932 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
933 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
934 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
935 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
936 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
937 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
938 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
939 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
940 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
941 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
942 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
943 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
944 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
945 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
946 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix.
947 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
948 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
949 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
950 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
951 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
952 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
953 - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
954 - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
955 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
956 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
957 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
958 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
959 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
960 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
961 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
962 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
963 If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
964 This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
965 ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
966 If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
967 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
968 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
969 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
970 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
971 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
972 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
973 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
974 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
975 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
976 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
977 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
978 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
979 GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
980 GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
981 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
982 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
983 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
984 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
985 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
986 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
987 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
988 - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
989 - the signature of the io.RenderDrawListsFn handler has changed!
990 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
991 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
992 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
993 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
994 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
995 - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
996 - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
997 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
998 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
999 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
1000 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
1001 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
1002 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
1003 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
1004 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
1005 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
1006 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
1007 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
1008 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
1009 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
1010 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
1011 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
1012 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
1013 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
1014 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
1015 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
1016 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
1017 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
1018 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
1019 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
1020 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
1021 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
1022 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
1023 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
1024 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
1025 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
1026 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
1027 you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
1028 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
1029 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
1030 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
1031 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
1032 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
1033 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
1034 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
1035 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
1036 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
1037 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
1038 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
1039 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
1040 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
1041 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
1042
1043
1044 FREQUENTLY ASKED QUESTIONS (FAQ)
1045 ================================
1046
1047 Read all answers online:
1048 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
1049 Read all answers locally (with a text editor or ideally a Markdown viewer):
1050 docs/FAQ.md
1051 Some answers are copied down here to facilitate searching in code.
1052
1053 Q&A: Basics
1054 ===========
1055
1056 Q: Where is the documentation?
1057 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
1058 - Run the examples/ applications and explore them.
1059 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
1060 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
1061 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
1062 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
1063 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
1064 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
1065 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
1066 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
1067 - Your programming IDE is your friend, find the type or function declaration to find comments
1068 associated with it.
1069
1070 Q: What is this library called?
1071 Q: Which version should I get?
1072 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
1073 >> See https://www.dearimgui.com/faq for details.
1074
1075 Q&A: Integration
1076 ================
1077
1078 Q: How to get started?
1079 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
1080
1081 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
1082 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
1083 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
1084
1085 Q. How can I enable keyboard or gamepad controls?
1086 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
1087 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
1088 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
1089 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
1090 >> See https://www.dearimgui.com/faq
1091
1092 Q&A: Usage
1093 ----------
1094
1095 Q: About the ID Stack system..
1096 - Why is my widget not reacting when I click on it?
1097 - How can I have widgets with an empty label?
1098 - How can I have multiple widgets with the same label?
1099 - How can I have multiple windows with the same label?
1100 Q: How can I display an image? What is ImTextureID, how does it work?
1101 Q: How can I use my own math types instead of ImVec2?
1102 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
1103 Q: How can I display custom shapes? (using low-level ImDrawList API)
1104 >> See https://www.dearimgui.com/faq
1105
1106 Q&A: Fonts, Text
1107 ================
1108
1109 Q: How should I handle DPI in my application?
1110 Q: How can I load a different font than the default?
1111 Q: How can I easily use icons in my application?
1112 Q: How can I load multiple fonts?
1113 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
1114 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
1115
1116 Q&A: Concerns
1117 =============
1118
1119 Q: Who uses Dear ImGui?
1120 Q: Can you create elaborate/serious tools with Dear ImGui?
1121 Q: Can you reskin the look of Dear ImGui?
1122 Q: Why using C++ (as opposed to C)?
1123 >> See https://www.dearimgui.com/faq
1124
1125 Q&A: Community
1126 ==============
1127
1128 Q: How can I help?
1129 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1130 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1131 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1132 >>> See https://github.com/ocornut/imgui/wiki/Funding
1133 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1134 - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1135 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1136 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1137 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1138 - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1139
1140 */
1141
1142 //-------------------------------------------------------------------------
1143 // [SECTION] INCLUDES
1144 //-------------------------------------------------------------------------
1145
1146 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1147 #define _CRT_SECURE_NO_WARNINGS
1148 #endif
1149
1150 #ifndef IMGUI_DEFINE_MATH_OPERATORS
1151 #define IMGUI_DEFINE_MATH_OPERATORS
1152 #endif
1153
1154 #include "imgui.h"
1155 #ifndef IMGUI_DISABLE
1156 #include "imgui_internal.h"
1157
1158 // System includes
1159 #include <stdio.h> // vsnprintf, sscanf, printf
1160 #include <stdint.h> // intptr_t
1161
1162 #include "../../src/fileutils.h"
1163
1164 // [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1165 #if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1166 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1167 #endif
1168
1169 // [Windows] OS specific includes (optional)
1170 #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)
1171 #define IMGUI_DISABLE_WIN32_FUNCTIONS
1172 #endif
1173 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1174 #ifndef WIN32_LEAN_AND_MEAN
1175 #define WIN32_LEAN_AND_MEAN
1176 #endif
1177 #ifndef NOMINMAX
1178 #define NOMINMAX
1179 #endif
1180 #ifndef __MINGW32__
1181 #include <Windows.h> // _wfopen, OpenClipboard
1182 #else
1183 #include <windows.h>
1184 #endif
1185 #if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
1186 // The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1187 #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1188 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1189 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1190 #endif
1191 #endif
1192
1193 // [Apple] OS specific includes
1194 #if defined(__APPLE__)
1195 #include <TargetConditionals.h>
1196 #endif
1197
1198 // Visual Studio warnings
1199 #ifdef _MSC_VER
1200 #pragma warning (disable: 4127) // condition expression is constant
1201 #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1202 #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1203 #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1204 #endif
1205 #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).
1206 #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1207 #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1208 #endif
1209
1210 // Clang/GCC warnings with -Weverything
1211 #if defined(__clang__)
1212 #if __has_warning("-Wunknown-warning-option")
1213 #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!
1214 #endif
1215 #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1216 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1217 #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.
1218 #pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int'
1219 #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.
1220 #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.
1221 #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.
1222 #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1223 #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1224 #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1225 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1226 #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.
1227 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1228 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1229 #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
1230 #pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
1231 #elif defined(__GNUC__)
1232 // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1233 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1234 #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1235 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1236 #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
1237 #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
1238 #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1239 #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1240 #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1241 #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1242 #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
1243 #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
1244 #endif
1245
1246 // Debug options
1247 #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.
1248 #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1249
1250 // Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls.
1251 static const float FONT_DEFAULT_SIZE = 20.0f;
1252
1253 // 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.
1254 static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1255 static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1256 static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1257 static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1258 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.
1259
1260 // Tooltip offset
1261 static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1262 static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale
1263 static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale
1264
1265 // Docking
1266 static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1267
1268 //-------------------------------------------------------------------------
1269 // [SECTION] FORWARD DECLARATIONS
1270 //-------------------------------------------------------------------------
1271
1272 static void SetCurrentWindow(ImGuiWindow* window);
1273 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags, const char* displayedName = NULL);
1274 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1275
1276 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1277
1278 // Settings
1279 static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1280 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1281 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1282 static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1283 static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1284
1285 // Platform Dependents default implementation for ImGuiPlatformIO functions
1286 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx);
1287 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text);
1288 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1289 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1290
1291 namespace ImGui
1292 {
1293 // Item
1294 static void ItemHandleShortcut(ImGuiID id);
1295
1296 // Window Focus
1297 static int FindWindowFocusIndex(ImGuiWindow* window);
1298 static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags);
1299
1300 // Navigation
1301 static void NavUpdate();
1302 static void NavUpdateWindowing();
1303 static void NavUpdateWindowingApplyFocus(ImGuiWindow* window);
1304 static void NavUpdateWindowingOverlay();
1305 static void NavUpdateCancelRequest();
1306 static void NavUpdateCreateMoveRequest();
1307 static void NavUpdateCreateTabbingRequest();
1308 static float NavUpdatePageUpPageDown();
1309 static inline void NavUpdateAnyRequestFlag();
1310 static void NavUpdateCreateWrappingRequest();
1311 static void NavEndFrame();
1312 static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb);
1313 static void NavApplyItemToResult(ImGuiNavItemData* result);
1314 static void NavProcessItem();
1315 static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1316 static ImGuiInputSource NavCalcPreferredRefPosSource();
1317 static ImVec2 NavCalcPreferredRefPos();
1318 static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1319 static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1320 static void NavRestoreLayer(ImGuiNavLayer layer);
1321
1322 // Error Checking and Debug Tools
1323 static void ErrorCheckNewFrameSanityChecks();
1324 static void ErrorCheckEndFrameSanityChecks();
1325 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
1326 static void UpdateDebugToolItemPicker();
1327 static void UpdateDebugToolStackQueries();
1328 static void UpdateDebugToolFlashStyleColor();
1329 #endif
1330
1331 // Inputs
1332 static void UpdateKeyboardInputs();
1333 static void UpdateMouseInputs();
1334 static void UpdateMouseWheel();
1335 static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1336
1337 // Misc
1338 static void UpdateFontsNewFrame();
1339 static void UpdateFontsEndFrame();
1340 static void UpdateTexturesNewFrame();
1341 static void UpdateTexturesEndFrame();
1342 static void UpdateSettings();
1343 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);
1344 static void RenderWindowOuterBorders(ImGuiWindow* window);
1345 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);
1346 static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1347 static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1348 static void RenderDimmedBackgrounds();
1349 static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1350 static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect);
1351
1352 // Viewports
1353 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.
1354 static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1355 static void DestroyViewport(ImGuiViewportP* viewport);
1356 static void UpdateViewportsNewFrame();
1357 static void UpdateViewportsEndFrame();
1358 static void WindowSelectViewport(ImGuiWindow* window);
1359 static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1360 static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1361 static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1362 static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1363 static int FindPlatformMonitorForPos(const ImVec2& pos);
1364 static int FindPlatformMonitorForRect(const ImRect& r);
1365 static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1366
1367 }
1368
1369 //-----------------------------------------------------------------------------
1370 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
1371 //-----------------------------------------------------------------------------
1372
1373 // DLL users:
1374 // - Heaps and globals are not shared across DLL boundaries!
1375 // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1376 // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1377 // - 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.
1378 // - 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).
1379
1380 // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1381 // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1382 // Change to a different context by calling ImGui::SetCurrentContext().
1383 // - Important: Dear ImGui functions are not thread-safe because of this pointer.
1384 // If you want thread-safety to allow N threads to access N different contexts:
1385 // - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1386 // struct ImGuiContext;
1387 // extern thread_local ImGuiContext* MyImGuiTLS;
1388 // #define GImGui MyImGuiTLS
1389 // 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.
1390 // - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1391 // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1392 // - DLL users: read comments above.
1393 #ifndef GImGui
1394 ImGuiContext* GImGui = NULL;
1395 #endif
1396
1397 // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1398 // - 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.
1399 // - DLL users: read comments above.
1400 #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1401 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1402 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1403 #else
1404 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1405 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1406 #endif
1407 static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1408 static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1409 static void* GImAllocatorUserData = NULL;
1410
1411 //-----------------------------------------------------------------------------
1412 // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
1413 //-----------------------------------------------------------------------------
1414
1415 ImGuiStyle::ImGuiStyle()
1416 {
1417 FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame.
1418 FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user.
1419 FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
1420
1421 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1422 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1423 WindowPadding = ImVec2(8,8); // Padding within a window
1424 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.
1425 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1426 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.
1427 WindowMinSize = ImVec2(32,32); // Minimum window size
1428 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1429 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1430 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1431 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1432 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1433 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1434 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1435 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1436 FrameShading = 0.0f; // Gradient intensity of frame
1437 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1438 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1439 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1440 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1441 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!
1442 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1443 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1444 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1445 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1446 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1447 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1448 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1449 ImageBorderSize = 0.0f; // Thickness of border around tabs.
1450 TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1451 TabBorderSize = 0.0f; // Thickness of border around tabs.
1452 TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
1453 TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy.
1454 TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
1455 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.
1456 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1457 TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1458 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1459 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1460 TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone;
1461 TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
1462 TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line.
1463 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1464 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1465 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.
1466 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText()
1467 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1468 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.
1469 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.
1470 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.
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 DoFrameShadingForMultilineText = false;
1480
1481 // Behaviors
1482 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1483 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1484 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1485 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1486 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1487
1488 // [Internal]
1489 _MainScale = 1.0f;
1490 _NextFrameFontSizeBase = 0.0f;
1491
1492 // Default theme
1493 ImGui::StyleColorsDark(this);
1494 }
1495
1496
1497 // Scale all spacing/padding/thickness values. Do not scale fonts.
1498 // 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.
1499 void ImGuiStyle::ScaleAllSizes(float scale_factor)
1500 {
1501 _MainScale *= scale_factor;
1502 WindowPadding = ImTrunc(WindowPadding * scale_factor);
1503 WindowRounding = ImTrunc(WindowRounding * scale_factor);
1504 WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1505 WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor);
1506 ChildRounding = ImTrunc(ChildRounding * scale_factor);
1507 PopupRounding = ImTrunc(PopupRounding * scale_factor);
1508 FramePadding = ImTrunc(FramePadding * scale_factor);
1509 FrameRounding = ImTrunc(FrameRounding * scale_factor);
1510 ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1511 ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1512 CellPadding = ImTrunc(CellPadding * scale_factor);
1513 TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1514 IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1515 ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1516 ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1517 ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1518 GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1519 GrabRounding = ImTrunc(GrabRounding * scale_factor);
1520 LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1521 ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor);
1522 TabRounding = ImTrunc(TabRounding * scale_factor);
1523 TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor);
1524 TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor);
1525 TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected;
1526 TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected;
1527 TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
1528 TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor);
1529 SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1530 DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1531 DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1532 DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1533 MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1534 }
1535
1536 ImGuiIO::ImGuiIO()
1537 {
1538 // Most fields are initialized with zero
1539 memset(this, 0, sizeof(*this));
1540 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1541
1542 // Settings
1543 ConfigFlags = ImGuiConfigFlags_None;
1544 BackendFlags = ImGuiBackendFlags_None;
1545 DisplaySize = ImVec2(-1.0f, -1.0f);
1546 DeltaTime = 1.0f / 60.0f;
1547 IniSavingRate = 5.0f;
1548 InputScale = 1.0f;
1549 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).
1550 LogFilename = "imgui_log.txt";
1551 UserData = NULL;
1552
1553 Fonts = NULL;
1554 FontDefault = NULL;
1555 FontAllowUserScaling = false;
1556 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1557 FontGlobalScale = 1.0f; // Use style.FontScaleMain instead!
1558 #endif
1559 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1560
1561 // Keyboard/Gamepad Navigation options
1562 ConfigNavSwapGamepadButtons = false;
1563 ConfigNavMoveSetMousePos = false;
1564 ConfigNavCaptureKeyboard = true;
1565 ConfigNavEscapeClearFocusItem = true;
1566 ConfigNavEscapeClearFocusWindow = false;
1567 ConfigNavCursorVisibleAuto = true;
1568 ConfigNavCursorVisibleAlways = false;
1569
1570 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1571 ConfigDockingNoSplit = false;
1572 ConfigDockingWithShift = false;
1573 ConfigDockingAlwaysTabBar = false;
1574 ConfigDockingTransparentPayload = false;
1575
1576 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1577 ConfigViewportsNoAutoMerge = false;
1578 ConfigViewportsNoTaskBarIcon = false;
1579 ConfigViewportsNoDecoration = true;
1580 ConfigViewportsNoDefaultParent = false;
1581 ConfigViewportPlatformFocusSetsImGuiFocus = true;
1582
1583 // Inertial scrolling options (when ImGuiConfigFlags_InertialScrollEnable is set)
1584 ConfigInertialScrollToleranceSqr = 36.0f;
1585
1586 // ScrollText options
1587 ScrollTextSpeed = 100.0f;
1588 ScrollTextSpacing = 8.0f;
1589 AlwaysScrollText = false;
1590
1591 // Miscellaneous options
1592 MouseDrawCursor = false;
1593 #ifdef __APPLE__
1594 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1595 #else
1596 ConfigMacOSXBehaviors = false;
1597 #endif
1598 ConfigInputTrickleEventQueue = true;
1599 ConfigInputTextCursorBlink = true;
1600 ConfigInputTextEnterKeepActive = false;
1601 ConfigDragClickToInputText = false;
1602 ConfigWindowsResizeFromEdges = true;
1603 ConfigWindowsMoveFromTitleBarOnly = false;
1604 ConfigWindowsCopyContentsWithCtrlC = false;
1605 ConfigScrollbarScrollByPage = true;
1606 ConfigMemoryCompactTimer = 60.0f;
1607 ConfigDebugIsDebuggerPresent = false;
1608 ConfigDebugHighlightIdConflicts = true;
1609 ConfigDebugHighlightIdConflictsShowItemPicker = true;
1610 ConfigDebugBeginReturnValueOnce = false;
1611 ConfigDebugBeginReturnValueLoop = false;
1612
1613 ConfigErrorRecovery = true;
1614 ConfigErrorRecoveryEnableAssert = true;
1615 ConfigErrorRecoveryEnableDebugLog = true;
1616 ConfigErrorRecoveryEnableTooltip = true;
1617
1618 // Inputs Behaviors
1619 MouseDoubleClickTime = 0.30f;
1620 MouseDoubleClickMaxDist = 6.0f;
1621 MouseDragThreshold = 6.0f;
1622 KeyRepeatDelay = 0.275f;
1623 KeyRepeatRate = 0.050f;
1624
1625 // Platform Functions
1626 // Note: Initialize() will setup default clipboard/ime handlers.
1627 BackendPlatformName = BackendRendererName = NULL;
1628 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1629
1630 // Input (NB: we already have memset zero the entire structure!)
1631 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1632 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1633 MouseSource = ImGuiMouseSource_Mouse;
1634 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1635 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1636 AppAcceptingEvents = true;
1637 }
1638
1639 // Pass in translated ASCII characters for text input.
1640 // - with glfw you can get those from the callback set in glfwSetCharCallback()
1641 // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1642 // FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1643 void ImGuiIO::AddInputCharacter(unsigned int c)
1644 {
1645 IM_ASSERT(Ctx != NULL);
1646 ImGuiContext& g = *Ctx;
1647 if (c == 0 || !AppAcceptingEvents)
1648 return;
1649
1650 ImGuiInputEvent e;
1651 e.Type = ImGuiInputEventType_Text;
1652 e.Source = ImGuiInputSource_Keyboard;
1653 e.EventId = g.InputEventsNextEventId++;
1654 e.Text.Char = c;
1655 g.InputEventsQueue.push_back(e);
1656 }
1657
1658 // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1659 // we should save the high surrogate.
1660 void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1661 {
1662 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1663 return;
1664
1665 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1666 {
1667 if (InputQueueSurrogate != 0)
1668 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1669 InputQueueSurrogate = c;
1670 return;
1671 }
1672
1673 ImWchar cp = c;
1674 if (InputQueueSurrogate != 0)
1675 {
1676 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1677 {
1678 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1679 }
1680 else
1681 {
1682 #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1683 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1684 #else
1685 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1686 #endif
1687 }
1688
1689 InputQueueSurrogate = 0;
1690 }
1691 AddInputCharacter((unsigned)cp);
1692 }
1693
1694 void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1695 {
1696 if (!AppAcceptingEvents)
1697 return;
1698 while (*utf8_chars != 0)
1699 {
1700 unsigned int c = 0;
1701 utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1702 AddInputCharacter(c);
1703 }
1704 }
1705
1706 // Clear all incoming events.
1707 void ImGuiIO::ClearEventsQueue()
1708 {
1709 IM_ASSERT(Ctx != NULL);
1710 ImGuiContext& g = *Ctx;
1711 g.InputEventsQueue.clear();
1712 }
1713
1714 // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1715 void ImGuiIO::ClearInputKeys()
1716 {
1717 ImGuiContext& g = *Ctx;
1718 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
1719 {
1720 if (ImGui::IsMouseKey((ImGuiKey)key))
1721 continue;
1722 ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
1723 key_data->Down = false;
1724 key_data->DownDuration = -1.0f;
1725 key_data->DownDurationPrev = -1.0f;
1726 }
1727 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1728 KeyMods = ImGuiMod_None;
1729 InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1730 }
1731
1732 void ImGuiIO::ClearInputMouse()
1733 {
1734 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1735 {
1736 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
1737 key_data->Down = false;
1738 key_data->DownDuration = -1.0f;
1739 key_data->DownDurationPrev = -1.0f;
1740 }
1741 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1742 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1743 {
1744 MouseDown[n] = false;
1745 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1746 }
1747 MouseWheel = MouseWheelH = 0.0f;
1748 }
1749
1750 // Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1751 // Current frame character buffer is now also cleared by ClearInputKeys().
1752 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1753 void ImGuiIO::ClearInputCharacters()
1754 {
1755 InputQueueCharacters.resize(0);
1756 }
1757 #endif
1758
1759 static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1760 {
1761 ImGuiContext& g = *ctx;
1762 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1763 {
1764 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1765 if (e->Type != type)
1766 continue;
1767 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1768 continue;
1769 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1770 continue;
1771 return e;
1772 }
1773 return NULL;
1774 }
1775
1776 // Queue a new key down/up event.
1777 // - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1778 // - bool down: Is the key down? use false to signify a key release.
1779 // - float analog_value: 0.0f..1.0f
1780 // IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1781 // WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1782 void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1783 {
1784 //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); }
1785 IM_ASSERT(Ctx != NULL);
1786 if (key == ImGuiKey_None || !AppAcceptingEvents)
1787 return;
1788 ImGuiContext& g = *Ctx;
1789 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.
1790 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1791
1792 // MacOS: swap Cmd(Super) and Ctrl
1793 if (g.IO.ConfigMacOSXBehaviors)
1794 {
1795 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1796 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1797 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1798 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1799 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1800 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1801 }
1802
1803 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1804 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1805 const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1806 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1807 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1808 if (latest_key_down == down && latest_key_analog == analog_value)
1809 return;
1810
1811 // Add event
1812 ImGuiInputEvent e;
1813 e.Type = ImGuiInputEventType_Key;
1814 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1815 e.EventId = g.InputEventsNextEventId++;
1816 e.Key.Key = key;
1817 e.Key.Down = down;
1818 e.Key.AnalogValue = analog_value;
1819 g.InputEventsQueue.push_back(e);
1820 }
1821
1822 void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1823 {
1824 if (!AppAcceptingEvents)
1825 return;
1826 AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1827 }
1828
1829 // [Optional] Call after AddKeyEvent().
1830 // Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1831 // 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.
1832 void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1833 {
1834 if (key == ImGuiKey_None)
1835 return;
1836 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1837 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1838 IM_UNUSED(key); // Yet unused
1839 IM_UNUSED(native_keycode); // Yet unused
1840 IM_UNUSED(native_scancode); // Yet unused
1841 IM_UNUSED(native_legacy_index); // Yet unused
1842 }
1843
1844 // 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.
1845 void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1846 {
1847 AppAcceptingEvents = accepting_events;
1848 }
1849
1850 // Queue a mouse move event
1851 void ImGuiIO::AddMousePosEvent(float x, float y)
1852 {
1853 IM_ASSERT(Ctx != NULL);
1854 ImGuiContext& g = *Ctx;
1855 if (!AppAcceptingEvents)
1856 return;
1857
1858 // Apply same flooring as UpdateMouseInputs()
1859 ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1860
1861 // Filter duplicate
1862 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1863 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1864 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1865 return;
1866
1867 ImGuiInputEvent e;
1868 e.Type = ImGuiInputEventType_MousePos;
1869 e.Source = ImGuiInputSource_Mouse;
1870 e.EventId = g.InputEventsNextEventId++;
1871 e.MousePos.PosX = pos.x;
1872 e.MousePos.PosY = pos.y;
1873 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1874 g.InputEventsQueue.push_back(e);
1875 }
1876
1877 void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1878 {
1879 IM_ASSERT(Ctx != NULL);
1880 ImGuiContext& g = *Ctx;
1881 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1882 if (!AppAcceptingEvents)
1883 return;
1884
1885 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1886 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1887 {
1888 // Order of both statements matters: this event will still release mouse button 1
1889 mouse_button = 1;
1890 if (!down)
1891 MouseCtrlLeftAsRightClick = false;
1892 }
1893
1894 // Filter duplicate
1895 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1896 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1897 if (latest_button_down == down)
1898 return;
1899
1900 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1901 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1902 // - At this point we want from !down to down, so this is handling the initial press.
1903 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1904 {
1905 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1906 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1907 {
1908 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1909 MouseCtrlLeftAsRightClick = true;
1910 AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1911 return;
1912 }
1913 }
1914
1915 ImGuiInputEvent e;
1916 e.Type = ImGuiInputEventType_MouseButton;
1917 e.Source = ImGuiInputSource_Mouse;
1918 e.EventId = g.InputEventsNextEventId++;
1919 e.MouseButton.Button = mouse_button;
1920 e.MouseButton.Down = down;
1921 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1922 g.InputEventsQueue.push_back(e);
1923 }
1924
1925 // Queue a mouse wheel event (some mouse/API may only have a Y component)
1926 void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1927 {
1928 IM_ASSERT(Ctx != NULL);
1929 ImGuiContext& g = *Ctx;
1930
1931 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1932 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1933 return;
1934
1935 ImGuiInputEvent e;
1936 e.Type = ImGuiInputEventType_MouseWheel;
1937 e.Source = ImGuiInputSource_Mouse;
1938 e.EventId = g.InputEventsNextEventId++;
1939 e.MouseWheel.WheelX = wheel_x;
1940 e.MouseWheel.WheelY = wheel_y;
1941 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1942 g.InputEventsQueue.push_back(e);
1943 }
1944
1945 // This is not a real event, the data is latched in order to be stored in actual Mouse events.
1946 // This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1947 void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1948 {
1949 IM_ASSERT(Ctx != NULL);
1950 ImGuiContext& g = *Ctx;
1951 g.InputEventsNextMouseSource = source;
1952 }
1953
1954 void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1955 {
1956 IM_ASSERT(Ctx != NULL);
1957 ImGuiContext& g = *Ctx;
1958 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1959 if (!AppAcceptingEvents)
1960 return;
1961
1962 // Filter duplicate
1963 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1964 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1965 if (latest_viewport_id == viewport_id)
1966 return;
1967
1968 ImGuiInputEvent e;
1969 e.Type = ImGuiInputEventType_MouseViewport;
1970 e.Source = ImGuiInputSource_Mouse;
1971 e.MouseViewport.HoveredViewportID = viewport_id;
1972 g.InputEventsQueue.push_back(e);
1973 }
1974
1975 void ImGuiIO::AddFocusEvent(bool focused)
1976 {
1977 IM_ASSERT(Ctx != NULL);
1978 ImGuiContext& g = *Ctx;
1979
1980 // Filter duplicate
1981 const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1982 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1983 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1984 return;
1985
1986 ImGuiInputEvent e;
1987 e.Type = ImGuiInputEventType_Focus;
1988 e.EventId = g.InputEventsNextEventId++;
1989 e.AppFocused.Focused = focused;
1990 g.InputEventsQueue.push_back(e);
1991 }
1992
1993 ImGuiPlatformIO::ImGuiPlatformIO()
1994 {
1995 // Most fields are initialized with zero
1996 memset(this, 0, sizeof(*this));
1997 Platform_LocaleDecimalPoint = '.';
1998 }
1999
2000 //-----------------------------------------------------------------------------
2001 // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
2002 //-----------------------------------------------------------------------------
2003
2004 ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
2005 {
2006 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
2007 ImVec2 p_last = p1;
2008 ImVec2 p_closest;
2009 float p_closest_dist2 = FLT_MAX;
2010 float t_step = 1.0f / (float)num_segments;
2011 for (int i_step = 1; i_step <= num_segments; i_step++)
2012 {
2013 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
2014 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
2015 float dist2 = ImLengthSqr(p - p_line);
2016 if (dist2 < p_closest_dist2)
2017 {
2018 p_closest = p_line;
2019 p_closest_dist2 = dist2;
2020 }
2021 p_last = p_current;
2022 }
2023 return p_closest;
2024 }
2025
2026 // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
2027 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)
2028 {
2029 float dx = x4 - x1;
2030 float dy = y4 - y1;
2031 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
2032 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
2033 d2 = (d2 >= 0) ? d2 : -d2;
2034 d3 = (d3 >= 0) ? d3 : -d3;
2035 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
2036 {
2037 ImVec2 p_current(x4, y4);
2038 ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
2039 float dist2 = ImLengthSqr(p - p_line);
2040 if (dist2 < p_closest_dist2)
2041 {
2042 p_closest = p_line;
2043 p_closest_dist2 = dist2;
2044 }
2045 p_last = p_current;
2046 }
2047 else if (level < 10)
2048 {
2049 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
2050 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
2051 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
2052 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
2053 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
2054 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
2055 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
2056 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
2057 }
2058 }
2059
2060 // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
2061 // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
2062 ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
2063 {
2064 IM_ASSERT(tess_tol > 0.0f);
2065 ImVec2 p_last = p1;
2066 ImVec2 p_closest;
2067 float p_closest_dist2 = FLT_MAX;
2068 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);
2069 return p_closest;
2070 }
2071
2072 ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
2073 {
2074 ImVec2 ap = p - a;
2075 ImVec2 ab_dir = b - a;
2076 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
2077 if (dot < 0.0f)
2078 return a;
2079 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
2080 if (dot > ab_len_sqr)
2081 return b;
2082 return a + ab_dir * dot / ab_len_sqr;
2083 }
2084
2085 bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2086 {
2087 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
2088 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
2089 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
2090 return ((b1 == b2) && (b2 == b3));
2091 }
2092
2093 void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
2094 {
2095 ImVec2 v0 = b - a;
2096 ImVec2 v1 = c - a;
2097 ImVec2 v2 = p - a;
2098 const float denom = v0.x * v1.y - v1.x * v0.y;
2099 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
2100 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
2101 out_u = 1.0f - out_v - out_w;
2102 }
2103
2104 ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2105 {
2106 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
2107 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
2108 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
2109 float dist2_ab = ImLengthSqr(p - proj_ab);
2110 float dist2_bc = ImLengthSqr(p - proj_bc);
2111 float dist2_ca = ImLengthSqr(p - proj_ca);
2112 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
2113 if (m == dist2_ab)
2114 return proj_ab;
2115 if (m == dist2_bc)
2116 return proj_bc;
2117 return proj_ca;
2118 }
2119
2120 //-----------------------------------------------------------------------------
2121 // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
2122 //-----------------------------------------------------------------------------
2123
2124 // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
2125 int ImStricmp(const char* str1, const char* str2)
2126 {
2127 int d;
2128 while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
2129 return d;
2130 }
2131
2132 int ImStrnicmp(const char* str1, const char* str2, size_t count)
2133 {
2134 int d = 0;
2135 while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
2136 return d;
2137 }
2138
2139 void ImStrncpy(char* dst, const char* src, size_t count)
2140 {
2141 if (count < 1)
2142 return;
2143 if (count > 1)
2144 strncpy(dst, src, count - 1);
2145 dst[count - 1] = 0;
2146 }
2147
2148 char* ImStrdup(const char* str)
2149 {
2150 size_t len = ImStrlen(str);
2151 void* buf = IM_ALLOC(len + 1);
2152 return (char*)memcpy(buf, (const void*)str, len + 1);
2153 }
2154
2155 void* ImMemdup(const void* src, size_t size)
2156 {
2157 void* dst = IM_ALLOC(size);
2158 return memcpy(dst, src, size);
2159 }
2160
2161 char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
2162 {
2163 size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1;
2164 size_t src_size = ImStrlen(src) + 1;
2165 if (dst_buf_size < src_size)
2166 {
2167 IM_FREE(dst);
2168 dst = (char*)IM_ALLOC(src_size);
2169 if (p_dst_size)
2170 *p_dst_size = src_size;
2171 }
2172 return (char*)memcpy(dst, (const void*)src, src_size);
2173 }
2174
2175 const char* ImStrchrRange(const char* str, const char* str_end, char c)
2176 {
2177 const char* p = (const char*)ImMemchr(str, (int)c, str_end - str);
2178 return p;
2179 }
2180
2181 int ImStrlenW(const ImWchar* str)
2182 {
2183 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
2184 int n = 0;
2185 while (*str++) n++;
2186 return n;
2187 }
2188
2189 // Find end-of-line. Return pointer will point to either first \n, either str_end.
2190 const char* ImStreolRange(const char* str, const char* str_end)
2191 {
2192 const char* p = (const char*)ImMemchr(str, '\n', str_end - str);
2193 return p ? p : str_end;
2194 }
2195
2196 const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
2197 {
2198 IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin));
2199 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2200 buf_mid_line--;
2201 return buf_mid_line;
2202 }
2203
2204 const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2205 {
2206 if (!needle_end)
2207 needle_end = needle + ImStrlen(needle);
2208
2209 const char un0 = (char)ImToUpper(*needle);
2210 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2211 {
2212 if (ImToUpper(*haystack) == un0)
2213 {
2214 const char* b = needle + 1;
2215 for (const char* a = haystack + 1; b < needle_end; a++, b++)
2216 if (ImToUpper(*a) != ImToUpper(*b))
2217 break;
2218 if (b == needle_end)
2219 return haystack;
2220 }
2221 haystack++;
2222 }
2223 return NULL;
2224 }
2225
2226 // 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.
2227 void ImStrTrimBlanks(char* buf)
2228 {
2229 char* p = buf;
2230 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
2231 p++;
2232 char* p_start = p;
2233 while (*p != 0) // Find end of string
2234 p++;
2235 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
2236 p--;
2237 if (p_start != buf) // Copy memory if we had leading blanks
2238 memmove(buf, p_start, p - p_start);
2239 buf[p - p_start] = 0; // Zero terminate
2240 }
2241
2242 const char* ImStrSkipBlank(const char* str)
2243 {
2244 while (str[0] == ' ' || str[0] == '\t')
2245 str++;
2246 return str;
2247 }
2248
2249 // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2250 // 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.
2251 // B) When buf==NULL vsnprintf() will return the output size.
2252 #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2253
2254 // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2255 // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2256 // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2257 // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2258 #ifdef IMGUI_USE_STB_SPRINTF
2259 #ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2260 #define STB_SPRINTF_IMPLEMENTATION
2261 #endif
2262 #ifdef IMGUI_STB_SPRINTF_FILENAME
2263 #include IMGUI_STB_SPRINTF_FILENAME
2264 #else
2265 #include "stb_sprintf.h"
2266 #endif
2267 #endif // #ifdef IMGUI_USE_STB_SPRINTF
2268
2269 #if defined(_MSC_VER) && !defined(vsnprintf)
2270 #define vsnprintf _vsnprintf
2271 #endif
2272
2273 int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2274 {
2275 va_list args;
2276 va_start(args, fmt);
2277 #ifdef IMGUI_USE_STB_SPRINTF
2278 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2279 #else
2280 int w = vsnprintf(buf, buf_size, fmt, args);
2281 #endif
2282 va_end(args);
2283 if (buf == NULL)
2284 return w;
2285 if (w == -1 || w >= (int)buf_size)
2286 w = (int)buf_size - 1;
2287 buf[w] = 0;
2288 return w;
2289 }
2290
2291 int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2292 {
2293 #ifdef IMGUI_USE_STB_SPRINTF
2294 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2295 #else
2296 int w = vsnprintf(buf, buf_size, fmt, args);
2297 #endif
2298 if (buf == NULL)
2299 return w;
2300 if (w == -1 || w >= (int)buf_size)
2301 w = (int)buf_size - 1;
2302 buf[w] = 0;
2303 return w;
2304 }
2305 #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2306
2307 void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2308 {
2309 va_list args;
2310 va_start(args, fmt);
2311 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2312 va_end(args);
2313 }
2314
2315 // FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2316 // by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2317 // ImGuiTempBufferToken token;
2318 // ImFormatStringToTempBuffer(token, ...);
2319 void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2320 {
2321 ImGuiContext& g = *GImGui;
2322 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2323 {
2324 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2325 if (buf == NULL)
2326 buf = "(null)";
2327 *out_buf = buf;
2328 if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); }
2329 }
2330 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2331 {
2332 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2333 const char* buf = va_arg(args, const char*);
2334 if (buf == NULL)
2335 {
2336 buf = "(null)";
2337 buf_len = ImMin(buf_len, 6);
2338 }
2339 *out_buf = buf;
2340 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2341 }
2342 else
2343 {
2344 int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2345 *out_buf = g.TempBuffer.Data;
2346 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2347 }
2348 }
2349
2350 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2351 // CRC32 needs a 1KB lookup table (not cache friendly)
2352 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2353 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2354 static const ImU32 GCrc32LookupTable[256] =
2355 {
2356 #ifdef IMGUI_USE_LEGACY_CRC32_ADLER
2357 // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
2358 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2359 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2360 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2361 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2362 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2363 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2364 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2365 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2366 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2367 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2368 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2369 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2370 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2371 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2372 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2373 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2374 #else
2375 // CRC32c table compatible with SSE 4.2 instructions
2376 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
2377 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
2378 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
2379 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
2380 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
2381 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
2382 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
2383 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
2384 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
2385 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
2386 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
2387 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
2388 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
2389 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
2390 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
2391 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
2392 #endif
2393 };
2394 #endif
2395
2396 // Known size hash
2397 // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2398 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2399 ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2400 {
2401 ImU32 crc = ~seed;
2402 const unsigned char* data = (const unsigned char*)data_p;
2403 const unsigned char *data_end = (const unsigned char*)data_p + data_size;
2404 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2405 const ImU32* crc32_lut = GCrc32LookupTable;
2406 while (data < data_end)
2407 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2408 return ~crc;
2409 #else
2410 while (data + 4 <= data_end)
2411 {
2412 crc = _mm_crc32_u32(crc, *(ImU32*)data);
2413 data += 4;
2414 }
2415 while (data < data_end)
2416 crc = _mm_crc32_u8(crc, *data++);
2417 return ~crc;
2418 #endif
2419 }
2420
2421 // Zero-terminated string hash, with support for ### to reset back to seed value
2422 // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2423 // Because this syntax is rarely used we are optimizing for the common case.
2424 // - If we reach ### in the string we discard the hash so far and reset to the seed.
2425 // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2426 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2427 ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2428 {
2429 seed = ~seed;
2430 ImU32 crc = seed;
2431 const unsigned char* data = (const unsigned char*)data_p;
2432 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2433 const ImU32* crc32_lut = GCrc32LookupTable;
2434 #endif
2435 if (data_size != 0)
2436 {
2437 while (data_size-- != 0)
2438 {
2439 unsigned char c = *data++;
2440 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2441 crc = seed;
2442 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2443 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2444 #else
2445 crc = _mm_crc32_u8(crc, c);
2446 #endif
2447 }
2448 }
2449 else
2450 {
2451 while (unsigned char c = *data++)
2452 {
2453 if (c == '#' && data[0] == '#' && data[1] == '#')
2454 crc = seed;
2455 #ifndef IMGUI_ENABLE_SSE4_2_CRC
2456 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2457 #else
2458 crc = _mm_crc32_u8(crc, c);
2459 #endif
2460 }
2461 }
2462 return ~crc;
2463 }
2464
2465 //-----------------------------------------------------------------------------
2466 // [SECTION] MISC HELPERS/UTILITIES (File functions)
2467 //-----------------------------------------------------------------------------
2468
2469 // Default file functions
2470 #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2471
2472 ImFileHandle ImFileOpen(const char* filename, const char* mode)
2473 {
2474 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__)))
2475 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2476 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2477 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2478 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2479
2480 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2481 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2482 wchar_t local_temp_stack[FILENAME_MAX];
2483 ImVector<wchar_t> local_temp_heap;
2484 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2485 local_temp_heap.resize(filename_wsize + mode_wsize);
2486 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2487 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2488 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2489 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2490 return ::_wfopen(filename_wbuf, mode_wbuf);
2491 #else
2492 return fopen(filename, mode);
2493 #endif
2494 }
2495
2496 // 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.
2497 bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
2498 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; }
2499 ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
2500 ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
2501 #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2502
2503 // Helper: Load file content into memory
2504 // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2505 // This can't really be used with "rt" because fseek size won't match read size.
2506 void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2507 {
2508 IM_ASSERT(filename && mode);
2509 if (out_file_size)
2510 *out_file_size = 0;
2511
2512 ImFileHandle f;
2513 if ((f = ImFileOpen(filename, mode)) == NULL)
2514 return NULL;
2515
2516 size_t file_size = (size_t)ImFileGetSize(f);
2517 if (file_size == (size_t)-1)
2518 {
2519 ImFileClose(f);
2520 return NULL;
2521 }
2522
2523 void* file_data = IM_ALLOC(file_size + padding_bytes);
2524 if (file_data == NULL)
2525 {
2526 ImFileClose(f);
2527 return NULL;
2528 }
2529 if (ImFileRead(file_data, 1, file_size, f) != file_size)
2530 {
2531 ImFileClose(f);
2532 IM_FREE(file_data);
2533 return NULL;
2534 }
2535 if (padding_bytes > 0)
2536 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2537
2538 ImFileClose(f);
2539 if (out_file_size)
2540 *out_file_size = file_size;
2541
2542 return file_data;
2543 }
2544
2545 //-----------------------------------------------------------------------------
2546 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2547 //-----------------------------------------------------------------------------
2548
2549 IM_MSVC_RUNTIME_CHECKS_OFF
2550
2551 // Convert UTF-8 to 32-bit character, process single character input.
2552 // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2553 // We handle UTF-8 decoding error by skipping forward.
2554 int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2555 {
2556 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 };
2557 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2558 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2559 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2560 static const int shifte[] = { 0, 6, 4, 2, 0 };
2561 int len = lengths[*(const unsigned char*)in_text >> 3];
2562 int wanted = len + (len ? 0 : 1);
2563
2564 if (in_text_end == NULL)
2565 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2566
2567 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2568 // so it is fast even with excessive branching.
2569 unsigned char s[4];
2570 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2571 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2572 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2573 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2574
2575 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2576 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2577 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2578 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2579 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2580 *out_char >>= shiftc[len];
2581
2582 // Accumulate the various error conditions.
2583 int e = 0;
2584 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2585 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2586 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve)
2587 e |= (s[1] & 0xc0) >> 2;
2588 e |= (s[2] & 0xc0) >> 4;
2589 e |= (s[3] ) >> 6;
2590 e ^= 0x2a; // top two bits of each tail byte correct?
2591 e >>= shifte[len];
2592
2593 if (e)
2594 {
2595 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2596 // One byte is consumed in case of invalid first byte of in_text.
2597 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2598 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2599 wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2600 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2601 }
2602
2603 return wanted;
2604 }
2605
2606 int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2607 {
2608 ImWchar* buf_out = buf;
2609 ImWchar* buf_end = buf + buf_size;
2610 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2611 {
2612 unsigned int c;
2613 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2614 *buf_out++ = (ImWchar)c;
2615 }
2616 *buf_out = 0;
2617 if (in_text_remaining)
2618 *in_text_remaining = in_text;
2619 return (int)(buf_out - buf);
2620 }
2621
2622 int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2623 {
2624 int char_count = 0;
2625 while ((!in_text_end || in_text < in_text_end) && *in_text)
2626 {
2627 unsigned int c;
2628 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2629 char_count++;
2630 }
2631 return char_count;
2632 }
2633
2634 // Based on stb_to_utf8() from github.com/nothings/stb/
2635 static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2636 {
2637 if (c < 0x80)
2638 {
2639 buf[0] = (char)c;
2640 return 1;
2641 }
2642 if (c < 0x800)
2643 {
2644 if (buf_size < 2) return 0;
2645 buf[0] = (char)(0xc0 + (c >> 6));
2646 buf[1] = (char)(0x80 + (c & 0x3f));
2647 return 2;
2648 }
2649 if (c < 0x10000)
2650 {
2651 if (buf_size < 3) return 0;
2652 buf[0] = (char)(0xe0 + (c >> 12));
2653 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2654 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2655 return 3;
2656 }
2657 if (c <= 0x10FFFF)
2658 {
2659 if (buf_size < 4) return 0;
2660 buf[0] = (char)(0xf0 + (c >> 18));
2661 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2662 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2663 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2664 return 4;
2665 }
2666 // Invalid code point, the max unicode is 0x10FFFF
2667 return 0;
2668 }
2669
2670 int ImTextCharToUtf8(char out_buf[5], unsigned int c)
2671 {
2672 int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2673 out_buf[count] = 0;
2674 return count;
2675 }
2676
2677 // Not optimal but we very rarely use this function.
2678 int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2679 {
2680 unsigned int unused = 0;
2681 return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2682 }
2683
2684 static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2685 {
2686 if (c < 0x80) return 1;
2687 if (c < 0x800) return 2;
2688 if (c < 0x10000) return 3;
2689 if (c <= 0x10FFFF) return 4;
2690 return 3;
2691 }
2692
2693 int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2694 {
2695 char* buf_p = out_buf;
2696 const char* buf_end = out_buf + out_buf_size;
2697 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2698 {
2699 unsigned int c = (unsigned int)(*in_text++);
2700 if (c < 0x80)
2701 *buf_p++ = (char)c;
2702 else
2703 buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2704 }
2705 *buf_p = 0;
2706 return (int)(buf_p - out_buf);
2707 }
2708
2709 int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2710 {
2711 int bytes_count = 0;
2712 while ((!in_text_end || in_text < in_text_end) && *in_text)
2713 {
2714 unsigned int c = (unsigned int)(*in_text++);
2715 if (c < 0x80)
2716 bytes_count++;
2717 else
2718 bytes_count += ImTextCountUtf8BytesFromChar(c);
2719 }
2720 return bytes_count;
2721 }
2722
2723 const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2724 {
2725 while (in_text_curr > in_text_start)
2726 {
2727 in_text_curr--;
2728 if ((*in_text_curr & 0xC0) != 0x80)
2729 return in_text_curr;
2730 }
2731 return in_text_start;
2732 }
2733
2734 int ImTextCountLines(const char* in_text, const char* in_text_end)
2735 {
2736 if (in_text_end == NULL)
2737 in_text_end = in_text + ImStrlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2738 int count = 0;
2739 while (in_text < in_text_end)
2740 {
2741 const char* line_end = (const char*)ImMemchr(in_text, '\n', in_text_end - in_text);
2742 in_text = line_end ? line_end + 1 : in_text_end;
2743 count++;
2744 }
2745 return count;
2746 }
2747
2748 IM_MSVC_RUNTIME_CHECKS_RESTORE
2749
2750 //-----------------------------------------------------------------------------
2751 // [SECTION] MISC HELPERS/UTILITIES (Color functions)
2752 // Note: The Convert functions are early design which are not consistent with other API.
2753 //-----------------------------------------------------------------------------
2754
2755 IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2756 {
2757 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2758 int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2759 int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2760 int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2761 return IM_COL32(r, g, b, 0xFF);
2762 }
2763
2764 ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2765 {
2766 float s = 1.0f / 255.0f;
2767 return ImVec4(
2768 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2769 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2770 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2771 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2772 }
2773
2774 ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2775 {
2776 ImU32 out;
2777 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2778 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2779 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2780 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2781 return out;
2782 }
2783
2784 // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2785 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2786 void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2787 {
2788 float K = 0.f;
2789 if (g < b)
2790 {
2791 ImSwap(g, b);
2792 K = -1.f;
2793 }
2794 if (r < g)
2795 {
2796 ImSwap(r, g);
2797 K = -2.f / 6.f - K;
2798 }
2799
2800 const float chroma = r - (g < b ? g : b);
2801 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2802 out_s = chroma / (r + 1e-20f);
2803 out_v = r;
2804 }
2805
2806 // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2807 // also http://en.wikipedia.org/wiki/HSL_and_HSV
2808 void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2809 {
2810 if (s == 0.0f)
2811 {
2812 // gray
2813 out_r = out_g = out_b = v;
2814 return;
2815 }
2816
2817 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2818 int i = (int)h;
2819 float f = h - (float)i;
2820 float p = v * (1.0f - s);
2821 float q = v * (1.0f - s * f);
2822 float t = v * (1.0f - s * (1.0f - f));
2823
2824 switch (i)
2825 {
2826 case 0: out_r = v; out_g = t; out_b = p; break;
2827 case 1: out_r = q; out_g = v; out_b = p; break;
2828 case 2: out_r = p; out_g = v; out_b = t; break;
2829 case 3: out_r = p; out_g = q; out_b = v; break;
2830 case 4: out_r = t; out_g = p; out_b = v; break;
2831 case 5: default: out_r = v; out_g = p; out_b = q; break;
2832 }
2833 }
2834
2835 //-----------------------------------------------------------------------------
2836 // [SECTION] ImGuiStorage
2837 // Helper: Key->value storage
2838 //-----------------------------------------------------------------------------
2839
2840 // std::lower_bound but without the bullshit
2841 ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2842 {
2843 ImGuiStoragePair* in_p = in_begin;
2844 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2845 {
2846 size_t count2 = count >> 1;
2847 ImGuiStoragePair* mid = in_p + count2;
2848 if (mid->key < key)
2849 {
2850 in_p = ++mid;
2851 count -= count2 + 1;
2852 }
2853 else
2854 {
2855 count = count2;
2856 }
2857 }
2858 return in_p;
2859 }
2860
2861 IM_MSVC_RUNTIME_CHECKS_OFF
2862 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2863 {
2864 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2865 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2866 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2867 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2868 }
2869
2870 // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2871 void ImGuiStorage::BuildSortByKey()
2872 {
2873 ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2874 }
2875
2876 int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2877 {
2878 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2879 if (it == Data.Data + Data.Size || it->key != key)
2880 return default_val;
2881 return it->val_i;
2882 }
2883
2884 bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2885 {
2886 return GetInt(key, default_val ? 1 : 0) != 0;
2887 }
2888
2889 float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2890 {
2891 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2892 if (it == Data.Data + Data.Size || it->key != key)
2893 return default_val;
2894 return it->val_f;
2895 }
2896
2897 void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2898 {
2899 ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2900 if (it == Data.Data + Data.Size || it->key != key)
2901 return NULL;
2902 return it->val_p;
2903 }
2904
2905 // 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.
2906 int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2907 {
2908 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2909 if (it == Data.Data + Data.Size || it->key != key)
2910 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2911 return &it->val_i;
2912 }
2913
2914 bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2915 {
2916 return (bool*)GetIntRef(key, default_val ? 1 : 0);
2917 }
2918
2919 float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2920 {
2921 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2922 if (it == Data.Data + Data.Size || it->key != key)
2923 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2924 return &it->val_f;
2925 }
2926
2927 void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2928 {
2929 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2930 if (it == Data.Data + Data.Size || it->key != key)
2931 it = Data.insert(it, ImGuiStoragePair(key, default_val));
2932 return &it->val_p;
2933 }
2934
2935 // 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)
2936 void ImGuiStorage::SetInt(ImGuiID key, int val)
2937 {
2938 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2939 if (it == Data.Data + Data.Size || it->key != key)
2940 Data.insert(it, ImGuiStoragePair(key, val));
2941 else
2942 it->val_i = val;
2943 }
2944
2945 void ImGuiStorage::SetBool(ImGuiID key, bool val)
2946 {
2947 SetInt(key, val ? 1 : 0);
2948 }
2949
2950 void ImGuiStorage::SetFloat(ImGuiID key, float val)
2951 {
2952 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2953 if (it == Data.Data + Data.Size || it->key != key)
2954 Data.insert(it, ImGuiStoragePair(key, val));
2955 else
2956 it->val_f = val;
2957 }
2958
2959 void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2960 {
2961 ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2962 if (it == Data.Data + Data.Size || it->key != key)
2963 Data.insert(it, ImGuiStoragePair(key, val));
2964 else
2965 it->val_p = val;
2966 }
2967
2968 void ImGuiStorage::SetAllInt(int v)
2969 {
2970 for (int i = 0; i < Data.Size; i++)
2971 Data[i].val_i = v;
2972 }
2973 IM_MSVC_RUNTIME_CHECKS_RESTORE
2974
2975 //-----------------------------------------------------------------------------
2976 // [SECTION] ImGuiTextFilter
2977 //-----------------------------------------------------------------------------
2978
2979 // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2980 ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2981 {
2982 InputBuf[0] = 0;
2983 CountGrep = 0;
2984 if (default_filter)
2985 {
2986 ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2987 Build();
2988 }
2989 }
2990
2991 bool ImGuiTextFilter::Draw(const char* label, float width)
2992 {
2993 if (width != 0.0f)
2994 ImGui::SetNextItemWidth(width);
2995 bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2996 if (value_changed)
2997 Build();
2998 return value_changed;
2999 }
3000
3001 void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
3002 {
3003 out->resize(0);
3004 const char* wb = b;
3005 const char* we = wb;
3006 while (we < e)
3007 {
3008 if (*we == separator)
3009 {
3010 out->push_back(ImGuiTextRange(wb, we));
3011 wb = we + 1;
3012 }
3013 we++;
3014 }
3015 if (wb != we)
3016 out->push_back(ImGuiTextRange(wb, we));
3017 }
3018
3019 void ImGuiTextFilter::Build()
3020 {
3021 Filters.resize(0);
3022 ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf));
3023 input_range.split(',', &Filters);
3024
3025 CountGrep = 0;
3026 for (ImGuiTextRange& f : Filters)
3027 {
3028 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
3029 f.b++;
3030 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
3031 f.e--;
3032 if (f.empty())
3033 continue;
3034 if (f.b[0] != '-')
3035 CountGrep += 1;
3036 }
3037 }
3038
3039 bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
3040 {
3041 if (Filters.Size == 0)
3042 return true;
3043
3044 if (text == NULL)
3045 text = text_end = "";
3046
3047 for (const ImGuiTextRange& f : Filters)
3048 {
3049 if (f.b == f.e)
3050 continue;
3051 if (f.b[0] == '-')
3052 {
3053 // Subtract
3054 if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
3055 return false;
3056 }
3057 else
3058 {
3059 // Grep
3060 if (ImStristr(text, text_end, f.b, f.e) != NULL)
3061 return true;
3062 }
3063 }
3064
3065 // Implicit * grep
3066 if (CountGrep == 0)
3067 return true;
3068
3069 return false;
3070 }
3071
3072 //-----------------------------------------------------------------------------
3073 // [SECTION] ImGuiTextBuffer, ImGuiTextIndex
3074 //-----------------------------------------------------------------------------
3075
3076 // On some platform vsnprintf() takes va_list by reference and modifies it.
3077 // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
3078 #ifndef va_copy
3079 #if defined(__GNUC__) || defined(__clang__)
3080 #define va_copy(dest, src) __builtin_va_copy(dest, src)
3081 #else
3082 #define va_copy(dest, src) (dest = src)
3083 #endif
3084 #endif
3085
3086 char ImGuiTextBuffer::EmptyString[1] = { 0 };
3087
3088 void ImGuiTextBuffer::append(const char* str, const char* str_end)
3089 {
3090 int len = str_end ? (int)(str_end - str) : (int)ImStrlen(str);
3091
3092 // Add zero-terminator the first time
3093 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3094 const int needed_sz = write_off + len;
3095 if (write_off + len >= Buf.Capacity)
3096 {
3097 int new_capacity = Buf.Capacity * 2;
3098 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
3099 }
3100
3101 Buf.resize(needed_sz);
3102 memcpy(&Buf[write_off - 1], str, (size_t)len);
3103 Buf[write_off - 1 + len] = 0;
3104 }
3105
3106 void ImGuiTextBuffer::appendf(const char* fmt, ...)
3107 {
3108 va_list args;
3109 va_start(args, fmt);
3110 appendfv(fmt, args);
3111 va_end(args);
3112 }
3113
3114 // Helper: Text buffer for logging/accumulating text
3115 void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
3116 {
3117 va_list args_copy;
3118 va_copy(args_copy, args);
3119
3120 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
3121 if (len <= 0)
3122 {
3123 va_end(args_copy);
3124 return;
3125 }
3126
3127 // Add zero-terminator the first time
3128 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3129 const int needed_sz = write_off + len;
3130 if (write_off + len >= Buf.Capacity)
3131 {
3132 int new_capacity = Buf.Capacity * 2;
3133 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
3134 }
3135
3136 Buf.resize(needed_sz);
3137 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
3138 va_end(args_copy);
3139 }
3140
3141 void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
3142 {
3143 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
3144 if (old_size == new_size)
3145 return;
3146 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
3147 LineOffsets.push_back(EndOffset);
3148 const char* base_end = base + new_size;
3149 for (const char* p = base + old_size; (p = (const char*)ImMemchr(p, '\n', base_end - p)) != 0; )
3150 if (++p < base_end) // Don't push a trailing offset on last \n
3151 LineOffsets.push_back((int)(intptr_t)(p - base));
3152 EndOffset = ImMax(EndOffset, new_size);
3153 }
3154
3155 //-----------------------------------------------------------------------------
3156 // [SECTION] ImGuiListClipper
3157 //-----------------------------------------------------------------------------
3158
3159 // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
3160 // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
3161 static bool GetSkipItemForListClipping()
3162 {
3163 ImGuiContext& g = *GImGui;
3164 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
3165 }
3166
3167 static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
3168 {
3169 if (ranges.Size - offset <= 1)
3170 return;
3171
3172 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
3173 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
3174 for (int i = offset; i < sort_end + offset; ++i)
3175 if (ranges[i].Min > ranges[i + 1].Min)
3176 ImSwap(ranges[i], ranges[i + 1]);
3177
3178 // Now fuse ranges together as much as possible.
3179 for (int i = 1 + offset; i < ranges.Size; i++)
3180 {
3181 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
3182 if (ranges[i - 1].Max < ranges[i].Min)
3183 continue;
3184 ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
3185 ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
3186 ranges.erase(ranges.Data + i);
3187 i--;
3188 }
3189 }
3190
3191 static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
3192 {
3193 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
3194 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
3195 // 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?
3196 ImGuiContext& g = *GImGui;
3197 ImGuiWindow* window = g.CurrentWindow;
3198 float off_y = pos_y - window->DC.CursorPos.y;
3199 window->DC.CursorPos.y = pos_y;
3200 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
3201 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.
3202 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.
3203 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
3204 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
3205 if (ImGuiTable* table = g.CurrentTable)
3206 {
3207 if (table->IsInsideRow)
3208 ImGui::TableEndRow(table);
3209 table->RowPosY2 = window->DC.CursorPos.y;
3210 const int row_increase = (int)((off_y / line_height) + 0.5f);
3211 table->CurrentRow += row_increase;
3212 table->RowBgColorCounter += row_increase;
3213 }
3214 }
3215
3216 ImGuiListClipper::ImGuiListClipper()
3217 {
3218 memset(this, 0, sizeof(*this));
3219 }
3220
3221 ImGuiListClipper::~ImGuiListClipper()
3222 {
3223 End();
3224 }
3225
3226 void ImGuiListClipper::Begin(int items_count, float items_height)
3227 {
3228 if (Ctx == NULL)
3229 Ctx = ImGui::GetCurrentContext();
3230
3231 ImGuiContext& g = *Ctx;
3232 ImGuiWindow* window = g.CurrentWindow;
3233 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3234
3235 if (ImGuiTable* table = g.CurrentTable)
3236 if (table->IsInsideRow)
3237 ImGui::TableEndRow(table);
3238
3239 StartPosY = window->DC.CursorPos.y;
3240 ItemsHeight = items_height;
3241 ItemsCount = items_count;
3242 DisplayStart = -1;
3243 DisplayEnd = 0;
3244
3245 // Acquire temporary buffer
3246 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3247 g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3248 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3249 data->Reset(this);
3250 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3251 TempData = data;
3252 StartSeekOffsetY = data->LossynessOffset;
3253 }
3254
3255 void ImGuiListClipper::End()
3256 {
3257 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3258 {
3259 // 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.
3260 ImGuiContext& g = *Ctx;
3261 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3262 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3263 SeekCursorForItem(ItemsCount);
3264
3265 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3266 IM_ASSERT(data->ListClipper == this);
3267 data->StepNo = data->Ranges.Size;
3268 if (--g.ClipperTempDataStacked > 0)
3269 {
3270 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3271 data->ListClipper->TempData = data;
3272 }
3273 TempData = NULL;
3274 }
3275 ItemsCount = -1;
3276 }
3277
3278 void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3279 {
3280 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3281 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3282 IM_ASSERT(item_begin <= item_end);
3283 if (item_begin < item_end)
3284 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3285 }
3286
3287 // This is already called while stepping.
3288 // 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.
3289 void ImGuiListClipper::SeekCursorForItem(int item_n)
3290 {
3291 // - Perform the add and multiply with double to allow seeking through larger ranges.
3292 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3293 // - 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.
3294 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3295 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight);
3296 }
3297
3298 static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3299 {
3300 ImGuiContext& g = *clipper->Ctx;
3301 ImGuiWindow* window = g.CurrentWindow;
3302 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3303 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3304
3305 ImGuiTable* table = g.CurrentTable;
3306 if (table && table->IsInsideRow)
3307 ImGui::TableEndRow(table);
3308
3309 // No items
3310 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3311 return false;
3312
3313 // While we are in frozen row state, keep displaying items one by one, unclipped
3314 // FIXME: Could be stored as a table-agnostic state.
3315 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3316 {
3317 clipper->DisplayStart = data->ItemsFrozen;
3318 clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3319 if (clipper->DisplayStart < clipper->DisplayEnd)
3320 data->ItemsFrozen++;
3321 return true;
3322 }
3323
3324 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3325 bool calc_clipping = false;
3326 if (data->StepNo == 0)
3327 {
3328 clipper->StartPosY = window->DC.CursorPos.y;
3329 if (clipper->ItemsHeight <= 0.0f)
3330 {
3331 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3332 data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3333 clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3334 clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3335 data->StepNo = 1;
3336 return true;
3337 }
3338 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3339 }
3340
3341 // Step 1: Let the clipper infer height from first range
3342 if (clipper->ItemsHeight <= 0.0f)
3343 {
3344 IM_ASSERT(data->StepNo == 1);
3345 if (table)
3346 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3347
3348 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3349 if (affected_by_floating_point_precision)
3350 {
3351 // Mitigation/hack for very large range: assume last time height constitute line height.
3352 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3353 window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight);
3354 }
3355 else
3356 {
3357 clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3358 }
3359 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3360 return false;
3361 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3362 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3363 }
3364
3365 // Step 0 or 1: Calculate the actual ranges of visible elements.
3366 const int already_submitted = clipper->DisplayEnd;
3367 if (calc_clipping)
3368 {
3369 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3370 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3371
3372 if (g.LogEnabled)
3373 {
3374 // If logging is active, do not perform any clipping
3375 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3376 }
3377 else
3378 {
3379 // Add range selected to be included for navigation
3380 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3381 if (is_nav_request)
3382 {
3383 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, 0, 0));
3384 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3385 }
3386 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3387 data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3388
3389 // Add focused/active item
3390 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3391 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3392 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3393
3394 // Add visible range
3395 float min_y = window->ClipRect.Min.y;
3396 float max_y = window->ClipRect.Max.y;
3397
3398 // Add box selection range
3399 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3400 if (bs->IsActive && bs->Window == window)
3401 {
3402 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3403 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3404 // As a workaround we currently half ItemSpacing worth on each side.
3405 min_y -= g.Style.ItemSpacing.y;
3406 max_y += g.Style.ItemSpacing.y;
3407
3408 // Box-select on 2D area requires different clipping.
3409 if (bs->UnclipMode)
3410 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
3411 }
3412
3413 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3414 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3415 data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
3416 }
3417
3418 // Convert position ranges to item index ranges
3419 // - 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.
3420 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3421 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3422 for (ImGuiListClipperRange& range : data->Ranges)
3423 if (range.PosToIndexConvert)
3424 {
3425 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3426 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3427 range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3428 range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3429 range.PosToIndexConvert = false;
3430 }
3431 ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3432 }
3433
3434 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3435 while (data->StepNo < data->Ranges.Size)
3436 {
3437 clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3438 clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3439 data->StepNo++;
3440 if (clipper->DisplayStart >= clipper->DisplayEnd)
3441 continue;
3442 if (clipper->DisplayStart > already_submitted)
3443 clipper->SeekCursorForItem(clipper->DisplayStart);
3444 return true;
3445 }
3446
3447 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3448 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3449 if (clipper->ItemsCount < INT_MAX)
3450 clipper->SeekCursorForItem(clipper->ItemsCount);
3451
3452 return false;
3453 }
3454
3455 bool ImGuiListClipper::Step()
3456 {
3457 ImGuiContext& g = *Ctx;
3458 bool need_items_height = (ItemsHeight <= 0.0f);
3459 bool ret = ImGuiListClipper_StepInternal(this);
3460 if (ret && (DisplayStart >= DisplayEnd))
3461 ret = false;
3462 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3463 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3464 if (need_items_height && ItemsHeight > 0.0f)
3465 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3466 if (ret)
3467 {
3468 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3469 }
3470 else
3471 {
3472 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3473 End();
3474 }
3475 return ret;
3476 }
3477
3478 //-----------------------------------------------------------------------------
3479 // [SECTION] STYLING
3480 //-----------------------------------------------------------------------------
3481
3482 ImGuiStyle& ImGui::GetStyle()
3483 {
3484 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3485 return GImGui->Style;
3486 }
3487
3488 ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3489 {
3490 ImGuiStyle& style = GImGui->Style;
3491 ImVec4 c = style.Colors[idx];
3492 c.w *= style.Alpha * alpha_mul;
3493 return ColorConvertFloat4ToU32(c);
3494 }
3495
3496 ImU32 ImGui::GetColorU32(const ImVec4& col)
3497 {
3498 ImGuiStyle& style = GImGui->Style;
3499 ImVec4 c = col;
3500 c.w *= style.Alpha;
3501 return ColorConvertFloat4ToU32(c);
3502 }
3503
3504 const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3505 {
3506 ImGuiStyle& style = GImGui->Style;
3507 return style.Colors[idx];
3508 }
3509
3510 ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3511 {
3512 ImGuiStyle& style = GImGui->Style;
3513 alpha_mul *= style.Alpha;
3514 if (alpha_mul >= 1.0f)
3515 return col;
3516 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3517 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3518 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3519 }
3520
3521 // 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
3522 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3523 {
3524 ImGuiContext& g = *GImGui;
3525 ImGuiColorMod backup;
3526 backup.Col = idx;
3527 backup.BackupValue = g.Style.Colors[idx];
3528 g.ColorStack.push_back(backup);
3529 if (g.DebugFlashStyleColorIdx != idx)
3530 g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3531 }
3532
3533 void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3534 {
3535 ImGuiContext& g = *GImGui;
3536 ImGuiColorMod backup;
3537 backup.Col = idx;
3538 backup.BackupValue = g.Style.Colors[idx];
3539 g.ColorStack.push_back(backup);
3540 if (g.DebugFlashStyleColorIdx != idx)
3541 g.Style.Colors[idx] = col;
3542 }
3543
3544 void ImGui::PopStyleColor(int count)
3545 {
3546 ImGuiContext& g = *GImGui;
3547 if (g.ColorStack.Size < count)
3548 {
3549 IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
3550 count = g.ColorStack.Size;
3551 }
3552 while (count > 0)
3553 {
3554 ImGuiColorMod& backup = g.ColorStack.back();
3555 g.Style.Colors[backup.Col] = backup.BackupValue;
3556 g.ColorStack.pop_back();
3557 count--;
3558 }
3559 }
3560
3561 static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3562 {
3563 ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3564 };
3565
3566 static const ImGuiStyleVarInfo GStyleVarsInfo[] =
3567 {
3568 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3569 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3570 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3571 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3572 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3573 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3574 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3575 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3576 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3577 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3578 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3579 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3580 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3581 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameShading) }, // tildearrow: ImGuiStyleVar_FrameShading
3582 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3583 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3584 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3585 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3586 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3587 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3588 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3589 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3590 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3591 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize
3592 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3593 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3594 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase
3595 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink
3596 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3597 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3598 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3599 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3600 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize
3601 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding
3602 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3603 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3604 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3605 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3606 { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3607 { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3608 };
3609
3610 const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3611 {
3612 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3613 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT);
3614 return &GStyleVarsInfo[idx];
3615 }
3616
3617 void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3618 {
3619 ImGuiContext& g = *GImGui;
3620 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3621 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1)
3622 {
3623 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3624 return;
3625 }
3626 float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3627 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3628 *pvar = val;
3629 }
3630
3631 void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
3632 {
3633 ImGuiContext& g = *GImGui;
3634 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3635 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3636 {
3637 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3638 return;
3639 }
3640 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3641 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3642 pvar->x = val_x;
3643 }
3644
3645 void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
3646 {
3647 ImGuiContext& g = *GImGui;
3648 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3649 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3650 {
3651 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3652 return;
3653 }
3654 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3655 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3656 pvar->y = val_y;
3657 }
3658
3659 void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3660 {
3661 ImGuiContext& g = *GImGui;
3662 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3663 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3664 {
3665 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3666 return;
3667 }
3668 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3669 g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3670 *pvar = val;
3671 }
3672
3673 void ImGui::PopStyleVar(int count)
3674 {
3675 ImGuiContext& g = *GImGui;
3676 if (g.StyleVarStack.Size < count)
3677 {
3678 IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
3679 count = g.StyleVarStack.Size;
3680 }
3681 while (count > 0)
3682 {
3683 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3684 ImGuiStyleMod& backup = g.StyleVarStack.back();
3685 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(backup.VarIdx);
3686 void* data = var_info->GetVarPtr(&g.Style);
3687 if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3688 else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3689 g.StyleVarStack.pop_back();
3690 count--;
3691 }
3692 }
3693
3694 const char* ImGui::GetStyleColorName(ImGuiCol idx)
3695 {
3696 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3697 switch (idx)
3698 {
3699 case ImGuiCol_Text: return "Text";
3700 case ImGuiCol_TextDisabled: return "TextDisabled";
3701 case ImGuiCol_WindowBg: return "WindowBg";
3702 case ImGuiCol_ChildBg: return "ChildBg";
3703 case ImGuiCol_PopupBg: return "PopupBg";
3704 case ImGuiCol_Border: return "Border";
3705 case ImGuiCol_BorderShadow: return "BorderShadow";
3706 case ImGuiCol_FrameBg: return "FrameBg";
3707 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3708 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3709 case ImGuiCol_TitleBg: return "TitleBg";
3710 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3711 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3712 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3713 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3714 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3715 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3716 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3717 case ImGuiCol_CheckMark: return "CheckMark";
3718 case ImGuiCol_SliderGrab: return "SliderGrab";
3719 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3720 case ImGuiCol_Button: return "Button";
3721 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3722 case ImGuiCol_ButtonActive: return "ButtonActive";
3723 case ImGuiCol_Header: return "Header";
3724 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3725 case ImGuiCol_HeaderActive: return "HeaderActive";
3726 case ImGuiCol_Separator: return "Separator";
3727 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3728 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3729 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3730 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3731 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3732 case ImGuiCol_InputTextCursor: return "InputTextCursor";
3733 case ImGuiCol_TabHovered: return "TabHovered";
3734 case ImGuiCol_Tab: return "Tab";
3735 case ImGuiCol_TabSelected: return "TabSelected";
3736 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3737 case ImGuiCol_TabDimmed: return "TabDimmed";
3738 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3739 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3740 case ImGuiCol_DockingPreview: return "DockingPreview";
3741 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3742 case ImGuiCol_PlotLines: return "PlotLines";
3743 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3744 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3745 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3746 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3747 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3748 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3749 case ImGuiCol_TableRowBg: return "TableRowBg";
3750 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3751 case ImGuiCol_TextLink: return "TextLink";
3752 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3753 case ImGuiCol_TreeLines: return "TreeLines";
3754 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3755 case ImGuiCol_NavCursor: return "NavCursor";
3756 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3757 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3758 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3759 }
3760 IM_ASSERT(0);
3761 return "Unknown";
3762 }
3763
3764 //-----------------------------------------------------------------------------
3765 // [SECTION] RENDER HELPERS
3766 // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3767 // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3768 // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3769 //-----------------------------------------------------------------------------
3770
3771 const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3772 {
3773 const char* text_display_end = text;
3774 if (!text_end)
3775 text_end = (const char*)-1;
3776
3777 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3778 text_display_end++;
3779 return text_display_end;
3780 }
3781
3782 const char* FindRenderedTextEndNoHashHide(const char* text, const char* text_end)
3783 {
3784 const char* text_display_end = text;
3785 if (!text_end)
3786 text_end = (const char*)-1;
3787
3788 while (text_display_end < text_end && *text_display_end != '\0')
3789 text_display_end++;
3790 return text_display_end;
3791 }
3792
3793 // Internal ImGui functions to render text
3794 // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3795 void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3796 {
3797 ImGuiContext& g = *GImGui;
3798 ImGuiWindow* window = g.CurrentWindow;
3799
3800 // Hide anything after a '##' string
3801 const char* text_display_end;
3802 if (hide_text_after_hash)
3803 {
3804 text_display_end = FindRenderedTextEnd(text, text_end);
3805 }
3806 else
3807 {
3808 if (!text_end)
3809 text_end = text + ImStrlen(text); // FIXME-OPT
3810 text_display_end = text_end;
3811 }
3812
3813 if (text != text_display_end)
3814 {
3815 if (hide_text_after_hash)
3816 {
3817 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3818 }
3819 else
3820 {
3821 window->DrawList->AddTextNoHashHide(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3822 }
3823 if (g.LogEnabled)
3824 LogRenderedText(&pos, text, text_display_end);
3825 }
3826 }
3827
3828 void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3829 {
3830 ImGuiContext& g = *GImGui;
3831 ImGuiWindow* window = g.CurrentWindow;
3832
3833 if (!text_end)
3834 text_end = text + ImStrlen(text); // FIXME-OPT
3835
3836 if (text != text_end)
3837 {
3838 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3839 if (g.LogEnabled)
3840 LogRenderedText(&pos, text, text_end);
3841 }
3842 }
3843
3844 void ImGui::RenderTextWrappedNoHashHide(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3845 {
3846 ImGuiContext& g = *GImGui;
3847 ImGuiWindow* window = g.CurrentWindow;
3848
3849 if (!text_end)
3850 text_end = text + strlen(text); // FIXME-OPT
3851
3852 if (text != text_end)
3853 {
3854 window->DrawList->AddTextNoHashHide(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3855 if (g.LogEnabled)
3856 LogRenderedText(&pos, text, text_end);
3857 }
3858 }
3859
3860 // Default clip_rect uses (pos_min,pos_max)
3861 // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3862 // FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList.
3863 // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3864 // better advantage of the render function taking size into account for coarse clipping.
3865 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, bool hide_after_hash)
3866 {
3867 // Perform CPU side clipping for single clipped element to avoid using scissor state
3868 ImVec2 pos = pos_min;
3869 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3870
3871 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3872 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3873 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3874 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3875 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3876
3877 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3878 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3879 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3880
3881 // Render
3882 if (need_clipping)
3883 {
3884 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3885 if (hide_after_hash) {
3886 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3887 } else {
3888 draw_list->AddTextNoHashHide(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3889 }
3890 }
3891 else
3892 {
3893 if (hide_after_hash) {
3894 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3895 } else {
3896 draw_list->AddTextNoHashHide(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3897 }
3898 }
3899 }
3900
3901 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)
3902 {
3903 // Hide anything after a '##' string
3904 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3905 const int text_len = (int)(text_display_end - text);
3906 if (text_len == 0)
3907 return;
3908
3909 ImGuiContext& g = *GImGui;
3910 ImGuiWindow* window = g.CurrentWindow;
3911 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3912 if (g.LogEnabled)
3913 LogRenderedText(&pos_min, text, text_display_end);
3914 }
3915
3916 void ImGui::RenderTextClippedNoHashHide(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)
3917 {
3918 // Do not hide anything after a '##' string
3919 const char* text_display_end = text_end;
3920 const int text_len = (int)(text_display_end - text);
3921 if (text_len == 0)
3922 return;
3923
3924 ImGuiContext& g = *GImGui;
3925 ImGuiWindow* window = g.CurrentWindow;
3926 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect, false);
3927 if (g.LogEnabled)
3928 LogRenderedText(&pos_min, text, text_display_end);
3929 }
3930
3931 // Another overly complex function until we reorganize everything into a nice all-in-one helper.
3932 // 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.
3933 // 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.
3934 // (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.
3935 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)
3936 {
3937 ImGuiContext& g = *GImGui;
3938 if (text_end_full == NULL)
3939 text_end_full = FindRenderedTextEnd(text);
3940 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3941
3942 //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));
3943 //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));
3944
3945 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3946 if (text_size.x > pos_max.x - pos_min.x)
3947 {
3948 // Hello wo...
3949 // | | |
3950 // min max ellipsis_max
3951 // <-> this is generally some padding value
3952
3953 ImFont* font = draw_list->_Data->Font;
3954 const float font_size = draw_list->_Data->FontSize;
3955 const float font_scale = draw_list->_Data->FontScale;
3956 const char* text_end_ellipsis = NULL;
3957 ImFontBaked* baked = font->GetFontBaked(font_size);
3958 const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale;
3959
3960 // We can now claim the space between pos_max.x and ellipsis_max.x
3961 const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3962 float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3963 while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3964 {
3965 // 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)
3966 text_end_ellipsis--;
3967 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
3968 }
3969
3970 // Render text, render ellipsis
3971 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3972 ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y);
3973 ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3974 font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect);
3975 }
3976 else
3977 {
3978 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3979 }
3980
3981 if (g.LogEnabled)
3982 LogRenderedText(&pos_min, text, text_end_full);
3983 }
3984
3985 // Render a rectangle shaped with optional rounding and borders
3986 void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding)
3987 {
3988 ImGuiContext& g = *GImGui;
3989 ImGuiWindow* window = g.CurrentWindow;
3990 if (g.Style.FrameShading>0.0f) {
3991 ImVec4 fill_colPre=ImGui::ColorConvertU32ToFloat4(fill_col);
3992 fill_colPre.w*=1.0f-g.Style.FrameShading;
3993 ImU32 fill_col1=ImGui::ColorConvertFloat4ToU32(fill_colPre);
3994 window->DrawList->AddRectFilledMultiColor(p_min, p_max, fill_col, fill_col, fill_col1, fill_col1, rounding);
3995 } else {
3996 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3997 }
3998 const float border_size = g.Style.FrameBorderSize;
3999 if (borders && border_size > 0.0f)
4000 {
4001 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
4002 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
4003 }
4004 }
4005
4006 // MODIFIED: Render a rectangle shaped with optional rounding and borders on DrawList
4007 void ImGui::RenderFrameDrawList(ImDrawList* dl, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
4008 {
4009 ImGuiContext& g = *GImGui;
4010 if (g.Style.FrameShading>0.0f) {
4011 ImVec4 fill_colPre=ImGui::ColorConvertU32ToFloat4(fill_col);
4012 fill_colPre.w*=1.0f-g.Style.FrameShading;
4013 ImU32 fill_col1=ImGui::ColorConvertFloat4ToU32(fill_colPre);
4014 dl->AddRectFilledMultiColor(p_min, p_max, fill_col, fill_col, fill_col1, fill_col1, rounding);
4015 } else {
4016 dl->AddRectFilled(p_min, p_max, fill_col, rounding);
4017 }
4018 const float border_size = g.Style.FrameBorderSize;
4019 if (border && border_size > 0.0f)
4020 {
4021 dl->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
4022 dl->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
4023 }
4024 }
4025
4026 void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
4027 {
4028 ImGuiContext& g = *GImGui;
4029 ImGuiWindow* window = g.CurrentWindow;
4030 const float border_size = g.Style.FrameBorderSize;
4031 if (border_size > 0.0f)
4032 {
4033 window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
4034 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
4035 }
4036 }
4037
4038 void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags)
4039 {
4040 ImGuiContext& g = *GImGui;
4041 if (id != g.NavId)
4042 return;
4043 if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
4044 return;
4045 if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
4046 return;
4047 ImGuiWindow* window = g.CurrentWindow;
4048 if (window->DC.NavHideHighlightOneFrame)
4049 return;
4050
4051 float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
4052 ImRect display_rect = bb;
4053 display_rect.ClipWith(window->ClipRect);
4054 const float thickness = 2.0f;
4055 if (flags & ImGuiNavRenderCursorFlags_Compact)
4056 {
4057 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
4058 }
4059 else
4060 {
4061 const float distance = 3.0f + thickness * 0.5f;
4062 display_rect.Expand(ImVec2(distance, distance));
4063 bool fully_visible = window->ClipRect.Contains(display_rect);
4064 if (!fully_visible)
4065 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
4066 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
4067 if (!fully_visible)
4068 window->DrawList->PopClipRect();
4069 }
4070 }
4071
4072 void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
4073 {
4074 ImGuiContext& g = *GImGui;
4075 if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
4076 mouse_cursor = ImGuiMouseCursor_Arrow;
4077 ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas;
4078 for (ImGuiViewportP* viewport : g.Viewports)
4079 {
4080 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
4081 ImVec2 offset, size, uv[4];
4082 if (!ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, &offset, &size, &uv[0], &uv[2]))
4083 continue;
4084 const ImVec2 pos = base_pos - offset;
4085 const float scale = base_scale * viewport->DpiScale;
4086 if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
4087 continue;
4088 ImDrawList* draw_list = GetForegroundDrawList(viewport);
4089 ImTextureRef tex_ref = font_atlas->TexRef;
4090 draw_list->PushTexture(tex_ref);
4091 draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
4092 draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
4093 draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border);
4094 draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill);
4095 if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress)
4096 {
4097 float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI);
4098 float a_max = a_min + IM_PI * 1.65f;
4099 draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max);
4100 draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale);
4101 }
4102 draw_list->PopTexture();
4103 }
4104 }
4105
4106 //-----------------------------------------------------------------------------
4107 // [SECTION] INITIALIZATION, SHUTDOWN
4108 //-----------------------------------------------------------------------------
4109
4110 // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
4111 // 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
4112 ImGuiContext* ImGui::GetCurrentContext()
4113 {
4114 return GImGui;
4115 }
4116
4117 void ImGui::SetCurrentContext(ImGuiContext* ctx)
4118 {
4119 #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
4120 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
4121 #else
4122 GImGui = ctx;
4123 #endif
4124 }
4125
4126 void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
4127 {
4128 GImAllocatorAllocFunc = alloc_func;
4129 GImAllocatorFreeFunc = free_func;
4130 GImAllocatorUserData = user_data;
4131 }
4132
4133 // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
4134 void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
4135 {
4136 *p_alloc_func = GImAllocatorAllocFunc;
4137 *p_free_func = GImAllocatorFreeFunc;
4138 *p_user_data = GImAllocatorUserData;
4139 }
4140
4141 ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
4142 {
4143 ImGuiContext* prev_ctx = GetCurrentContext();
4144 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
4145 SetCurrentContext(ctx);
4146 Initialize();
4147 if (prev_ctx != NULL)
4148 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
4149 return ctx;
4150 }
4151
4152 void ImGui::DestroyContext(ImGuiContext* ctx)
4153 {
4154 ImGuiContext* prev_ctx = GetCurrentContext();
4155 if (ctx == NULL) //-V1051
4156 ctx = prev_ctx;
4157 SetCurrentContext(ctx);
4158 Shutdown();
4159 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
4160 IM_DELETE(ctx);
4161 }
4162
4163 // IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation.
4164 static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
4165 {
4166 { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
4167 { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" },
4168 { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" },
4169 { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" },
4170 { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" },
4171 { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" },
4172 { ImGuiLocKey_WindowingPopup, "(Popup)" },
4173 { ImGuiLocKey_WindowingUntitled, "(Untitled)" },
4174 { ImGuiLocKey_OpenLink_s, "Open '%s'" },
4175 { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" },
4176 { ImGuiLocKey_DockingHideTabBar, "Hide tab bar###HideTabBar" },
4177 { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window." },
4178 { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node." },
4179 };
4180
4181 ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
4182 {
4183 IO.Ctx = this;
4184 InputTextState.Ctx = this;
4185
4186 Initialized = false;
4187 ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None;
4188
4189 Font = NULL;
4190 FontBaked = NULL;
4191 FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f;
4192 FontRasterizerDensity = 1.0f;
4193 IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
4194 if (shared_font_atlas == NULL)
4195 IO.Fonts->OwnerContext = this;
4196 Time = 0.0f;
4197 FrameCount = 0;
4198 FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1;
4199 WithinEndChildID = 0;
4200 WithinFrameScope = WithinFrameScopeWithImplicitWindow = false;
4201 GcCompactAll = false;
4202 TestEngineHookItems = false;
4203 TestEngine = NULL;
4204 memset(ContextName, 0, sizeof(ContextName));
4205
4206 InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
4207 InputEventsNextEventId = 1;
4208
4209 WindowsActiveCount = 0;
4210 WindowsBorderHoverPadding = 0.0f;
4211 CurrentWindow = NULL;
4212 HoveredWindow = NULL;
4213 HoveredWindowUnderMovingWindow = NULL;
4214 HoveredWindowBeforeClear = NULL;
4215 MovingWindow = NULL;
4216 WheelingWindow = NULL;
4217 WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
4218 WheelingWindowReleaseTimer = 0.0f;
4219
4220 DebugDrawIdConflictsId = 0;
4221 DebugHookIdInfo = 0;
4222 HoveredId = HoveredIdPreviousFrame = 0;
4223 HoveredIdPreviousFrameItemCount = 0;
4224 HoveredIdAllowOverlap = false;
4225 HoveredIdIsDisabled = false;
4226 HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
4227 ItemUnclipByLog = false;
4228 ActiveId = 0;
4229 ActiveIdIsAlive = 0;
4230 ActiveIdTimer = 0.0f;
4231 ActiveIdIsJustActivated = false;
4232 ActiveIdAllowOverlap = false;
4233 ActiveIdNoClearOnFocusLoss = false;
4234 ActiveIdHasBeenPressedBefore = false;
4235 ActiveIdHasBeenEditedBefore = false;
4236 ActiveIdHasBeenEditedThisFrame = false;
4237 ActiveIdFromShortcut = false;
4238 ActiveIdClickOffset = ImVec2(-1, -1);
4239 ActiveIdWindow = NULL;
4240 ActiveIdSource = ImGuiInputSource_None;
4241 ActiveIdDisabledId = 0;
4242 ActiveIdMouseButton = -1;
4243 ActiveIdPreviousFrame = 0;
4244 memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData));
4245 memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation));
4246 LastActiveId = 0;
4247 LastActiveIdTimer = 0.0f;
4248
4249 LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
4250
4251 ActiveIdUsingNavDirMask = 0x00;
4252 ActiveIdUsingAllKeyboardKeys = false;
4253
4254 CurrentFocusScopeId = 0;
4255 CurrentItemFlags = ImGuiItemFlags_None;
4256 DebugShowGroupRects = false;
4257
4258 CurrentViewport = NULL;
4259 MouseViewport = MouseLastHoveredViewport = NULL;
4260 PlatformLastFocusedViewportId = 0;
4261 ViewportCreatedCount = PlatformWindowsCreatedCount = 0;
4262 ViewportFocusedStampCount = 0;
4263
4264 NavCursorVisible = false;
4265 NavHighlightItemUnderNav = false;
4266 NavMousePosDirty = false;
4267 NavIdIsAlive = false;
4268 NavId = 0;
4269 NavWindow = NULL;
4270 NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
4271 NavLayer = ImGuiNavLayer_Main;
4272 NavNextActivateId = 0;
4273 NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
4274 NavHighlightActivatedId = 0;
4275 NavHighlightActivatedTimer = 0.0f;
4276 NavInputSource = ImGuiInputSource_Keyboard;
4277 NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
4278 NavCursorHideFrames = 0;
4279
4280 NavAnyRequest = false;
4281 NavInitRequest = false;
4282 NavInitRequestFromMove = false;
4283 NavMoveSubmitted = false;
4284 NavMoveScoringItems = false;
4285 NavMoveForwardToNextFrame = false;
4286 NavMoveFlags = ImGuiNavMoveFlags_None;
4287 NavMoveScrollFlags = ImGuiScrollFlags_None;
4288 NavMoveKeyMods = ImGuiMod_None;
4289 NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
4290 NavScoringDebugCount = 0;
4291 NavTabbingDir = 0;
4292 NavTabbingCounter = 0;
4293
4294 NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
4295 NavJustMovedToKeyMods = ImGuiMod_None;
4296 NavJustMovedToIsTabbing = false;
4297 NavJustMovedToHasSelectionData = false;
4298
4299 // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
4300 // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
4301 ConfigNavWindowingWithGamepad = true;
4302 ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
4303 ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
4304 NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
4305 NavWindowingInputSource = ImGuiInputSource_None;
4306 NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
4307 NavWindowingToggleLayer = false;
4308 NavWindowingToggleKey = ImGuiKey_None;
4309
4310 InertialScrollInhibited = false;
4311
4312 DimBgRatio = 0.0f;
4313
4314 DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
4315 DragDropSourceFlags = ImGuiDragDropFlags_None;
4316 DragDropSourceFrameCount = -1;
4317 DragDropMouseButton = -1;
4318 DragDropTargetId = 0;
4319 DragDropAcceptFlags = ImGuiDragDropFlags_None;
4320 DragDropAcceptIdCurrRectSurface = 0.0f;
4321 DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
4322 DragDropAcceptFrameCount = -1;
4323 DragDropHoldJustPressedId = 0;
4324 memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
4325
4326 ClipperTempDataStacked = 0;
4327
4328 CurrentTable = NULL;
4329 TablesTempDataStacked = 0;
4330 CurrentTabBar = NULL;
4331 CurrentMultiSelect = NULL;
4332 MultiSelectTempDataStacked = 0;
4333
4334 HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
4335 HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
4336
4337 MouseCursor = ImGuiMouseCursor_Arrow;
4338 MouseStationaryTimer = 0.0f;
4339
4340 InputTextPasswordFontBackupFlags = ImFontFlags_None;
4341 TempInputId = 0;
4342 memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
4343 BeginMenuDepth = BeginComboDepth = 0;
4344 ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
4345 ColorEditCurrentID = ColorEditSavedID = 0;
4346 ColorEditSavedHue = ColorEditSavedSat = 0.0f;
4347 ColorEditSavedColor = 0;
4348 WindowResizeRelativeMode = false;
4349 ScrollbarSeekMode = 0;
4350 ScrollbarClickDeltaToGrabCenter = 0.0f;
4351 SliderGrabClickOffset = 0.0f;
4352 SliderCurrentAccum = 0.0f;
4353 SliderCurrentAccumDirty = false;
4354 DragCurrentAccumDirty = false;
4355 DragCurrentAccum = 0.0f;
4356 DragSpeedDefaultRatio = 1.0f / 100.0f;
4357 DisabledAlphaBackup = 0.0f;
4358 DisabledStackSize = 0;
4359 TooltipOverrideCount = 0;
4360 TooltipPreviousWindow = NULL;
4361
4362 PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
4363 PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
4364
4365 DockNodeWindowMenuHandler = NULL;
4366
4367 SettingsLoaded = false;
4368 SettingsDirtyTimer = 0.0f;
4369 HookIdNext = 0;
4370
4371 memset(LocalizationTable, 0, sizeof(LocalizationTable));
4372
4373 LogEnabled = false;
4374 LogFlags = ImGuiLogFlags_None;
4375 LogWindow = NULL;
4376 LogNextPrefix = LogNextSuffix = NULL;
4377 LogFile = NULL;
4378 LogLinePosY = FLT_MAX;
4379 LogLineFirstItem = false;
4380 LogDepthRef = 0;
4381 LogDepthToExpand = LogDepthToExpandDefault = 2;
4382
4383 ErrorCallback = NULL;
4384 ErrorCallbackUserData = NULL;
4385 ErrorFirst = true;
4386 ErrorCountCurrentFrame = 0;
4387 StackSizesInBeginForCurrentWindow = NULL;
4388
4389 DebugDrawIdConflictsCount = 0;
4390 DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
4391 DebugLocateId = 0;
4392 DebugLogSkippedErrors = 0;
4393 DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4394 DebugLogAutoDisableFrames = 0;
4395 DebugLocateFrames = 0;
4396 DebugBeginReturnValueCullDepth = -1;
4397 DebugItemPickerActive = false;
4398 DebugItemPickerMouseButton = ImGuiMouseButton_Left;
4399 DebugItemPickerBreakId = 0;
4400 DebugFlashStyleColorTime = 0.0f;
4401 DebugFlashStyleColorIdx = ImGuiCol_COUNT;
4402 DebugHoveredDockNode = NULL;
4403
4404 // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
4405 DebugBreakInWindow = 0;
4406 DebugBreakInTable = 0;
4407 DebugBreakInLocateId = false;
4408 DebugBreakKeyChord = ImGuiKey_Pause;
4409 DebugBreakInShortcutRouting = ImGuiKey_None;
4410
4411 memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
4412 FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
4413 FramerateSecPerFrameAccum = 0.0f;
4414 WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
4415 memset(TempKeychordName, 0, sizeof(TempKeychordName));
4416 }
4417
4418 void ImGui::Initialize()
4419 {
4420 ImGuiContext& g = *GImGui;
4421 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4422
4423 // Add .ini handle for ImGuiWindow and ImGuiTable types
4424 {
4425 ImGuiSettingsHandler ini_handler;
4426 ini_handler.TypeName = "Window";
4427 ini_handler.TypeHash = ImHashStr("Window");
4428 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4429 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4430 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4431 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4432 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4433 AddSettingsHandler(&ini_handler);
4434 }
4435 TableSettingsAddSettingsHandler();
4436
4437 // Setup default localization table
4438 LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
4439
4440 // Setup default ImGuiPlatformIO clipboard/IME handlers.
4441 g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
4442 g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl;
4443 g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl;
4444 g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl;
4445
4446 // Create default viewport
4447 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4448 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4449 viewport->Idx = 0;
4450 viewport->PlatformWindowCreated = true;
4451 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
4452 g.Viewports.push_back(viewport);
4453 g.TempBuffer.resize(1024 * 3 + 1, 0);
4454 g.ViewportCreatedCount++;
4455 g.PlatformIO.Viewports.push_back(g.Viewports[0]);
4456
4457 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
4458 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4459 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
4460 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
4461 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
4462 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
4463 g.KeysMayBeCharInput.SetBit(key);
4464
4465 #ifdef IMGUI_HAS_DOCK
4466 // Initialize Docking
4467 DockContextInitialize(&g);
4468 #endif
4469
4470 // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow.
4471 // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED.
4472 #ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
4473 DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
4474 #endif
4475
4476 // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context.
4477 // But this link allows us to facilitate/handle a few edge cases better.
4478 ImFontAtlas* atlas = g.IO.Fonts;
4479 g.DrawListSharedData.Context = &g;
4480 RegisterFontAtlas(atlas);
4481
4482 g.Initialized = true;
4483 }
4484
4485 // This function is merely here to free heap allocations.
4486 void ImGui::Shutdown()
4487 {
4488 ImGuiContext& g = *GImGui;
4489 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
4490 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
4491
4492 // 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)
4493 for (ImFontAtlas* atlas : g.FontAtlases)
4494 {
4495 UnregisterFontAtlas(atlas);
4496 if (atlas->OwnerContext == &g)
4497 {
4498 atlas->Locked = false;
4499 IM_DELETE(atlas);
4500 }
4501 }
4502 g.DrawListSharedData.TempBuffer.clear();
4503
4504 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4505 if (!g.Initialized)
4506 return;
4507
4508 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4509 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4510 SaveIniSettingsToDisk(g.IO.IniFilename);
4511
4512 // Destroy platform windows
4513 DestroyPlatformWindows();
4514
4515 // Shutdown extensions
4516 DockContextShutdown(&g);
4517
4518 CallContextHooks(&g, ImGuiContextHookType_Shutdown);
4519
4520 // Clear everything else
4521 g.Windows.clear_delete();
4522 g.WindowsFocusOrder.clear();
4523 g.WindowsTempSortBuffer.clear();
4524 g.CurrentWindow = NULL;
4525 g.CurrentWindowStack.clear();
4526 g.WindowsById.Clear();
4527 g.NavWindow = NULL;
4528 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4529 g.ActiveIdWindow = NULL;
4530 g.MovingWindow = NULL;
4531
4532 g.KeysRoutingTable.Clear();
4533
4534 g.ColorStack.clear();
4535 g.StyleVarStack.clear();
4536 g.FontStack.clear();
4537 g.OpenPopupStack.clear();
4538 g.BeginPopupStack.clear();
4539 g.TreeNodeStack.clear();
4540
4541 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
4542 g.Viewports.clear_delete();
4543
4544 g.TabBars.Clear();
4545 g.CurrentTabBarStack.clear();
4546 g.ShrinkWidthBuffer.clear();
4547
4548 g.ClipperTempData.clear_destruct();
4549
4550 g.Tables.Clear();
4551 g.TablesTempData.clear_destruct();
4552 g.DrawChannelsTempMergeBuffer.clear();
4553
4554 g.MultiSelectStorage.Clear();
4555 g.MultiSelectTempData.clear_destruct();
4556
4557 g.ClipboardHandlerData.clear();
4558 g.MenusIdSubmittedThisFrame.clear();
4559 g.InputTextState.ClearFreeMemory();
4560 g.InputTextDeactivatedState.ClearFreeMemory();
4561
4562 g.SettingsWindows.clear();
4563 g.SettingsHandlers.clear();
4564
4565 if (g.LogFile)
4566 {
4567 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4568 if (g.LogFile != stdout)
4569 #endif
4570 ImFileClose(g.LogFile);
4571 g.LogFile = NULL;
4572 }
4573 g.LogBuffer.clear();
4574 g.DebugLogBuf.clear();
4575 g.DebugLogIndex.clear();
4576
4577 g.Initialized = false;
4578 }
4579
4580 // No specific ordering/dependency support, will see as needed
4581 ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
4582 {
4583 ImGuiContext& g = *ctx;
4584 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
4585 g.Hooks.push_back(*hook);
4586 g.Hooks.back().HookId = ++g.HookIdNext;
4587 return g.HookIdNext;
4588 }
4589
4590 // Deferred removal, avoiding issue with changing vector while iterating it
4591 void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
4592 {
4593 ImGuiContext& g = *ctx;
4594 IM_ASSERT(hook_id != 0);
4595 for (ImGuiContextHook& hook : g.Hooks)
4596 if (hook.HookId == hook_id)
4597 hook.Type = ImGuiContextHookType_PendingRemoval_;
4598 }
4599
4600 // Call context hooks (used by e.g. test engine)
4601 // We assume a small number of hooks so all stored in same array
4602 void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
4603 {
4604 ImGuiContext& g = *ctx;
4605 for (ImGuiContextHook& hook : g.Hooks)
4606 if (hook.Type == hook_type)
4607 hook.Callback(&g, &hook);
4608 }
4609
4610 //-----------------------------------------------------------------------------
4611 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4612 //-----------------------------------------------------------------------------
4613
4614 // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4615 ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name, const char* displayedName) : DrawListInst(NULL)
4616 {
4617 memset(this, 0, sizeof(*this));
4618 Ctx = ctx;
4619 Name = ImStrdup(name);
4620 NameBufLen = (int)ImStrlen(name) + 1;
4621
4622 if(displayedName != NULL)
4623 {
4624 DisplayedName = ImStrdup(displayedName);
4625 }
4626
4627 else
4628 {
4629 DisplayedName = NULL;
4630 }
4631
4632 ID = ImHashStr(name);
4633 IDStack.push_back(ID);
4634 ViewportAllowPlatformMonitorExtend = -1;
4635 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
4636 MoveId = GetID("#MOVE");
4637 TabId = GetID("#TAB");
4638 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4639 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4640 InertialScrollSpeed = ImVec2(0.0f, 0.0f);
4641 AutoFitFramesX = AutoFitFramesY = -1;
4642 AutoPosLastDirection = ImGuiDir_None;
4643 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4644 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4645 LastFrameActive = -1;
4646 LastFrameJustFocused = -1;
4647 LastTimeActive = -1.0f;
4648 FontRefSize = 0.0f;
4649 FontWindowScale = FontWindowScaleParents = 1.0f;
4650 SettingsOffset = -1;
4651 DockOrder = -1;
4652 DrawList = &DrawListInst;
4653 DrawList->_OwnerName = Name;
4654 DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData);
4655 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4656 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4657 }
4658
4659 ImGuiWindow::~ImGuiWindow()
4660 {
4661 IM_ASSERT(DrawList == &DrawListInst);
4662 IM_DELETE(Name);
4663 IM_DELETE(DisplayedName);
4664 ColumnsStorage.clear_destruct();
4665 }
4666
4667 static void SetCurrentWindow(ImGuiWindow* window)
4668 {
4669 ImGuiContext& g = *GImGui;
4670 g.CurrentWindow = window;
4671 g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
4672 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4673 if (window)
4674 {
4675 bool backup_skip_items = window->SkipItems;
4676 window->SkipItems = false;
4677 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
4678 {
4679 ImGuiViewport* viewport = window->Viewport;
4680 g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity()
4681 }
4682 ImGui::UpdateCurrentFontSize(0.0f);
4683 window->SkipItems = backup_skip_items;
4684 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4685 }
4686 }
4687
4688 void ImGui::GcCompactTransientMiscBuffers()
4689 {
4690 ImGuiContext& g = *GImGui;
4691 g.ItemFlagsStack.clear();
4692 g.GroupStack.clear();
4693 g.MultiSelectTempDataStacked = 0;
4694 g.MultiSelectTempData.clear_destruct();
4695 TableGcCompactSettings();
4696 for (ImFontAtlas* atlas : g.FontAtlases)
4697 atlas->CompactCache();
4698 }
4699
4700 // Free up/compact internal window buffers, we can use this when a window becomes unused.
4701 // Not freed:
4702 // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4703 // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4704 void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4705 {
4706 window->MemoryCompacted = true;
4707 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4708 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4709 window->IDStack.clear();
4710 window->DrawList->_ClearFreeMemory();
4711 window->DC.ChildWindows.clear();
4712 window->DC.ItemWidthStack.clear();
4713 window->DC.TextWrapPosStack.clear();
4714 }
4715
4716 void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4717 {
4718 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4719 // The other buffers tends to amortize much faster.
4720 window->MemoryCompacted = false;
4721 window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4722 window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4723 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4724 }
4725
4726 void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4727 {
4728 ImGuiContext& g = *GImGui;
4729
4730 // Clear previous active id
4731 if (g.ActiveId != 0)
4732 {
4733 // Store deactivate data
4734 ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData;
4735 deactivated_data->ID = g.ActiveId;
4736 deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData?
4737 deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4738 deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId);
4739
4740 // This could be written in a more general way (e.g associate a hook to ActiveId),
4741 // but since this is currently quite an exception we'll leave it as is.
4742 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
4743 if (g.InputTextState.ID == g.ActiveId)
4744 InputTextDeactivateHook(g.ActiveId);
4745
4746 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4747 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4748 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4749 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4750 {
4751 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4752 StopMouseMovingWindow();
4753 }
4754 }
4755
4756 // Set active id
4757 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4758 if (g.ActiveIdIsJustActivated)
4759 {
4760 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 : "");
4761 g.ActiveIdTimer = 0.0f;
4762 g.ActiveIdHasBeenPressedBefore = false;
4763 g.ActiveIdHasBeenEditedBefore = false;
4764 g.ActiveIdMouseButton = -1;
4765 if (id != 0)
4766 {
4767 g.LastActiveId = id;
4768 g.LastActiveIdTimer = 0.0f;
4769 }
4770 }
4771 g.ActiveId = id;
4772 g.ActiveIdAllowOverlap = false;
4773 g.ActiveIdNoClearOnFocusLoss = false;
4774 g.ActiveIdWindow = window;
4775 g.ActiveIdHasBeenEditedThisFrame = false;
4776 g.ActiveIdFromShortcut = false;
4777 g.ActiveIdDisabledId = 0;
4778 if (id)
4779 {
4780 g.ActiveIdIsAlive = id;
4781 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4782 // TODO: check whether this works
4783 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoInertialScroll) {
4784 g.InertialScrollInhibited=true;
4785 }
4786 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4787 }
4788
4789 // Clear declaration of inputs claimed by the widget
4790 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4791 g.ActiveIdUsingNavDirMask = 0x00;
4792 g.ActiveIdUsingAllKeyboardKeys = false;
4793 }
4794
4795 void ImGui::ClearActiveID()
4796 {
4797 SetActiveID(0, NULL); // g.ActiveId = 0;
4798 }
4799
4800 void ImGui::SetHoveredID(ImGuiID id)
4801 {
4802 ImGuiContext& g = *GImGui;
4803 g.HoveredId = id;
4804 g.HoveredIdAllowOverlap = false;
4805 if (id != 0 && g.HoveredIdPreviousFrame != id)
4806 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4807 }
4808
4809 ImGuiID ImGui::GetHoveredID()
4810 {
4811 ImGuiContext& g = *GImGui;
4812 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4813 }
4814
4815 void ImGui::MarkItemEdited(ImGuiID id)
4816 {
4817 // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
4818 // 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.
4819 ImGuiContext& g = *GImGui;
4820 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
4821 return;
4822 if (g.ActiveId == id || g.ActiveId == 0)
4823 {
4824 // FIXME: Can't we fully rely on LastItemData yet?
4825 g.ActiveIdHasBeenEditedThisFrame = true;
4826 g.ActiveIdHasBeenEditedBefore = true;
4827 if (g.DeactivatedItemData.ID == id)
4828 g.DeactivatedItemData.HasBeenEditedBefore = true;
4829 }
4830
4831 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4832 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4833 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4834
4835 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4836 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4837 }
4838
4839 bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4840 {
4841 // An active popup disable hovering on other windows (apart from its own children)
4842 // FIXME-OPT: This could be cached/stored within the window.
4843 ImGuiContext& g = *GImGui;
4844 if (g.NavWindow)
4845 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4846 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4847 {
4848 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4849 // NB: The 'else' is important because Modal windows are also Popups.
4850 bool want_inhibit = false;
4851 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4852 want_inhibit = true;
4853 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4854 want_inhibit = true;
4855
4856 // Inhibit hover unless the window is within the stack of our modal/popup
4857 if (want_inhibit)
4858 if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4859 return false;
4860 }
4861
4862 // Filter by viewport
4863 if (window->Viewport != g.MouseViewport)
4864 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4865 return false;
4866
4867 return true;
4868 }
4869
4870 static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4871 {
4872 ImGuiContext& g = *GImGui;
4873 if (flags & ImGuiHoveredFlags_DelayNormal)
4874 return g.Style.HoverDelayNormal;
4875 if (flags & ImGuiHoveredFlags_DelayShort)
4876 return g.Style.HoverDelayShort;
4877 return 0.0f;
4878 }
4879
4880 static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4881 {
4882 // Allow instance flags to override shared flags
4883 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4884 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4885 return user_flags | shared_flags;
4886 }
4887
4888 // This is roughly matching the behavior of internal-facing ItemHoverable()
4889 // - 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()
4890 // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4891 bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4892 {
4893 ImGuiContext& g = *GImGui;
4894 ImGuiWindow* window = g.CurrentWindow;
4895 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
4896
4897 if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
4898 {
4899 if (!IsItemFocused())
4900 return false;
4901 if (window->InertialScroll)
4902 return false;
4903 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4904 return false;
4905
4906 if (flags & ImGuiHoveredFlags_ForTooltip)
4907 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4908 }
4909 else
4910 {
4911 // Test for bounding box overlap, as updated as ItemAdd()
4912 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4913 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4914 return false;
4915
4916 if (flags & ImGuiHoveredFlags_ForTooltip)
4917 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4918
4919 // Done with rectangle culling so we can perform heavier checks now
4920 // Test if we are hovering the right window (our window could be behind another window)
4921 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4922 // [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
4923 // 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
4924 // the test that has been running for a long while.
4925 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4926 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4927 return false;
4928
4929 // Test if another item is active (e.g. being dragged)
4930 const ImGuiID id = g.LastItemData.ID;
4931 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4932 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4933 {
4934 // When ActiveId == MoveId it means that either:
4935 // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag)
4936 // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed.
4937 // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId.
4938 bool cancel_is_hovered = true;
4939 if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id))
4940 cancel_is_hovered = false;
4941 // When ActiveId == TabId it means user clicked docking tab for the window.
4942 if (g.ActiveId == window->TabId)
4943 cancel_is_hovered = false;
4944 if (cancel_is_hovered)
4945 return false;
4946 }
4947
4948 // Test if interactions on this window are blocked by an active popup or modal.
4949 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4950 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4951 return false;
4952
4953 // Test if the item is disabled
4954 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4955 return false;
4956
4957 // Test for inertial scroll
4958 if (window->InertialScroll)
4959 return false;
4960
4961 // Special handling for calling after Begin() which represent the title bar or tab.
4962 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4963 // will never be overwritten so we need to detect the case.
4964 if (id == window->MoveId && window->WriteAccessed)
4965 return false;
4966
4967 // Test if using AllowOverlap and overlapped
4968 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4969 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4970 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4971 return false;
4972 }
4973
4974 // Handle hover delay
4975 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4976 const float delay = CalcDelayFromHoveredFlags(flags);
4977 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4978 {
4979 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(g.LastItemData.Rect.Min);
4980 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4981 g.HoverItemDelayTimer = 0.0f;
4982 g.HoverItemDelayId = hover_delay_id;
4983
4984 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4985 // but once unlocked on a given item we also moving.
4986 //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); }
4987 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4988 return false;
4989
4990 if (g.HoverItemDelayTimer < delay)
4991 return false;
4992 }
4993
4994 return true;
4995 }
4996
4997 // Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK.
4998 // Returns whether the item was hovered, logic differs slightly from IsItemHovered().
4999 // (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
5000 // FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
5001 // If you used this in your legacy/custom widgets code:
5002 // - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
5003 // - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
5004 bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
5005 {
5006 ImGuiContext& g = *GImGui;
5007 ImGuiWindow* window = g.CurrentWindow;
5008
5009 // Detect ID conflicts
5010 // (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)
5011 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5012 if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
5013 {
5014 g.HoveredIdPreviousFrameItemCount++;
5015 if (g.DebugDrawIdConflictsId == id)
5016 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);
5017 }
5018 #endif
5019
5020 if (g.HoveredWindow != window)
5021 return false;
5022 if (!IsMouseHoveringRect(bb.Min, bb.Max))
5023 return false;
5024
5025 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
5026 return false;
5027 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
5028 if (!g.ActiveIdFromShortcut)
5029 return false;
5030
5031 // We are done with rectangle culling so we can perform heavier checks now.
5032 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
5033 {
5034 g.HoveredIdIsDisabled = true;
5035 return false;
5036 }
5037
5038 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
5039 // hover test in widgets code. We could also decide to split this function is two.
5040 if (id != 0)
5041 {
5042 // Drag source doesn't report as hovered
5043 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
5044 return false;
5045
5046 SetHoveredID(id);
5047
5048 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
5049 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
5050 if (item_flags & ImGuiItemFlags_AllowOverlap)
5051 {
5052 g.HoveredIdAllowOverlap = true;
5053 if (g.HoveredIdPreviousFrame != id)
5054 return false;
5055 }
5056
5057 // Display shortcut (only works with mouse)
5058 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
5059 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
5060 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
5061 SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
5062 }
5063
5064 // When disabled we'll return false but still set HoveredId
5065 // Same thing if swiping
5066 if (item_flags & ImGuiItemFlags_Disabled || window->InertialScroll)
5067 {
5068 // Release active id if turning disabled
5069 if (g.ActiveId == id && id != 0)
5070 ClearActiveID();
5071 g.HoveredIdIsDisabled = true;
5072 return false;
5073 }
5074
5075 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5076 if (id != 0)
5077 {
5078 // [DEBUG] Item Picker tool!
5079 // We perform the check here because reaching is path is rare (1~ time a frame),
5080 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
5081 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
5082 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
5083 GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
5084 if (g.DebugItemPickerBreakId == id)
5085 IM_DEBUG_BREAK();
5086 }
5087 #endif
5088
5089 if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
5090 return false;
5091
5092 return true;
5093 }
5094
5095 // FIXME: This is inlined/duplicated in ItemAdd()
5096 // FIXME: The id != 0 path is not used by our codebase, may get rid of it?
5097 bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
5098 {
5099 ImGuiContext& g = *GImGui;
5100 ImGuiWindow* window = g.CurrentWindow;
5101 if (!bb.Overlaps(window->ClipRect))
5102 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
5103 if (!g.ItemUnclipByLog)
5104 return true;
5105 return false;
5106 }
5107
5108 // This is also inlined in ItemAdd()
5109 // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
5110 void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect)
5111 {
5112 ImGuiContext& g = *GImGui;
5113 g.LastItemData.ID = item_id;
5114 g.LastItemData.ItemFlags = item_flags;
5115 g.LastItemData.StatusFlags = status_flags;
5116 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
5117 }
5118
5119 static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
5120 {
5121 ImGuiContext& g = *GImGui;
5122 if (window->DockIsActive)
5123 SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.DockTabItemStatusFlags, window->DC.DockTabItemRect);
5124 else
5125 SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect);
5126 }
5127
5128 static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect)
5129 {
5130 ImGuiContext& g = *GImGui;
5131 SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.ChildItemStatusFlags, rect);
5132 }
5133
5134 float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
5135 {
5136 if (wrap_pos_x < 0.0f)
5137 return 0.0f;
5138
5139 ImGuiContext& g = *GImGui;
5140 ImGuiWindow* window = g.CurrentWindow;
5141 if (wrap_pos_x == 0.0f)
5142 {
5143 // We could decide to setup a default wrapping max point for auto-resizing windows,
5144 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
5145 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
5146 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
5147 //else
5148 wrap_pos_x = window->WorkRect.Max.x;
5149 }
5150 else if (wrap_pos_x > 0.0f)
5151 {
5152 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
5153 }
5154
5155 return ImMax(wrap_pos_x - pos.x, 1.0f);
5156 }
5157
5158 // IM_ALLOC() == ImGui::MemAlloc()
5159 void* ImGui::MemAlloc(size_t size)
5160 {
5161 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
5162 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5163 if (ImGuiContext* ctx = GImGui)
5164 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
5165 #endif
5166 return ptr;
5167 }
5168
5169 // IM_FREE() == ImGui::MemFree()
5170 void ImGui::MemFree(void* ptr)
5171 {
5172 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5173 if (ptr != NULL)
5174 if (ImGuiContext* ctx = GImGui)
5175 DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
5176 #endif
5177 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
5178 }
5179
5180 // 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"
5181 void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
5182 {
5183 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5184 IM_UNUSED(ptr);
5185 if (entry->FrameCount != frame_count)
5186 {
5187 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
5188 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5189 entry->FrameCount = frame_count;
5190 entry->AllocCount = entry->FreeCount = 0;
5191 }
5192 if (size != (size_t)-1)
5193 {
5194 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
5195 entry->AllocCount++;
5196 info->TotalAllocCount++;
5197 }
5198 else
5199 {
5200 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
5201 entry->FreeCount++;
5202 info->TotalFreeCount++;
5203 }
5204 }
5205
5206 const char* ImGui::GetClipboardText()
5207 {
5208 ImGuiContext& g = *GImGui;
5209 return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : "";
5210 }
5211
5212 void ImGui::SetClipboardText(const char* text)
5213 {
5214 ImGuiContext& g = *GImGui;
5215 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5216 g.PlatformIO.Platform_SetClipboardTextFn(&g, text);
5217 }
5218
5219 const char* ImGui::GetVersion()
5220 {
5221 return IMGUI_VERSION;
5222 }
5223
5224 ImGuiIO& ImGui::GetIO()
5225 {
5226 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5227 return GImGui->IO;
5228 }
5229
5230 // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5231 ImGuiIO& ImGui::GetIO(ImGuiContext* ctx)
5232 {
5233 IM_ASSERT(ctx != NULL);
5234 return ctx->IO;
5235 }
5236
5237 ImGuiPlatformIO& ImGui::GetPlatformIO()
5238 {
5239 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
5240 return GImGui->PlatformIO;
5241 }
5242
5243 // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5244 ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx)
5245 {
5246 IM_ASSERT(ctx != NULL);
5247 return ctx->PlatformIO;
5248 }
5249
5250 // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
5251 ImDrawData* ImGui::GetDrawData()
5252 {
5253 ImGuiContext& g = *GImGui;
5254 ImGuiViewportP* viewport = g.Viewports[0];
5255 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
5256 }
5257
5258 double ImGui::GetTime()
5259 {
5260 return GImGui->Time;
5261 }
5262
5263 int ImGui::GetFrameCount()
5264 {
5265 return GImGui->FrameCount;
5266 }
5267
5268 static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
5269 {
5270 // Create the draw list on demand, because they are not frequently used for all viewports
5271 ImGuiContext& g = *GImGui;
5272 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
5273 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
5274 if (draw_list == NULL)
5275 {
5276 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
5277 draw_list->_OwnerName = drawlist_name;
5278 viewport->BgFgDrawLists[drawlist_no] = draw_list;
5279 }
5280
5281 // Our ImDrawList system requires that there is always a command
5282 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
5283 {
5284 draw_list->_ResetForNewFrame();
5285 draw_list->PushTexture(g.IO.Fonts->TexRef);
5286 draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
5287 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
5288 }
5289 return draw_list;
5290 }
5291
5292 ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
5293 {
5294 if (viewport == NULL)
5295 viewport = GImGui->CurrentWindow->Viewport;
5296 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
5297 }
5298
5299 ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
5300 {
5301 if (viewport == NULL)
5302 viewport = GImGui->CurrentWindow->Viewport;
5303 return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
5304 }
5305
5306 ImDrawListSharedData* ImGui::GetDrawListSharedData()
5307 {
5308 return &GImGui->DrawListSharedData;
5309 }
5310
5311 void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
5312 {
5313 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
5314 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
5315 // This is because we want ActiveId to be set even when the window is not permitted to move.
5316 ImGuiContext& g = *GImGui;
5317 FocusWindow(window);
5318 SetActiveID(window->MoveId, window);
5319 if (g.IO.ConfigNavCursorVisibleAuto)
5320 g.NavCursorVisible = false;
5321 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
5322 g.ActiveIdNoClearOnFocusLoss = true;
5323 SetActiveIdUsingAllKeyboardKeys();
5324
5325 bool can_move_window = true;
5326 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
5327 can_move_window = false;
5328 if (ImGuiDockNode* node = window->DockNodeAsHost)
5329 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
5330 can_move_window = false;
5331 if (can_move_window)
5332 g.MovingWindow = window;
5333 }
5334
5335 // We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
5336 void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
5337 {
5338 ImGuiContext& g = *GImGui;
5339 bool can_undock_node = false;
5340 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
5341 {
5342 // Can undock if:
5343 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
5344 // - 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.
5345 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
5346 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
5347 can_undock_node = true;
5348 if (node->MergedFlags & ImGuiDockNodeFlags_NoMove)
5349 can_undock_node = false;
5350 }
5351
5352 const bool clicked = IsMouseClicked(0);
5353 const bool dragging = IsMouseDragging(0);
5354 if (can_undock_node && dragging)
5355 DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
5356 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
5357 StartMouseMovingWindow(window);
5358 }
5359
5360 // This is not 100% symetric with StartMouseMovingWindow().
5361 // We do NOT clear ActiveID, because:
5362 // - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired.
5363 // - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item).
5364 void ImGui::StopMouseMovingWindow()
5365 {
5366 ImGuiContext& g = *GImGui;
5367 ImGuiWindow* window = g.MovingWindow;
5368
5369 // Ref commits 6b7766817, 36055213c for some partial history on checking if viewport != NULL.
5370 if (window && window->Viewport)
5371 {
5372 // Try to merge the window back into the main viewport.
5373 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
5374 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
5375 UpdateTryMergeWindowIntoHostViewport(window, g.MouseViewport);
5376
5377 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
5378 if (!IsDragDropPayloadBeingAccepted())
5379 g.MouseViewport = window->Viewport;
5380
5381 // Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport()
5382 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
5383 if (window_can_use_inputs)
5384 window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
5385 }
5386 g.MovingWindow = NULL;
5387 }
5388
5389 // Handle mouse moving window
5390 // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
5391 // FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId.
5392 // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
5393 // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
5394 void ImGui::UpdateMouseMovingWindowNewFrame()
5395 {
5396 ImGuiContext& g = *GImGui;
5397 if (g.MovingWindow != NULL)
5398 {
5399 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
5400 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
5401 KeepAliveID(g.ActiveId);
5402 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
5403 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
5404
5405 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
5406 const bool window_disappeared = (!moving_window->WasActive && !moving_window->Active);
5407 if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappeared)
5408 {
5409 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
5410 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
5411 {
5412 SetWindowPos(moving_window, pos, ImGuiCond_Always);
5413 g.InertialScrollInhibited=true;
5414 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
5415 {
5416 moving_window->Viewport->Pos = pos;
5417 moving_window->Viewport->UpdateWorkRect();
5418 }
5419 }
5420 FocusWindow(g.MovingWindow);
5421 }
5422 else
5423 {
5424 StopMouseMovingWindow();
5425 ClearActiveID();
5426 }
5427 }
5428 else
5429 {
5430 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
5431 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
5432 {
5433 KeepAliveID(g.ActiveId);
5434 if (!g.IO.MouseDown[0])
5435 ClearActiveID();
5436 }
5437 }
5438 }
5439
5440 // Initiate focusing and moving window when clicking on empty space or title bar.
5441 // Initiate focusing window when clicking on a disabled item.
5442 // Handle left-click and right-click focus.
5443 void ImGui::UpdateMouseMovingWindowEndFrame()
5444 {
5445 ImGuiContext& g = *GImGui;
5446 if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
5447 return;
5448
5449 // Unless we just made a window/popup appear
5450 if (g.NavWindow && g.NavWindow->Appearing)
5451 return;
5452
5453 // Click on empty space to focus window and start moving
5454 // (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!)
5455 if (g.IO.MouseClicked[0])
5456 {
5457 // Handle the edge case of a popup being closed while clicking in its empty space.
5458 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
5459 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
5460 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
5461
5462 if (root_window != NULL && !is_closed_popup)
5463 {
5464 StartMouseMovingWindow(g.HoveredWindow); //-V595
5465
5466 // FIXME: In principal we might be able to call StopMouseMovingWindow() below.
5467 // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId.
5468
5469 // Cancel moving if clicked outside of title bar
5470 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
5471 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
5472 if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
5473 g.MovingWindow = NULL;
5474
5475 // Cancel moving if clicked over an item which was disabled or inhibited by popups
5476 // (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)
5477 if (g.HoveredIdIsDisabled)
5478 {
5479 g.MovingWindow = NULL;
5480 g.ActiveIdDisabledId = g.HoveredId;
5481 }
5482 }
5483 else if (root_window == NULL && g.NavWindow != NULL)
5484 {
5485 // Clicking on void disable focus
5486 FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
5487 }
5488 }
5489
5490 // With right mouse button we close popups without changing focus based on where the mouse is aimed
5491 // Instead, focus will be restored to the window under the bottom-most closed popup.
5492 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
5493 if (g.IO.MouseClicked[1] && g.HoveredId == 0)
5494 {
5495 // Find the top-most window between HoveredWindow and the top-most Modal Window.
5496 // This is where we can trim the popup stack.
5497 ImGuiWindow* modal = GetTopMostPopupModal();
5498 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
5499 ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
5500 }
5501 }
5502
5503 // This is called during NewFrame()->UpdateViewportsNewFrame() only.
5504 // Need to keep in sync with SetWindowPos()
5505 static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
5506 {
5507 window->Pos += delta;
5508 window->ClipRect.Translate(delta);
5509 window->OuterRectClipped.Translate(delta);
5510 window->InnerRect.Translate(delta);
5511 window->DC.CursorPos += delta;
5512 window->DC.CursorStartPos += delta;
5513 window->DC.CursorMaxPos += delta;
5514 window->DC.IdealMaxPos += delta;
5515 }
5516
5517 static void ScaleWindow(ImGuiWindow* window, float scale)
5518 {
5519 ImVec2 origin = window->Viewport->Pos;
5520 window->Pos = ImFloor((window->Pos - origin) * scale + origin);
5521 window->Size = ImTrunc(window->Size * scale);
5522 window->SizeFull = ImTrunc(window->SizeFull * scale);
5523 window->ContentSize = ImTrunc(window->ContentSize * scale);
5524 }
5525
5526 static bool IsWindowActiveAndVisible(ImGuiWindow* window)
5527 {
5528 return (window->Active) && (!window->Hidden);
5529 }
5530
5531 // 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)
5532 void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos)
5533 {
5534 ImGuiContext& g = *GImGui;
5535 ImGuiIO& io = g.IO;
5536
5537 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
5538 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
5539 g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding);
5540
5541 // Find the window hovered by mouse:
5542 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
5543 // - 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.
5544 // - 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.
5545 bool clear_hovered_windows = false;
5546 FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
5547 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
5548 g.HoveredWindowBeforeClear = g.HoveredWindow;
5549
5550 // Modal windows prevents mouse from hovering behind them.
5551 ImGuiWindow* modal_window = GetTopMostPopupModal();
5552 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
5553 clear_hovered_windows = true;
5554
5555 // Disabled mouse hovering (we don't currently clear MousePos, we could)
5556 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
5557 clear_hovered_windows = true;
5558
5559 // We track click ownership. When clicked outside of a window the click is owned by the application and
5560 // won't report hovering nor request capture even while dragging over our windows afterward.
5561 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
5562 const bool has_open_modal = (modal_window != NULL);
5563 int mouse_earliest_down = -1;
5564 bool mouse_any_down = false;
5565 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
5566 {
5567 if (io.MouseClicked[i])
5568 {
5569 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
5570 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
5571 }
5572 mouse_any_down |= io.MouseDown[i];
5573 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
5574 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
5575 mouse_earliest_down = i;
5576 }
5577 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
5578 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
5579
5580 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
5581 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
5582 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
5583 if (!mouse_avail && !mouse_dragging_extern_payload)
5584 clear_hovered_windows = true;
5585
5586 if (clear_hovered_windows)
5587 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5588
5589 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
5590 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
5591 if (g.WantCaptureMouseNextFrame != -1)
5592 {
5593 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
5594 }
5595 else
5596 {
5597 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
5598 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
5599 }
5600
5601 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
5602 io.WantCaptureKeyboard = false;
5603 if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
5604 {
5605 if ((g.ActiveId != 0) || (modal_window != NULL))
5606 io.WantCaptureKeyboard = true;
5607 else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
5608 io.WantCaptureKeyboard = true;
5609 }
5610 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
5611 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
5612
5613 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
5614 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
5615 }
5616
5617 // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
5618 // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
5619 static void SetupDrawListSharedData()
5620 {
5621 ImGuiContext& g = *GImGui;
5622 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
5623 for (ImGuiViewportP* viewport : g.Viewports)
5624 virtual_space.Add(viewport->GetMainRect());
5625 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
5626 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
5627 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
5628 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
5629 if (g.Style.AntiAliasedLines)
5630 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
5631 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
5632 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
5633 if (g.Style.AntiAliasedFill)
5634 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
5635 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
5636 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
5637 g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments.
5638 }
5639
5640 void ImGui::NewFrame()
5641 {
5642 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5643 ImGuiContext& g = *GImGui;
5644
5645 // Remove pending delete hooks before frame start.
5646 // This deferred removal avoid issues of removal while iterating the hook vector
5647 for (int n = g.Hooks.Size - 1; n >= 0; n--)
5648 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
5649 g.Hooks.erase(&g.Hooks[n]);
5650
5651 CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
5652
5653 // Check and assert for various common IO and Configuration mistakes
5654 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
5655 ErrorCheckNewFrameSanityChecks();
5656 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
5657
5658 // Load settings on first frame, save settings when modified (after a delay)
5659 UpdateSettings();
5660
5661 g.Time += g.IO.DeltaTime;
5662 g.FrameCount += 1;
5663 g.TooltipOverrideCount = 0;
5664 g.WindowsActiveCount = 0;
5665 g.MenusIdSubmittedThisFrame.resize(0);
5666
5667 // Calculate frame-rate for the user, as a purely luxurious feature
5668 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
5669 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
5670 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
5671 g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
5672 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
5673 g.IO.IsSomethingHappening = false;
5674
5675 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
5676 g.InputEventsTrail.resize(0);
5677 UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
5678
5679 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
5680 UpdateViewportsNewFrame();
5681
5682 // Update texture list (collect destroyed textures, etc.)
5683 UpdateTexturesNewFrame();
5684
5685 // Setup current font and draw list shared data
5686 SetupDrawListSharedData();
5687 UpdateFontsNewFrame();
5688
5689 g.WithinFrameScope = true;
5690
5691 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
5692 for (ImGuiViewportP* viewport : g.Viewports)
5693 {
5694 viewport->DrawData = NULL;
5695 viewport->DrawDataP.Valid = false;
5696 }
5697
5698 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
5699 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
5700 KeepAliveID(g.DragDropPayload.SourceId);
5701
5702 // [DEBUG]
5703 if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
5704 g.DebugDrawIdConflictsId = 0;
5705 if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
5706 g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame;
5707
5708 // Update HoveredId data
5709 if (!g.HoveredIdPreviousFrame)
5710 g.HoveredIdTimer = 0.0f;
5711 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
5712 g.HoveredIdNotActiveTimer = 0.0f;
5713 if (g.HoveredId)
5714 g.HoveredIdTimer += g.IO.DeltaTime;
5715 if (g.HoveredId && g.ActiveId != g.HoveredId)
5716 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
5717 g.HoveredIdPreviousFrame = g.HoveredId;
5718 g.HoveredIdPreviousFrameItemCount = 0;
5719 g.HoveredId = 0;
5720 g.HoveredIdAllowOverlap = false;
5721 g.HoveredIdIsDisabled = false;
5722
5723 // Clear ActiveID if the item is not alive anymore.
5724 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
5725 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
5726 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
5727 {
5728 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
5729 ClearActiveID();
5730 }
5731
5732 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
5733 if (g.ActiveId)
5734 g.ActiveIdTimer += g.IO.DeltaTime;
5735 g.LastActiveIdTimer += g.IO.DeltaTime;
5736 g.ActiveIdPreviousFrame = g.ActiveId;
5737 g.ActiveIdIsAlive = 0;
5738 g.ActiveIdHasBeenEditedThisFrame = false;
5739 g.ActiveIdIsJustActivated = false;
5740 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
5741 g.TempInputId = 0;
5742 if (g.ActiveId == 0)
5743 {
5744 g.ActiveIdUsingNavDirMask = 0x00;
5745 g.ActiveIdUsingAllKeyboardKeys = false;
5746 }
5747 if (g.DeactivatedItemData.ElapseFrame < g.FrameCount)
5748 g.DeactivatedItemData.ID = 0;
5749 g.DeactivatedItemData.IsAlive = false;
5750
5751 // Record when we have been stationary as this state is preserved while over same item.
5752 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5753 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5754 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5755 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5756 else if (g.HoverItemDelayId == 0)
5757 g.HoverItemUnlockedStationaryId = 0;
5758 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5759 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5760 else if (g.HoveredWindow == NULL)
5761 g.HoverWindowUnlockedStationaryId = 0;
5762
5763 // Update hover delay for IsItemHovered() with delays and tooltips
5764 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5765 if (g.HoverItemDelayId != 0)
5766 {
5767 g.HoverItemDelayTimer += g.IO.DeltaTime;
5768 g.HoverItemDelayClearTimer = 0.0f;
5769 g.HoverItemDelayId = 0;
5770 }
5771 else if (g.HoverItemDelayTimer > 0.0f)
5772 {
5773 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5774 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5775 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5776 if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5777 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.
5778 }
5779
5780 // Drag and drop
5781 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5782 g.DragDropAcceptIdCurr = 0;
5783 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5784 g.DragDropWithinSource = false;
5785 g.DragDropWithinTarget = false;
5786 g.DragDropHoldJustPressedId = 0;
5787 g.TooltipPreviousWindow = NULL;
5788
5789 // Close popups on focus lost (currently wip/opt-in)
5790 //if (g.IO.AppFocusLost)
5791 // ClosePopupsExceptModals();
5792
5793 // Update keyboard input state
5794 UpdateKeyboardInputs();
5795
5796 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5797 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5798 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5799 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5800
5801 // Update keyboard/gamepad navigation
5802 NavUpdate();
5803
5804 // Update mouse input state
5805 UpdateMouseInputs();
5806
5807 // Undocking
5808 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5809 DockContextNewFrameUpdateUndocking(&g);
5810
5811 // Mark all windows as not visible and compact unused memory.
5812 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5813 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5814 for (ImGuiWindow* window : g.Windows)
5815 {
5816 window->WasActive = window->Active;
5817 window->Active = false;
5818 window->WriteAccessed = false;
5819 window->BeginCountPreviousFrame = window->BeginCount;
5820 window->BeginCount = 0;
5821
5822 // Garbage collect transient buffers of recently unused windows
5823 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5824 GcCompactTransientWindowBuffers(window);
5825 }
5826
5827 // Find hovered window
5828 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5829 // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
5830 UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos);
5831
5832 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5833 UpdateMouseMovingWindowNewFrame();
5834
5835 // Background darkening/whitening
5836 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) {
5837 g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5838 if (g.DimBgRatio<=0.999f) g.IO.IsSomethingHappening = true;
5839 } else {
5840 g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5841 if (g.DimBgRatio>=0.001f) g.IO.IsSomethingHappening = true;
5842 }
5843
5844 g.MouseCursor = ImGuiMouseCursor_Arrow;
5845 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5846
5847 // Platform IME data: reset for the frame
5848 g.PlatformImeDataPrev = g.PlatformImeData;
5849 g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false;
5850
5851 // Mouse wheel scrolling, scale
5852 UpdateMouseWheel();
5853
5854 // Garbage collect transient buffers of recently unused tables
5855 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5856 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5857 TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5858 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5859 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5860 TableGcCompactTransientBuffers(&table_temp_data);
5861 if (g.GcCompactAll)
5862 GcCompactTransientMiscBuffers();
5863 g.GcCompactAll = false;
5864
5865 // Closing the focused window restore focus to the first active root window in descending z-order
5866 if (g.NavWindow && !g.NavWindow->WasActive)
5867 FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5868
5869 // No window should be open at the beginning of the frame.
5870 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5871 g.CurrentWindowStack.resize(0);
5872 g.BeginPopupStack.resize(0);
5873 g.ItemFlagsStack.resize(0);
5874 g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags
5875 g.CurrentItemFlags = g.ItemFlagsStack.back();
5876 g.GroupStack.resize(0);
5877
5878 // Docking
5879 DockContextNewFrameUpdateDocking(&g);
5880
5881 // [DEBUG] Update debug features
5882 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5883 UpdateDebugToolItemPicker();
5884 UpdateDebugToolStackQueries();
5885 UpdateDebugToolFlashStyleColor();
5886 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5887 {
5888 g.DebugLocateId = 0;
5889 g.DebugBreakInLocateId = false;
5890 }
5891 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5892 {
5893 DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5894 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5895 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5896 }
5897 #endif
5898
5899 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5900 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5901 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5902 g.WithinFrameScopeWithImplicitWindow = true;
5903 SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5904 Begin("Debug##Default");
5905 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5906
5907 // Store stack sizes
5908 g.ErrorCountCurrentFrame = 0;
5909 ErrorRecoveryStoreState(&g.StackSizesInNewFrame);
5910
5911 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5912 // allowing to validate correct Begin/End behavior in user code.
5913 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5914 if (g.IO.ConfigDebugBeginReturnValueLoop)
5915 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5916 else
5917 g.DebugBeginReturnValueCullDepth = -1;
5918 #endif
5919
5920 CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5921 }
5922
5923 // FIXME: Add a more explicit sort order in the window structure.
5924 static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5925 {
5926 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5927 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5928 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5929 return d;
5930 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5931 return d;
5932 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5933 }
5934
5935 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5936 {
5937 out_sorted_windows->push_back(window);
5938 if (window->Active)
5939 {
5940 int count = window->DC.ChildWindows.Size;
5941 ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5942 for (int i = 0; i < count; i++)
5943 {
5944 ImGuiWindow* child = window->DC.ChildWindows[i];
5945 if (child->Active)
5946 AddWindowToSortBuffer(out_sorted_windows, child);
5947 }
5948 }
5949 }
5950
5951 static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5952 {
5953 ImGuiContext& g = *GImGui;
5954 ImGuiViewportP* viewport = window->Viewport;
5955 IM_ASSERT(viewport != NULL);
5956 g.IO.MetricsRenderWindows++;
5957 if (window->DrawList->_Splitter._Count > 1)
5958 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5959 ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5960 for (ImGuiWindow* child : window->DC.ChildWindows)
5961 if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5962 AddWindowToDrawData(child, layer);
5963 }
5964
5965 static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5966 {
5967 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5968 }
5969
5970 // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5971 static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5972 {
5973 AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5974 }
5975
5976 static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5977 {
5978 int n = builder->Layers[0]->Size;
5979 int full_size = n;
5980 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5981 full_size += builder->Layers[i]->Size;
5982 builder->Layers[0]->resize(full_size);
5983 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5984 {
5985 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5986 if (layer->empty())
5987 continue;
5988 memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5989 n += layer->Size;
5990 layer->resize(0);
5991 }
5992 }
5993
5994 static void InitViewportDrawData(ImGuiViewportP* viewport)
5995 {
5996 ImGuiIO& io = ImGui::GetIO();
5997 ImDrawData* draw_data = &viewport->DrawDataP;
5998
5999 viewport->DrawData = draw_data; // Make publicly accessible
6000 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
6001 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
6002 viewport->DrawDataBuilder.Layers[0]->resize(0);
6003 viewport->DrawDataBuilder.Layers[1]->resize(0);
6004
6005 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
6006 // and to allow applications/backends to easily skip rendering.
6007 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
6008 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
6009 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
6010 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
6011
6012 draw_data->Valid = true;
6013 draw_data->CmdListsCount = 0;
6014 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
6015 draw_data->DisplayPos = viewport->Pos;
6016 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
6017 draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale;
6018 draw_data->OwnerViewport = viewport;
6019 draw_data->Textures = &ImGui::GetPlatformIO().Textures;
6020 }
6021
6022 // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
6023 // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
6024 // so that e.g. (int)(max.x-min.x) in user's render produce correct result.
6025 // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
6026 // some frequently called functions which to modify both channels and clipping simultaneously tend to use the
6027 // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
6028 // - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
6029 // which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
6030 void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
6031 {
6032 ImGuiWindow* window = GetCurrentWindow();
6033 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
6034 window->ClipRect = window->DrawList->_ClipRectStack.back();
6035 }
6036
6037 void ImGui::PopClipRect()
6038 {
6039 ImGuiWindow* window = GetCurrentWindow();
6040 window->DrawList->PopClipRect();
6041 window->ClipRect = window->DrawList->_ClipRectStack.back();
6042 }
6043
6044 static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
6045 {
6046 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
6047 if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
6048 return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
6049 return window;
6050 }
6051
6052 static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
6053 {
6054 if ((col & IM_COL32_A_MASK) == 0)
6055 return;
6056
6057 ImGuiViewportP* viewport = window->Viewport;
6058 ImRect viewport_rect = viewport->GetMainRect();
6059
6060 // Draw behind window by moving the draw command at the FRONT of the draw list
6061 {
6062 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
6063 // 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.
6064 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
6065 draw_list->ChannelsMerge();
6066 if (draw_list->CmdBuffer.Size == 0)
6067 draw_list->AddDrawCmd();
6068 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)
6069 draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
6070 ImDrawCmd cmd = draw_list->CmdBuffer.back();
6071 IM_ASSERT(cmd.ElemCount == 6);
6072 draw_list->CmdBuffer.pop_back();
6073 draw_list->CmdBuffer.push_front(cmd);
6074 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
6075 draw_list->PopClipRect();
6076 }
6077
6078 // Draw over sibling docking nodes in a same docking tree
6079 if (window->RootWindow->DockIsActive)
6080 {
6081 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
6082 draw_list->ChannelsMerge();
6083 if (draw_list->CmdBuffer.Size == 0)
6084 draw_list->AddDrawCmd();
6085 draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
6086 RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
6087 draw_list->PopClipRect();
6088 }
6089 }
6090
6091 ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
6092 {
6093 ImGuiContext& g = *GImGui;
6094 ImGuiWindow* bottom_most_visible_window = parent_window;
6095 for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
6096 {
6097 ImGuiWindow* window = g.Windows[i];
6098 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6099 continue;
6100 if (!IsWindowWithinBeginStackOf(window, parent_window))
6101 break;
6102 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
6103 bottom_most_visible_window = window;
6104 }
6105 return bottom_most_visible_window;
6106 }
6107
6108 // Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
6109 // We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
6110 static void ImGui::RenderDimmedBackgrounds()
6111 {
6112 ImGuiContext& g = *GImGui;
6113 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
6114 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
6115 return;
6116 const bool dim_bg_for_modal = (modal_window != NULL);
6117 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
6118 if (!dim_bg_for_modal && !dim_bg_for_window_list)
6119 return;
6120
6121 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
6122 if (dim_bg_for_modal)
6123 {
6124 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
6125 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
6126 RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
6127 viewports_already_dimmed[0] = modal_window->Viewport;
6128 }
6129 else if (dim_bg_for_window_list)
6130 {
6131 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
6132 RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
6133 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
6134 RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
6135 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
6136 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
6137
6138 // Draw border around CTRL+Tab target window
6139 ImGuiWindow* window = g.NavWindowingTargetAnim;
6140 ImGuiViewport* viewport = window->Viewport;
6141 float distance = g.FontSize;
6142 ImRect bb = window->Rect();
6143 bb.Expand(distance);
6144 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
6145 bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
6146 window->DrawList->ChannelsMerge();
6147 if (window->DrawList->CmdBuffer.Size == 0)
6148 window->DrawList->AddDrawCmd();
6149 window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
6150 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); // FIXME-DPI
6151 window->DrawList->PopClipRect();
6152 }
6153
6154 // Draw dimming background on _other_ viewports than the ones our windows are in
6155 for (ImGuiViewportP* viewport : g.Viewports)
6156 {
6157 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
6158 continue;
6159 if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
6160 continue;
6161 ImDrawList* draw_list = GetForegroundDrawList(viewport);
6162 const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
6163 draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
6164 }
6165 }
6166
6167 // 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.
6168 void ImGui::EndFrame()
6169 {
6170 ImGuiContext& g = *GImGui;
6171 IM_ASSERT(g.Initialized);
6172
6173 // Don't process EndFrame() multiple times.
6174 if (g.FrameCountEnded == g.FrameCount)
6175 return;
6176 if (!g.WithinFrameScope)
6177 {
6178 IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?");
6179 return;
6180 }
6181
6182 CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
6183
6184 // [EXPERIMENTAL] Recover from errors
6185 if (g.IO.ConfigErrorRecovery)
6186 ErrorRecoveryTryToRecoverState(&g.StackSizesInNewFrame);
6187 ErrorCheckEndFrameSanityChecks();
6188 ErrorCheckEndFrameFinalizeErrorTooltip();
6189
6190 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
6191 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
6192 if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
6193 {
6194 ImGuiViewport* viewport = FindViewportByID(ime_data->ViewportId);
6195 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);
6196 if (viewport == NULL)
6197 viewport = GetMainViewport();
6198 g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
6199 }
6200 g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0;
6201
6202 // Hide implicit/fallback "Debug" window if it hasn't been used
6203 g.WithinFrameScopeWithImplicitWindow = false;
6204 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
6205 g.CurrentWindow->Active = false;
6206 End();
6207
6208 // Update navigation: CTRL+Tab, wrap-around requests
6209 NavEndFrame();
6210
6211 // Update docking
6212 DockContextEndFrame(&g);
6213
6214 SetCurrentViewport(NULL, NULL);
6215
6216 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
6217 if (g.DragDropActive)
6218 {
6219 bool is_delivered = g.DragDropPayload.Delivery;
6220 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
6221 if (is_delivered || is_elapsed)
6222 ClearDragDrop();
6223 }
6224
6225 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
6226 // If you want to handle source item disappearing: instead of submitting your description tooltip
6227 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
6228 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
6229 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
6230 if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
6231 {
6232 g.DragDropWithinSource = true;
6233 SetTooltip("...");
6234 g.DragDropWithinSource = false;
6235 }
6236
6237 // Check for inertial scroll inhibit status
6238 if (!g.IO.MouseDown[ImGuiMouseButton_Left]) {
6239 g.InertialScrollInhibited=false;
6240 }
6241
6242 // End frame
6243 g.WithinFrameScope = false;
6244 g.FrameCountEnded = g.FrameCount;
6245 UpdateFontsEndFrame();
6246
6247 // Initiate moving window + handle left-click and right-click focus
6248 UpdateMouseMovingWindowEndFrame();
6249
6250 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
6251 UpdateViewportsEndFrame();
6252
6253 // Sort the window list so that all child windows are after their parent
6254 // We cannot do that on FocusWindow() because children may not exist yet
6255 g.WindowsTempSortBuffer.resize(0);
6256 g.WindowsTempSortBuffer.reserve(g.Windows.Size);
6257 for (ImGuiWindow* window : g.Windows)
6258 {
6259 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
6260 continue;
6261 AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
6262 }
6263
6264 // 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.
6265 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
6266 g.Windows.swap(g.WindowsTempSortBuffer);
6267 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
6268
6269 UpdateTexturesEndFrame();
6270
6271 // Unlock font atlas
6272 for (ImFontAtlas* atlas : g.FontAtlases)
6273 atlas->Locked = false;
6274
6275 // Clear Input data for next frame
6276 g.IO.MousePosPrev = g.IO.MousePos;
6277 g.IO.AppFocusLost = false;
6278 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
6279 g.IO.InputQueueCharacters.resize(0);
6280
6281 CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
6282 }
6283
6284 // Prepare the data for rendering so you can call GetDrawData()
6285 // (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all:
6286 // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
6287 void ImGui::Render()
6288 {
6289 ImGuiContext& g = *GImGui;
6290 IM_ASSERT(g.Initialized);
6291
6292 if (g.FrameCountEnded != g.FrameCount)
6293 EndFrame();
6294 if (g.FrameCountRendered == g.FrameCount)
6295 return;
6296 g.FrameCountRendered = g.FrameCount;
6297
6298 g.IO.MetricsRenderWindows = 0;
6299 CallContextHooks(&g, ImGuiContextHookType_RenderPre);
6300
6301 // Add background ImDrawList (for each active viewport)
6302 for (ImGuiViewportP* viewport : g.Viewports)
6303 {
6304 InitViewportDrawData(viewport);
6305 if (viewport->BgFgDrawLists[0] != NULL)
6306 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
6307 }
6308
6309 // Draw modal/window whitening backgrounds
6310 RenderDimmedBackgrounds();
6311
6312 // Add ImDrawList to render
6313 ImGuiWindow* windows_to_render_top_most[2];
6314 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
6315 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
6316 for (ImGuiWindow* window : g.Windows)
6317 {
6318 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
6319 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
6320 AddRootWindowToDrawData(window);
6321 }
6322 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
6323 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
6324 AddRootWindowToDrawData(windows_to_render_top_most[n]);
6325
6326 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
6327 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
6328 RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
6329
6330 // Setup ImDrawData structures for end-user
6331 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
6332 for (ImGuiViewportP* viewport : g.Viewports)
6333 {
6334 FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
6335
6336 // Add foreground ImDrawList (for each active viewport)
6337 if (viewport->BgFgDrawLists[1] != NULL)
6338 AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
6339
6340 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
6341 ImDrawData* draw_data = &viewport->DrawDataP;
6342 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
6343 for (ImDrawList* draw_list : draw_data->CmdLists)
6344 draw_list->_PopUnusedDrawCmd();
6345
6346 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
6347 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
6348 }
6349
6350 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
6351 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
6352 for (ImFontAtlas* atlas : g.FontAtlases)
6353 ImFontAtlasDebugLogTextureRequests(atlas);
6354 #endif
6355
6356 CallContextHooks(&g, ImGuiContextHookType_RenderPost);
6357 }
6358
6359 // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
6360 // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
6361 ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
6362 {
6363 ImGuiContext& g = *GImGui;
6364
6365 const char* text_display_end;
6366 if (hide_text_after_double_hash)
6367 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
6368 else
6369 text_display_end = text_end;
6370
6371 ImFont* font = g.Font;
6372 const float font_size = g.FontSize;
6373 if (text == text_display_end)
6374 return ImVec2(0.0f, font_size);
6375 ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
6376
6377 // Round
6378 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
6379 // FIXME: Investigate using ceilf or e.g.
6380 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
6381 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
6382 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
6383
6384 return text_size;
6385 }
6386
6387 // Find window given position, search front-to-back
6388 // - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
6389 // - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
6390 // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
6391 // called, aka before the next Begin(). Moving window isn't affected.
6392 // - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
6393 void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
6394 {
6395 ImGuiContext& g = *GImGui;
6396 ImGuiWindow* hovered_window = NULL;
6397 ImGuiWindow* hovered_window_under_moving_window = NULL;
6398
6399 // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
6400 ImGuiViewportP* backup_moving_window_viewport = NULL;
6401 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6402 {
6403 backup_moving_window_viewport = g.MovingWindow->Viewport;
6404 g.MovingWindow->Viewport = g.MouseViewport;
6405 if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
6406 hovered_window = g.MovingWindow;
6407 }
6408
6409 ImVec2 padding_regular = g.Style.TouchExtraPadding;
6410 ImVec2 padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding));
6411 for (int i = g.Windows.Size - 1; i >= 0; i--)
6412 {
6413 ImGuiWindow* window = g.Windows[i];
6414 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6415 if (!window->WasActive || window->Hidden)
6416 continue;
6417 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
6418 continue;
6419 IM_ASSERT(window->Viewport);
6420 if (window->Viewport != g.MouseViewport)
6421 continue;
6422
6423 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
6424 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
6425 if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
6426 continue;
6427
6428 // Support for one rectangular hole in any given window
6429 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
6430 if (window->HitTestHoleSize.x != 0)
6431 {
6432 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
6433 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
6434 if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
6435 continue;
6436 }
6437
6438 if (find_first_and_in_any_viewport)
6439 {
6440 hovered_window = window;
6441 break;
6442 }
6443 else
6444 {
6445 if (hovered_window == NULL)
6446 hovered_window = window;
6447 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6448 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
6449 hovered_window_under_moving_window = window;
6450 if (hovered_window && hovered_window_under_moving_window)
6451 break;
6452 }
6453 }
6454
6455 *out_hovered_window = hovered_window;
6456 if (out_hovered_window_under_moving_window != NULL)
6457 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
6458 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6459 g.MovingWindow->Viewport = backup_moving_window_viewport;
6460 }
6461
6462 bool ImGui::IsItemActive()
6463 {
6464 ImGuiContext& g = *GImGui;
6465 if (g.ActiveId)
6466 return g.ActiveId == g.LastItemData.ID;
6467 return false;
6468 }
6469
6470 bool ImGui::IsItemActivated()
6471 {
6472 ImGuiContext& g = *GImGui;
6473 if (g.ActiveId)
6474 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
6475 return true;
6476 return false;
6477 }
6478
6479 bool ImGui::IsItemDeactivated()
6480 {
6481 ImGuiContext& g = *GImGui;
6482 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
6483 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
6484 return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount);
6485 }
6486
6487 bool ImGui::IsItemDeactivatedAfterEdit()
6488 {
6489 ImGuiContext& g = *GImGui;
6490 return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore;
6491 }
6492
6493 // == (GetItemID() == GetFocusID() && GetFocusID() != 0)
6494 bool ImGui::IsItemFocused()
6495 {
6496 ImGuiContext& g = *GImGui;
6497 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
6498 return false;
6499
6500 // Special handling for the dummy item after Begin() which represent the title bar or tab.
6501 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
6502 ImGuiWindow* window = g.CurrentWindow;
6503 if (g.LastItemData.ID == window->ID && window->WriteAccessed)
6504 return false;
6505
6506 return true;
6507 }
6508
6509 // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
6510 // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
6511 bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
6512 {
6513 return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
6514 }
6515
6516 bool ImGui::IsItemToggledOpen()
6517 {
6518 ImGuiContext& g = *GImGui;
6519 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
6520 }
6521
6522 // Call after a Selectable() or TreeNode() involved in multi-selection.
6523 // Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
6524 // This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
6525 // (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
6526 // return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
6527 bool ImGui::IsItemToggledSelection()
6528 {
6529 ImGuiContext& g = *GImGui;
6530 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
6531 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
6532 }
6533
6534 // IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
6535 // you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
6536 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
6537 bool ImGui::IsAnyItemHovered()
6538 {
6539 ImGuiContext& g = *GImGui;
6540 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
6541 }
6542
6543 bool ImGui::IsAnyItemActive()
6544 {
6545 ImGuiContext& g = *GImGui;
6546 return g.ActiveId != 0;
6547 }
6548
6549 bool ImGui::IsAnyItemFocused()
6550 {
6551 ImGuiContext& g = *GImGui;
6552 return g.NavId != 0 && g.NavCursorVisible;
6553 }
6554
6555 bool ImGui::IsItemVisible()
6556 {
6557 ImGuiContext& g = *GImGui;
6558 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
6559 }
6560
6561 bool ImGui::IsItemEdited()
6562 {
6563 ImGuiContext& g = *GImGui;
6564 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
6565 }
6566
6567 // Allow next item to be overlapped by subsequent items.
6568 // This works by requiring HoveredId to match for two subsequent frames,
6569 // so if a following items overwrite it our interactions will naturally be disabled.
6570 void ImGui::SetNextItemAllowOverlap()
6571 {
6572 ImGuiContext& g = *GImGui;
6573 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
6574 }
6575
6576 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6577 // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
6578 // FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
6579 void ImGui::SetItemAllowOverlap()
6580 {
6581 ImGuiContext& g = *GImGui;
6582 ImGuiID id = g.LastItemData.ID;
6583 if (g.HoveredId == id)
6584 g.HoveredIdAllowOverlap = true;
6585 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
6586 g.ActiveIdAllowOverlap = true;
6587 }
6588 #endif
6589
6590 // This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
6591 // FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
6592 void ImGui::SetActiveIdUsingAllKeyboardKeys()
6593 {
6594 ImGuiContext& g = *GImGui;
6595 IM_ASSERT(g.ActiveId != 0);
6596 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
6597 g.ActiveIdUsingAllKeyboardKeys = true;
6598 NavMoveRequestCancel();
6599 }
6600
6601 ImGuiID ImGui::GetItemID()
6602 {
6603 ImGuiContext& g = *GImGui;
6604 return g.LastItemData.ID;
6605 }
6606
6607 ImVec2 ImGui::GetItemRectMin()
6608 {
6609 ImGuiContext& g = *GImGui;
6610 return g.LastItemData.Rect.Min;
6611 }
6612
6613 ImVec2 ImGui::GetItemRectMax()
6614 {
6615 ImGuiContext& g = *GImGui;
6616 return g.LastItemData.Rect.Max;
6617 }
6618
6619 ImVec2 ImGui::GetItemRectSize()
6620 {
6621 ImGuiContext& g = *GImGui;
6622 return g.LastItemData.Rect.GetSize();
6623 }
6624
6625 // Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
6626 // ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
6627 bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6628 {
6629 ImGuiID id = GetCurrentWindow()->GetID(str_id);
6630 return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
6631 }
6632
6633 bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6634 {
6635 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
6636 }
6637
6638 bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6639 {
6640 ImGuiContext& g = *GImGui;
6641 ImGuiWindow* parent_window = g.CurrentWindow;
6642 IM_ASSERT(id != 0);
6643
6644 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
6645 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
6646 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
6647 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
6648 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
6649 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
6650 {
6651 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6652 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6653 }
6654 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6655 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
6656 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
6657 if (window_flags & ImGuiWindowFlags_NavFlattened)
6658 child_flags |= ImGuiChildFlags_NavFlattened;
6659 #endif
6660 if (child_flags & ImGuiChildFlags_AutoResizeX)
6661 child_flags &= ~ImGuiChildFlags_ResizeX;
6662 if (child_flags & ImGuiChildFlags_AutoResizeY)
6663 child_flags &= ~ImGuiChildFlags_ResizeY;
6664
6665 // Set window flags
6666 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
6667 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
6668 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
6669 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
6670 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
6671 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
6672
6673 // Special framed style
6674 if (child_flags & ImGuiChildFlags_FrameStyle)
6675 {
6676 PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
6677 PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
6678 PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
6679 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
6680 child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding;
6681 window_flags |= ImGuiWindowFlags_NoMove;
6682 }
6683
6684 // Forward size
6685 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
6686 // (the alternative would to store conditional flags per axis, which is possible but more code)
6687 const ImVec2 size_avail = GetContentRegionAvail();
6688 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
6689 ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
6690
6691 // A SetNextWindowSize() call always has priority (#8020)
6692 // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
6693 // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
6694 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
6695 {
6696 if (g.NextWindowData.SizeVal.x > 0.0f)
6697 {
6698 size.x = g.NextWindowData.SizeVal.x;
6699 child_flags &= ~ImGuiChildFlags_ResizeX;
6700 }
6701 if (g.NextWindowData.SizeVal.y > 0.0f)
6702 {
6703 size.y = g.NextWindowData.SizeVal.y;
6704 child_flags &= ~ImGuiChildFlags_ResizeY;
6705 }
6706 }
6707 SetNextWindowSize(size);
6708
6709 // Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
6710 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
6711 g.NextWindowData.ChildFlags |= child_flags;
6712 else
6713 g.NextWindowData.ChildFlags = child_flags;
6714 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
6715
6716 // 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.
6717 // 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.
6718 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
6719 const char* temp_window_name;
6720 /*if (name && parent_window->IDStack.back() == parent_window->ID)
6721 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
6722 else*/
6723 if (name)
6724 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
6725 else
6726 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
6727
6728 // Set style
6729 const float backup_border_size = g.Style.ChildBorderSize;
6730 if ((child_flags & ImGuiChildFlags_Borders) == 0)
6731 g.Style.ChildBorderSize = 0.0f;
6732
6733 // Begin into window
6734 const bool ret = Begin(temp_window_name, NULL, window_flags);
6735
6736 // Restore style
6737 g.Style.ChildBorderSize = backup_border_size;
6738 if (child_flags & ImGuiChildFlags_FrameStyle)
6739 {
6740 PopStyleVar(3);
6741 PopStyleColor();
6742 }
6743
6744 ImGuiWindow* child_window = g.CurrentWindow;
6745 child_window->ChildId = id;
6746
6747 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
6748 // While this is not really documented/defined, it seems that the expected thing to do.
6749 if (child_window->BeginCount == 1)
6750 parent_window->DC.CursorPos = child_window->Pos;
6751
6752 // Process navigation-in immediately so NavInit can run on first frame
6753 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
6754 const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
6755 if (g.ActiveId == temp_id_for_activation)
6756 ClearActiveID();
6757 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
6758 {
6759 FocusWindow(child_window);
6760 NavInitWindow(child_window, false);
6761 SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
6762 g.ActiveIdSource = g.NavInputSource;
6763 }
6764 return ret;
6765 }
6766
6767 void ImGui::EndChild()
6768 {
6769 ImGuiContext& g = *GImGui;
6770 ImGuiWindow* child_window = g.CurrentWindow;
6771
6772 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
6773 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
6774
6775 g.WithinEndChildID = child_window->ID;
6776 ImVec2 child_size = child_window->Size;
6777 End();
6778 if (child_window->BeginCount == 1)
6779 {
6780 ImGuiWindow* parent_window = g.CurrentWindow;
6781 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
6782 ItemSize(child_size);
6783 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
6784 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
6785 {
6786 ItemAdd(bb, child_window->ChildId);
6787 RenderNavCursor(bb, child_window->ChildId);
6788
6789 // 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)
6790 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
6791 RenderNavCursor(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavRenderCursorFlags_Compact);
6792 }
6793 else
6794 {
6795 // Not navigable into
6796 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
6797 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
6798 ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
6799
6800 // But when flattened we directly reach items, adjust active layer mask accordingly
6801 if (nav_flattened)
6802 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6803 }
6804 if (g.HoveredWindow == child_window)
6805 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6806 child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags;
6807 //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd()
6808 }
6809 else
6810 {
6811 SetLastItemDataForChildWindowItem(child_window, child_window->Rect());
6812 }
6813
6814 g.WithinEndChildID = backup_within_end_child_id;
6815 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6816 }
6817
6818 static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6819 {
6820 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
6821 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
6822 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6823 window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
6824 }
6825
6826 ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6827 {
6828 ImGuiContext& g = *GImGui;
6829 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6830 }
6831
6832 ImGuiWindow* ImGui::FindWindowByName(const char* name)
6833 {
6834 ImGuiID id = ImHashStr(name);
6835 return FindWindowByID(id);
6836 }
6837
6838 static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6839 {
6840 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6841 window->ViewportPos = main_viewport->Pos;
6842 if (settings->ViewportId)
6843 {
6844 window->ViewportId = settings->ViewportId;
6845 window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6846 }
6847 window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6848 if (settings->Size.x > 0 && settings->Size.y > 0)
6849 window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6850 window->Collapsed = settings->Collapsed;
6851 window->DockId = settings->DockId;
6852 window->DockOrder = settings->DockOrder;
6853 }
6854
6855 static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6856 {
6857 // Initial window state with e.g. default/arbitrary window position
6858 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6859 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6860 window->Pos = main_viewport->Pos + ImVec2(60, 60);
6861 window->Size = window->SizeFull = ImVec2(0, 0);
6862 window->ViewportPos = main_viewport->Pos;
6863 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6864
6865 if (settings != NULL)
6866 {
6867 SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6868 ApplyWindowSettings(window, settings);
6869 }
6870 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6871
6872 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6873 {
6874 window->AutoFitFramesX = window->AutoFitFramesY = 2;
6875 window->AutoFitOnlyGrows = false;
6876 }
6877 else
6878 {
6879 if (window->Size.x <= 0.0f)
6880 window->AutoFitFramesX = 2;
6881 if (window->Size.y <= 0.0f)
6882 window->AutoFitFramesY = 2;
6883 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6884 }
6885 }
6886
6887 static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags, const char* displayedName)
6888 {
6889 // Create window the first time
6890 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6891 ImGuiContext& g = *GImGui;
6892 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name, displayedName);
6893 window->Flags = flags;
6894 g.WindowsById.SetVoidPtr(window->ID, window);
6895
6896 ImGuiWindowSettings* settings = NULL;
6897 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6898 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6899 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6900
6901 InitOrLoadWindowSettings(window, settings);
6902
6903 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6904 g.Windows.push_front(window); // Quite slow but rare and only once
6905 else
6906 g.Windows.push_back(window);
6907
6908 return window;
6909 }
6910
6911 static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6912 {
6913 return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6914 }
6915
6916 static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6917 {
6918 return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6919 }
6920
6921 static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6922 {
6923 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6924 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6925 // Perhaps should tend further a neater test for this.
6926 ImGuiContext& g = *GImGui;
6927 ImVec2 size_min;
6928 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6929 {
6930 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6931 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6932 }
6933 else
6934 {
6935 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6936 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6937 }
6938
6939 // Reduce artifacts with very small windows
6940 ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6941 size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6942 return size_min;
6943 }
6944
6945 static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6946 {
6947 ImGuiContext& g = *GImGui;
6948 ImVec2 new_size = size_desired;
6949 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6950 {
6951 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6952 ImRect cr = g.NextWindowData.SizeConstraintRect;
6953 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6954 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6955 if (g.NextWindowData.SizeCallback)
6956 {
6957 ImGuiSizeCallbackData data;
6958 data.UserData = g.NextWindowData.SizeCallbackUserData;
6959 data.Pos = window->Pos;
6960 data.CurrentSize = window->SizeFull;
6961 data.DesiredSize = new_size;
6962 g.NextWindowData.SizeCallback(&data);
6963 new_size = data.DesiredSize;
6964 }
6965 new_size.x = IM_TRUNC(new_size.x);
6966 new_size.y = IM_TRUNC(new_size.y);
6967 }
6968
6969 // Minimum size
6970 ImVec2 size_min = CalcWindowMinSize(window);
6971 return ImMax(new_size, size_min);
6972 }
6973
6974 static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6975 {
6976 bool preserve_old_content_sizes = false;
6977 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6978 preserve_old_content_sizes = true;
6979 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6980 preserve_old_content_sizes = true;
6981 if (preserve_old_content_sizes)
6982 {
6983 *content_size_current = window->ContentSize;
6984 *content_size_ideal = window->ContentSizeIdeal;
6985 return;
6986 }
6987
6988 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6989 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6990 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);
6991 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);
6992 }
6993
6994 static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6995 {
6996 ImGuiContext& g = *GImGui;
6997 ImGuiStyle& style = g.Style;
6998 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6999 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
7000 ImVec2 size_pad = window->WindowPadding * 2.0f;
7001 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
7002
7003 // Determine maximum window size
7004 // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
7005 ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
7006 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
7007 {
7008 if (!window->ViewportOwned)
7009 size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
7010 const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
7011 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
7012 size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
7013 }
7014
7015 if (window->Flags & ImGuiWindowFlags_Tooltip)
7016 {
7017 // Tooltip always resize (up to maximum size)
7018 return ImMin(size_desired, size_max);
7019 }
7020 else
7021 {
7022 ImVec2 size_min = CalcWindowMinSize(window);
7023 ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max);
7024
7025 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
7026 // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
7027 // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
7028 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY)))
7029 size_auto_fit.y = window->SizeFull.y;
7030 else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX)))
7031 size_auto_fit.x = window->SizeFull.x;
7032
7033 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
7034 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
7035 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
7036 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);
7037 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);
7038 if (will_have_scrollbar_x)
7039 size_auto_fit.y += style.ScrollbarSize;
7040 if (will_have_scrollbar_y)
7041 size_auto_fit.x += style.ScrollbarSize;
7042 return size_auto_fit;
7043 }
7044 }
7045
7046 ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
7047 {
7048 ImVec2 size_contents_current;
7049 ImVec2 size_contents_ideal;
7050 CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
7051 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
7052 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
7053 return size_final;
7054 }
7055
7056 static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
7057 {
7058 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
7059 return ImGuiCol_PopupBg;
7060 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
7061 return ImGuiCol_ChildBg;
7062 return ImGuiCol_WindowBg;
7063 }
7064
7065 static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
7066 {
7067 ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
7068 ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
7069 ImVec2 size_expected = pos_max - pos_min;
7070 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
7071 *out_pos = pos_min;
7072 if (corner_norm.x == 0.0f)
7073 out_pos->x -= (size_constrained.x - size_expected.x);
7074 if (corner_norm.y == 0.0f)
7075 out_pos->y -= (size_constrained.y - size_expected.y);
7076 *out_size = size_constrained;
7077 }
7078
7079 // Data for resizing from resize grip / corner
7080 struct ImGuiResizeGripDef
7081 {
7082 ImVec2 CornerPosN;
7083 ImVec2 InnerDir;
7084 int AngleMin12, AngleMax12;
7085 };
7086 static const ImGuiResizeGripDef resize_grip_def[4] =
7087 {
7088 { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
7089 { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
7090 { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
7091 { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
7092 };
7093
7094 // Data for resizing from borders
7095 struct ImGuiResizeBorderDef
7096 {
7097 ImVec2 InnerDir; // Normal toward inside
7098 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
7099 float OuterAngle; // Angle toward outside
7100 };
7101 static const ImGuiResizeBorderDef resize_border_def[4] =
7102 {
7103 { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
7104 { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
7105 { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
7106 { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
7107 };
7108
7109 static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
7110 {
7111 ImRect rect = window->Rect();
7112 if (thickness == 0.0f)
7113 rect.Max -= ImVec2(1, 1);
7114 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); }
7115 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); }
7116 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); }
7117 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); }
7118 IM_ASSERT(0);
7119 return ImRect();
7120 }
7121
7122 // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
7123 ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
7124 {
7125 IM_ASSERT(n >= 0 && n < 4);
7126 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
7127 id = ImHashStr("#RESIZE", 0, id);
7128 id = ImHashData(&n, sizeof(int), id);
7129 return id;
7130 }
7131
7132 // Borders (Left, Right, Up, Down)
7133 ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
7134 {
7135 IM_ASSERT(dir >= 0 && dir < 4);
7136 int n = (int)dir + 4;
7137 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
7138 id = ImHashStr("#RESIZE", 0, id);
7139 id = ImHashData(&n, sizeof(int), id);
7140 return id;
7141 }
7142
7143 // Handle resize for: Resize Grips, Borders, Gamepad
7144 // Return true when using auto-fit (double-click on resize grip)
7145 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)
7146 {
7147 ImGuiContext& g = *GImGui;
7148 ImGuiWindowFlags flags = window->Flags;
7149
7150 if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7151 return false;
7152 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
7153 return false;
7154 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
7155 return false;
7156
7157 int ret_auto_fit_mask = 0x00;
7158 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7159 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
7160 const float grip_hover_outer_size = g.WindowsBorderHoverPadding;
7161
7162 ImRect clamp_rect = visibility_rect;
7163 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
7164 if (window_move_from_title_bar)
7165 clamp_rect.Min.y -= window->TitleBarHeight;
7166
7167 ImVec2 pos_target(FLT_MAX, FLT_MAX);
7168 ImVec2 size_target(FLT_MAX, FLT_MAX);
7169
7170 // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
7171 // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
7172 // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
7173 // - 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.
7174 // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
7175 // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
7176 const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
7177 if (clip_with_viewport_rect)
7178 window->ClipRect = window->Viewport->GetMainRect();
7179
7180 // Resize grips and borders are on layer 1
7181 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7182
7183 // Manual resize grips
7184 PushID("#RESIZE");
7185 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7186 {
7187 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
7188 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
7189
7190 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
7191 bool hovered, held;
7192 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
7193 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
7194 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
7195 ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
7196 ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
7197 ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7198 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
7199 if (hovered || held)
7200 SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
7201
7202 if (held && g.IO.MouseDoubleClicked[0])
7203 {
7204 // Auto-fit when double-clicking
7205 size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
7206 ret_auto_fit_mask = 0x03; // Both axes
7207 ClearActiveID();
7208 }
7209 else if (held)
7210 {
7211 // Resize from any of the four corners
7212 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
7213 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);
7214 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);
7215 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
7216 corner_target = ImClamp(corner_target, clamp_min, clamp_max);
7217 CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
7218 }
7219
7220 // Only lower-left grip is visible before hovering/activating
7221 if (resize_grip_n == 0 || held || hovered)
7222 resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
7223 }
7224
7225 int resize_border_mask = 0x00;
7226 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7227 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
7228 else
7229 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
7230 for (int border_n = 0; border_n < 4; border_n++)
7231 {
7232 if ((resize_border_mask & (1 << border_n)) == 0)
7233 continue;
7234 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7235 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
7236
7237 bool hovered, held;
7238 ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding);
7239 ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
7240 ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
7241 ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7242 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
7243 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
7244 hovered = false;
7245 if (hovered || held)
7246 SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
7247 if (held && g.IO.MouseDoubleClicked[0])
7248 {
7249 // Double-clicking bottom or right border auto-fit on this axis
7250 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
7251 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
7252 if (border_n == 1 || border_n == 3) // Right and bottom border
7253 {
7254 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
7255 ret_auto_fit_mask |= (1 << axis);
7256 hovered = held = false; // So border doesn't show highlighted at new position
7257 }
7258 ClearActiveID();
7259 }
7260 else if (held)
7261 {
7262 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
7263 // 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.
7264 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
7265 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
7266 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
7267 {
7268 g.WindowResizeBorderExpectedRect = border_rect;
7269 g.WindowResizeRelativeMode = false;
7270 }
7271 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
7272 g.WindowResizeRelativeMode = true;
7273
7274 const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
7275 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
7276 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above.
7277
7278 // Use absolute mode position
7279 ImVec2 border_target = window->Pos;
7280 border_target[axis] = border_target_abs_mode_for_axis;
7281
7282 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
7283 bool ignore_resize = false;
7284 if (g.WindowResizeRelativeMode)
7285 {
7286 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
7287 border_target[axis] = border_target_rel_mode_for_axis;
7288 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))
7289 ignore_resize = true;
7290 }
7291
7292 // Clamp, apply
7293 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);
7294 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
7295 border_target = ImClamp(border_target, clamp_min, clamp_max);
7296 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
7297 {
7298 ImGuiWindow* parent_window = window->ParentWindow;
7299 ImGuiWindowFlags parent_flags = parent_window->Flags;
7300 ImRect border_limit_rect = parent_window->InnerRect;
7301 border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
7302 if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
7303 border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
7304 if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
7305 border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
7306 }
7307 if (!ignore_resize)
7308 CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
7309 }
7310 if (hovered)
7311 *border_hovered = border_n;
7312 if (held)
7313 *border_held = border_n;
7314 }
7315 PopID();
7316
7317 // Restore nav layer
7318 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7319
7320 // Navigation resize (keyboard/gamepad)
7321 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
7322 // Not even sure the callback works here.
7323 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
7324 {
7325 ImVec2 nav_resize_dir;
7326 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
7327 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
7328 if (g.NavInputSource == ImGuiInputSource_Gamepad)
7329 nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
7330 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
7331 {
7332 const float NAV_RESIZE_SPEED = 600.0f;
7333 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
7334 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
7335 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
7336 g.NavWindowingToggleLayer = false;
7337 g.NavHighlightItemUnderNav = true;
7338 resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
7339 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
7340 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
7341 {
7342 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
7343 size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
7344 g.NavWindowingAccumDeltaSize -= accum_floored;
7345 }
7346 }
7347 }
7348
7349 // Apply back modified position/size to window
7350 const ImVec2 curr_pos = window->Pos;
7351 const ImVec2 curr_size = window->SizeFull;
7352 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x)) {
7353 window->Size.x = window->SizeFull.x = size_target.x;
7354 g.InertialScrollInhibited=true;
7355 }
7356 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y)) {
7357 window->Size.y = window->SizeFull.y = size_target.y;
7358 g.InertialScrollInhibited=true;
7359 }
7360 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
7361 window->Pos.x = ImTrunc(pos_target.x);
7362 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
7363 window->Pos.y = ImTrunc(pos_target.y);
7364 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)
7365 MarkIniSettingsDirty(window);
7366
7367 // Recalculate next expected border expected coordinates
7368 if (*border_held != -1)
7369 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding);
7370
7371 return ret_auto_fit_mask;
7372 }
7373
7374 static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
7375 {
7376 ImGuiContext& g = *GImGui;
7377 ImVec2 size_for_clamping = window->Size;
7378 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
7379 size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
7380 else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7381 size_for_clamping.y = window->TitleBarHeight;
7382 window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
7383 }
7384
7385 static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
7386 {
7387 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7388 const float rounding = window->WindowRounding;
7389 const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
7390 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);
7391 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);
7392 window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
7393 }
7394
7395 static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
7396 {
7397 ImGuiContext& g = *GImGui;
7398 const float border_size = window->WindowBorderSize;
7399 const ImU32 border_col = GetColorU32(ImGuiCol_Border);
7400 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
7401 window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
7402 else if (border_size > 0.0f)
7403 {
7404 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
7405 RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
7406 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
7407 RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
7408 }
7409 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
7410 {
7411 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
7412 const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
7413 RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
7414 }
7415 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7416 {
7417 float y = window->Pos.y + window->TitleBarHeight - 1;
7418 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);
7419 }
7420 }
7421
7422 // Draw background and borders
7423 // Draw and handle scrollbars
7424 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)
7425 {
7426 ImGuiContext& g = *GImGui;
7427 ImGuiStyle& style = g.Style;
7428 ImGuiWindowFlags flags = window->Flags;
7429
7430 // Ensure that Scrollbar() doesn't read last frame's SkipItems
7431 IM_ASSERT(window->BeginCount == 0);
7432 window->SkipItems = false;
7433 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7434
7435 // Draw window + handle manual resize
7436 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
7437 const float window_rounding = window->WindowRounding;
7438 const float window_border_size = window->WindowBorderSize;
7439 if (window->Collapsed)
7440 {
7441 // Title bar only
7442 const float backup_border_size = style.FrameBorderSize;
7443 g.Style.FrameBorderSize = window->WindowBorderSize;
7444 ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
7445 if (window->ViewportOwned)
7446 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)
7447 RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
7448 g.Style.FrameBorderSize = backup_border_size;
7449 }
7450 else
7451 {
7452 // Window background
7453 if (!(flags & ImGuiWindowFlags_NoBackground))
7454 {
7455 bool is_docking_transparent_payload = false;
7456 if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
7457 if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
7458 is_docking_transparent_payload = true;
7459
7460 ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
7461 if (window->ViewportOwned)
7462 {
7463 bg_col |= IM_COL32_A_MASK; // No alpha
7464 if (is_docking_transparent_payload)
7465 window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
7466 }
7467 else
7468 {
7469 // Adjust alpha. For docking
7470 bool override_alpha = false;
7471 float alpha = 1.0f;
7472 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha)
7473 {
7474 alpha = g.NextWindowData.BgAlphaVal;
7475 override_alpha = true;
7476 }
7477 if (is_docking_transparent_payload)
7478 {
7479 alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
7480 override_alpha = true;
7481 }
7482 if (override_alpha)
7483 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
7484 }
7485
7486 // Render, for docked windows and host windows we ensure bg goes before decorations
7487 if (window->DockIsActive)
7488 window->DockNode->LastBgColor = bg_col;
7489 ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
7490 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7491 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
7492 bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
7493 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7494 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
7495 }
7496 if (window->DockIsActive)
7497 window->DockNode->IsBgDrawnThisFrame = true;
7498
7499 // Title bar
7500 // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
7501 // in order for their pos/size to be matching their undocking state.)
7502 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7503 {
7504 ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
7505 if (window->ViewportOwned)
7506 title_bar_col |= IM_COL32_A_MASK; // No alpha
7507 window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
7508 }
7509
7510 // Menu bar
7511 if (flags & ImGuiWindowFlags_MenuBar)
7512 {
7513 ImRect menu_bar_rect = window->MenuBarRect();
7514 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.
7515 window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
7516 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
7517 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);
7518 }
7519
7520 // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
7521 ImGuiDockNode* node = window->DockNode;
7522 if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar() && !(node->MergedFlags & ImGuiDockNodeFlags_NoMove))
7523 {
7524 float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
7525 float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
7526 ImVec2 p = node->Pos;
7527 ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
7528 ImGuiID unhide_id = window->GetID("#UNHIDE");
7529 KeepAliveID(unhide_id);
7530 bool hovered, held;
7531 // TODO: tildearrow: test whether we still need workaround for #5325 (how did I not remove that yet?)
7532 if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
7533 node->WantHiddenTabBarToggle = true;
7534 else if (held && IsMouseDragging(0))
7535 StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
7536
7537 // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
7538 ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
7539 window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
7540 }
7541
7542 // Scrollbars
7543 if (window->ScrollbarX)
7544 Scrollbar(ImGuiAxis_X);
7545 if (window->ScrollbarY)
7546 Scrollbar(ImGuiAxis_Y);
7547
7548 // Render resize grips (after their input handling so we don't have a frame of latency)
7549 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
7550 {
7551 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7552 {
7553 const ImU32 col = resize_grip_col[resize_grip_n];
7554 if ((col & IM_COL32_A_MASK) == 0)
7555 continue;
7556 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
7557 const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
7558 const float border_inner = IM_ROUND(window_border_size * 0.5f);
7559 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner)));
7560 window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size)));
7561 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);
7562 window->DrawList->PathFillConvex(col);
7563 }
7564 }
7565
7566 // Borders (for dock node host they will be rendered over after the tab bar)
7567 if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
7568 RenderWindowOuterBorders(window);
7569 }
7570 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7571 }
7572
7573 // When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
7574 // Render title text, collapse button, close button
7575 void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
7576 {
7577 ImGuiContext& g = *GImGui;
7578 ImGuiStyle& style = g.Style;
7579 ImGuiWindowFlags flags = window->Flags;
7580
7581 const bool has_close_button = (p_open != NULL);
7582 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
7583
7584 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
7585 // 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?
7586 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
7587 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
7588 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7589
7590 // Layout buttons
7591 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
7592 float pad_l = style.FramePadding.x;
7593 float pad_r = style.FramePadding.x;
7594 float button_sz = g.FontSize;
7595 ImVec2 close_button_pos;
7596 ImVec2 collapse_button_pos;
7597 if (has_close_button)
7598 {
7599 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7600 pad_r += button_sz + style.ItemInnerSpacing.x;
7601 }
7602 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
7603 {
7604 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7605 pad_r += button_sz + style.ItemInnerSpacing.x;
7606 }
7607 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
7608 {
7609 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
7610 pad_l += button_sz + style.ItemInnerSpacing.x;
7611 }
7612
7613 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
7614 if (has_collapse_button)
7615 if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
7616 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
7617
7618 // Close button
7619 if (has_close_button)
7620 {
7621 g.CurrentItemFlags |= ImGuiItemFlags_NoFocus;
7622 if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
7623 *p_open = false;
7624 g.CurrentItemFlags &= ~ImGuiItemFlags_NoFocus;
7625 }
7626
7627 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7628 g.CurrentItemFlags = item_flags_backup;
7629
7630 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
7631 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
7632 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
7633 const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
7634
7635 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
7636 // while uncentered title text will still reach edges correctly.
7637 if (pad_l > style.FramePadding.x)
7638 pad_l += g.Style.ItemInnerSpacing.x;
7639 if (pad_r > style.FramePadding.x)
7640 pad_r += g.Style.ItemInnerSpacing.x;
7641 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
7642 {
7643 float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
7644 float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
7645 pad_l = ImMax(pad_l, pad_extend * centerness);
7646 pad_r = ImMax(pad_r, pad_extend * centerness);
7647 }
7648
7649 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);
7650 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);
7651 if (flags & ImGuiWindowFlags_UnsavedDocument)
7652 {
7653 ImVec2 marker_pos;
7654 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);
7655 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
7656 if (marker_pos.x > layout_r.Min.x)
7657 {
7658 RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
7659 clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
7660 }
7661 }
7662 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7663 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7664 RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
7665 }
7666
7667 void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
7668 {
7669 window->ParentWindow = parent_window;
7670 window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
7671 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
7672 {
7673 window->RootWindowDockTree = parent_window->RootWindowDockTree;
7674 if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
7675 window->RootWindow = parent_window->RootWindow;
7676 }
7677 if (parent_window && (flags & ImGuiWindowFlags_Popup))
7678 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
7679 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
7680 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
7681 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
7682 {
7683 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
7684 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
7685 }
7686 }
7687
7688 // [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
7689 // This is designed as a toy/test-bed for
7690 void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
7691 {
7692 ImGuiContext& g = *GImGui;
7693 window->SkipRefresh = false;
7694 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
7695 return;
7696 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
7697 {
7698 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
7699 if (window->Appearing) // If currently appearing
7700 return;
7701 if (window->Hidden) // If was hidden (previous frame)
7702 return;
7703 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow)
7704 if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, window))
7705 return;
7706 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow)
7707 if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(g.NavWindow->RootWindow, window))
7708 return;
7709 window->DrawList = NULL;
7710 window->SkipRefresh = true;
7711 }
7712 }
7713
7714 static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
7715 {
7716 window->Active = true;
7717 for (ImGuiWindow* child : window->DC.ChildWindows)
7718 if (!child->Hidden)
7719 {
7720 child->Active = child->SkipRefresh = true;
7721 SetWindowActiveForSkipRefresh(child);
7722 }
7723 }
7724
7725 // Push a new Dear ImGui window to add widgets to.
7726 // - 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.
7727 // - Begin/End can be called multiple times during the frame with the same window name to append content.
7728 // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
7729 // 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.
7730 // - 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.
7731 // - 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.
7732 bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags, const char* displayedName)
7733 {
7734 ImGuiContext& g = *GImGui;
7735 const ImGuiStyle& style = g.Style;
7736 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
7737 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
7738 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
7739
7740 // Find or create
7741 ImGuiWindow* window = FindWindowByName(name);
7742 const bool window_just_created = (window == NULL);
7743 if (window_just_created)
7744 window = CreateNewWindow(name, flags, displayedName);
7745
7746 // [DEBUG] Debug break requested by user
7747 if (g.DebugBreakInWindow == window->ID)
7748 IM_DEBUG_BREAK();
7749
7750 // Automatically disable manual moving/resizing when NoInputs is set
7751 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
7752 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
7753
7754 const int current_frame = g.FrameCount;
7755 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
7756 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
7757
7758 // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
7759 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
7760 if (flags & ImGuiWindowFlags_Popup)
7761 {
7762 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7763 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
7764 window_just_activated_by_user |= (window != popup_ref.Window);
7765 }
7766
7767 // Update Flags, LastFrameActive, BeginOrderXXX fields
7768 const bool window_was_appearing = window->Appearing;
7769 if (first_begin_of_the_frame)
7770 {
7771 UpdateWindowInFocusOrderList(window, window_just_created, flags);
7772 window->Appearing = window_just_activated_by_user;
7773 if (window->Appearing)
7774 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7775 window->FlagsPreviousFrame = window->Flags;
7776 window->Flags = (ImGuiWindowFlags)flags;
7777 window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7778 window->LastFrameActive = current_frame;
7779 window->LastTimeActive = (float)g.Time;
7780 window->BeginOrderWithinParent = 0;
7781 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7782 }
7783 else
7784 {
7785 flags = window->Flags;
7786 }
7787
7788 // Docking
7789 // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7790 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7791 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasDock)
7792 SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
7793 if (first_begin_of_the_frame)
7794 {
7795 bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7796 bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7797 bool dock_node_was_visible = window->DockNodeIsVisible;
7798 bool dock_tab_was_visible = window->DockTabIsVisible;
7799 if (has_dock_node || new_auto_dock_node)
7800 {
7801 BeginDocked(window, p_open);
7802 flags = window->Flags;
7803 if (window->DockIsActive)
7804 {
7805 IM_ASSERT(window->DockNode != NULL);
7806 g.NextWindowData.HasFlags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7807 }
7808
7809 // Amend the Appearing flag
7810 if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7811 {
7812 window->Appearing = true;
7813 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7814 }
7815 }
7816 else
7817 {
7818 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7819 }
7820 }
7821
7822 // 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
7823 ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7824 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7825 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7826
7827 // We allow window memory to be compacted so recreate the base stack when needed.
7828 if (window->IDStack.Size == 0)
7829 window->IDStack.push_back(window->ID);
7830
7831 // Add to stack
7832 g.CurrentWindow = window;
7833 g.CurrentWindowStack.resize(g.CurrentWindowStack.Size + 1);
7834 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7835 window_stack_data.Window = window;
7836 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7837 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7838 window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f;
7839 ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin);
7840 g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
7841 if (flags & ImGuiWindowFlags_ChildMenu)
7842 g.BeginMenuDepth++;
7843
7844 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7845 if (first_begin_of_the_frame)
7846 {
7847 UpdateWindowParentAndRootLinks(window, flags, parent_window);
7848 window->ParentWindowInBeginStack = parent_window_in_stack;
7849
7850 // Focus route
7851 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7852 // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7853 window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7854 if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7855 if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7856 window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7857
7858 // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7859 if (window->WindowClass.FocusRouteParentWindowId != 0)
7860 {
7861 window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7862 IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7863 }
7864
7865 // Inherit SetWindowFontScale() from parent until we fix this system...
7866 window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f;
7867 }
7868
7869 // Add to focus scope stack
7870 PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7871 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7872
7873 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7874 if (flags & ImGuiWindowFlags_Popup)
7875 {
7876 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7877 popup_ref.Window = window;
7878 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7879 g.BeginPopupStack.push_back(popup_ref);
7880 window->PopupId = popup_ref.PopupId;
7881 }
7882
7883 // Process SetNextWindow***() calls
7884 // (FIXME: Consider splitting the HasXXX flags into X/Y components
7885 bool window_pos_set_by_api = false;
7886 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7887 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos)
7888 {
7889 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7890 if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7891 {
7892 // May be processed on the next frame if this is our first frame and we are measuring size
7893 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7894 window->SetWindowPosVal = g.NextWindowData.PosVal;
7895 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7896 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7897 }
7898 else
7899 {
7900 SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7901 }
7902 }
7903 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize)
7904 {
7905 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7906 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7907 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7908 g.NextWindowData.SizeVal.x = window->SizeFull.x;
7909 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7910 g.NextWindowData.SizeVal.y = window->SizeFull.y;
7911 SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7912 }
7913 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll)
7914 {
7915 if (g.NextWindowData.ScrollVal.x >= 0.0f)
7916 {
7917 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7918 window->ScrollTargetCenterRatio.x = 0.0f;
7919 }
7920 if (g.NextWindowData.ScrollVal.y >= 0.0f)
7921 {
7922 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7923 window->ScrollTargetCenterRatio.y = 0.0f;
7924 }
7925 }
7926 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize)
7927 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7928 else if (first_begin_of_the_frame)
7929 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7930 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowClass)
7931 window->WindowClass = g.NextWindowData.WindowClass;
7932 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed)
7933 SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7934 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus)
7935 FocusWindow(window);
7936 if (window->Appearing)
7937 SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7938
7939 // [EXPERIMENTAL] Skip Refresh mode
7940 UpdateWindowSkipRefresh(window);
7941
7942 // Nested root windows (typically tooltips) override disabled state
7943 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7944 BeginDisabledOverrideReenable();
7945
7946 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7947 g.CurrentWindow = NULL;
7948
7949 // When reusing window again multiple times a frame, just append content (don't need to setup again)
7950 if (first_begin_of_the_frame && !window->SkipRefresh)
7951 {
7952 // Initialize
7953 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7954 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7955 window->Active = true;
7956 window->HasCloseButton = (p_open != NULL);
7957 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7958 window->IDStack.resize(1);
7959 window->DrawList->_ResetForNewFrame();
7960 window->DC.CurrentTableIdx = -1;
7961 if (flags & ImGuiWindowFlags_DockNodeHost)
7962 {
7963 window->DrawList->ChannelsSplit(2);
7964 window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7965 }
7966
7967 // Restore buffer capacity when woken from a compacted state, to avoid
7968 if (window->MemoryCompacted)
7969 GcAwakeTransientWindowBuffers(window);
7970
7971 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7972 // 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.
7973 bool window_title_visible_elsewhere = false;
7974 if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7975 window_title_visible_elsewhere = true;
7976 else if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
7977 window_title_visible_elsewhere = true;
7978 else if (flags & ImGuiWindowFlags_ChildMenu)
7979 window_title_visible_elsewhere = true;
7980 if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7981 {
7982 size_t buf_len = (size_t)window->NameBufLen;
7983 window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7984 window->NameBufLen = (int)buf_len;
7985 }
7986
7987 if(window->DisplayedName)
7988 {
7989 if(strcmp(displayedName, window->DisplayedName) != 0)
7990 {
7991 // WAHAHAHAHA
7992 // you wrote free() instead of IM_DELETE() and broke portability HAHAHA
7993 IM_DELETE(window->DisplayedName);
7994 window->DisplayedName = ImStrdup(displayedName);
7995 }
7996 }
7997
7998 if(window->DisplayedName == NULL && displayedName != NULL)
7999 {
8000 window->DisplayedName = ImStrdup(displayedName);
8001 }
8002
8003 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
8004
8005 // Update contents size from last frame for auto-fitting (or use explicit size)
8006 CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
8007
8008 // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
8009 // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
8010 // it has a single usage before this code block and may be set below before it is finally checked.
8011 if (window->HiddenFramesCanSkipItems > 0)
8012 window->HiddenFramesCanSkipItems--;
8013 if (window->HiddenFramesCannotSkipItems > 0)
8014 window->HiddenFramesCannotSkipItems--;
8015 if (window->HiddenFramesForRenderOnly > 0)
8016 window->HiddenFramesForRenderOnly--;
8017
8018 // Hide new windows for one frame until they calculate their size
8019 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
8020 window->HiddenFramesCannotSkipItems = 1;
8021
8022 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
8023 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
8024 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
8025 {
8026 window->HiddenFramesCannotSkipItems = 1;
8027 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
8028 {
8029 if (!window_size_x_set_by_api)
8030 window->Size.x = window->SizeFull.x = 0.f;
8031 if (!window_size_y_set_by_api)
8032 window->Size.y = window->SizeFull.y = 0.f;
8033 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
8034 }
8035 }
8036
8037 // SELECT VIEWPORT
8038 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
8039
8040 WindowSelectViewport(window);
8041 SetCurrentViewport(window, window->Viewport);
8042 SetCurrentWindow(window);
8043 flags = window->Flags;
8044
8045 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
8046 // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
8047
8048 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
8049 window->WindowBorderSize = style.ChildBorderSize;
8050 else
8051 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
8052 window->WindowPadding = style.WindowPadding;
8053 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
8054 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
8055
8056 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
8057 window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
8058 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
8059 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
8060 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
8061 window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window.
8062
8063 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
8064 // Those flags will be altered further down in the function depending on more conditions.
8065 bool use_current_size_for_scrollbar_x = window_just_created;
8066 bool use_current_size_for_scrollbar_y = window_just_created;
8067 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
8068 use_current_size_for_scrollbar_x = true;
8069 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
8070 use_current_size_for_scrollbar_y = true;
8071
8072 // Collapse window by double-clicking on title bar
8073 // 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
8074 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
8075 {
8076 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
8077 // so verify that we don't have items over the title bar.
8078 ImRect title_bar_rect = window->TitleBarRect();
8079 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
8080 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
8081 window->WantCollapseToggle = true;
8082 if (window->WantCollapseToggle)
8083 {
8084 window->Collapsed = !window->Collapsed;
8085 if (!window->Collapsed)
8086 use_current_size_for_scrollbar_y = true;
8087 MarkIniSettingsDirty(window);
8088 }
8089 }
8090 else
8091 {
8092 window->Collapsed = false;
8093 }
8094 window->WantCollapseToggle = false;
8095
8096 // SIZE
8097
8098 // Outer Decoration Sizes
8099 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
8100 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
8101 window->DecoOuterSizeX1 = 0.0f;
8102 window->DecoOuterSizeX2 = 0.0f;
8103 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
8104 window->DecoOuterSizeY2 = 0.0f;
8105 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
8106
8107 // Calculate auto-fit size, handle automatic resize
8108 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
8109 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
8110 {
8111 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
8112 if (!window_size_x_set_by_api)
8113 {
8114 window->SizeFull.x = size_auto_fit.x;
8115 use_current_size_for_scrollbar_x = true;
8116 }
8117 if (!window_size_y_set_by_api)
8118 {
8119 window->SizeFull.y = size_auto_fit.y;
8120 use_current_size_for_scrollbar_y = true;
8121 }
8122 }
8123 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
8124 {
8125 // Auto-fit may only grow window during the first few frames
8126 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
8127 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
8128 {
8129 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
8130 use_current_size_for_scrollbar_x = true;
8131 }
8132 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
8133 {
8134 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
8135 use_current_size_for_scrollbar_y = true;
8136 }
8137 if (!window->Collapsed)
8138 MarkIniSettingsDirty(window);
8139 }
8140
8141 // Apply minimum/maximum window size constraints and final size
8142 window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
8143 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
8144
8145 // POSITION
8146
8147 // Popup latch its initial position, will position itself when it appears next frame
8148 if (window_just_activated_by_user)
8149 {
8150 window->AutoPosLastDirection = ImGuiDir_None;
8151 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
8152 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
8153 }
8154
8155 // Position child window
8156 if (flags & ImGuiWindowFlags_ChildWindow)
8157 {
8158 IM_ASSERT(parent_window && parent_window->Active);
8159 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
8160 parent_window->DC.ChildWindows.push_back(window);
8161 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
8162 window->Pos = parent_window->DC.CursorPos;
8163 }
8164
8165 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
8166 if (window_pos_with_pivot)
8167 SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
8168 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
8169 window->Pos = FindBestWindowPosForPopup(window);
8170 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
8171 window->Pos = FindBestWindowPosForPopup(window);
8172 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
8173 window->Pos = FindBestWindowPosForPopup(window);
8174
8175 // Late create viewport if we don't fit within our current host viewport.
8176 if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
8177 if (!window->Viewport->GetMainRect().Contains(window->Rect()))
8178 {
8179 // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
8180 //ImGuiViewport* old_viewport = window->Viewport;
8181 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
8182
8183 // FIXME-DPI
8184 //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
8185 SetCurrentViewport(window, window->Viewport);
8186 SetCurrentWindow(window);
8187 }
8188
8189 if (window->ViewportOwned)
8190 WindowSyncOwnedViewport(window, parent_window_in_stack);
8191
8192 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
8193 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
8194 ImRect viewport_rect(window->Viewport->GetMainRect());
8195 ImRect viewport_work_rect(window->Viewport->GetWorkRect());
8196 ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
8197 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
8198
8199 // Clamp position/size so window stays visible within its viewport or monitor
8200 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
8201 // FIXME: Similar to code in GetWindowAllowedExtentRect()
8202 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
8203 {
8204 if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
8205 {
8206 ClampWindowPos(window, visibility_rect);
8207 }
8208 else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
8209 {
8210 if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
8211 {
8212 // While moving windows we allow them to straddle monitors (#7299, #3071)
8213 visibility_rect = g.PlatformMonitorsFullWorkRect;
8214 }
8215 else
8216 {
8217 // When not moving ensure visible in its monitor
8218 // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
8219 const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
8220 visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
8221 }
8222 visibility_rect.Expand(-visibility_padding);
8223 ClampWindowPos(window, visibility_rect);
8224 }
8225 }
8226 window->Pos = ImTrunc(window->Pos);
8227
8228 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
8229 // Large values tend to lead to variety of artifacts and are not recommended.
8230 if (window->ViewportOwned || window->DockIsActive)
8231 window->WindowRounding = 0.0f;
8232 else
8233 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
8234
8235 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
8236 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
8237 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
8238
8239 // Apply window focus (new and reactivated windows are moved to front)
8240 bool want_focus = false;
8241 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
8242 {
8243 if (flags & ImGuiWindowFlags_Popup)
8244 want_focus = true;
8245 else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
8246 want_focus = true;
8247 }
8248
8249 // [Test Engine] Register whole window in the item system (before submitting further decorations)
8250 #ifdef IMGUI_ENABLE_TEST_ENGINE
8251 if (g.TestEngineHookItems)
8252 {
8253 IM_ASSERT(window->IDStack.Size == 1);
8254 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
8255 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8256 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
8257 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
8258 window->IDStack.Size = 1;
8259 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8260
8261 }
8262 #endif
8263
8264 // Decide if we are going to handle borders and resize grips
8265 // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815)
8266 // Whenever we add support for full decorated child windows we will likely make this logic more general.
8267 bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
8268 if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems)
8269 handle_borders_and_resize_grips = false;
8270
8271 // Handle manual resize: Resize Grips, Borders, Gamepad
8272 int border_hovered = -1, border_held = -1;
8273 ImU32 resize_grip_col[4] = {};
8274 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.
8275 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
8276 if (handle_borders_and_resize_grips && !window->Collapsed)
8277 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
8278 {
8279 if (auto_fit_mask & (1 << ImGuiAxis_X))
8280 use_current_size_for_scrollbar_x = true;
8281 if (auto_fit_mask & (1 << ImGuiAxis_Y))
8282 use_current_size_for_scrollbar_y = true;
8283 }
8284 window->ResizeBorderHovered = (signed char)border_hovered;
8285 window->ResizeBorderHeld = (signed char)border_held;
8286
8287 // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
8288 if (window->ViewportOwned)
8289 {
8290 if (!window->Viewport->PlatformRequestMove)
8291 window->Viewport->Pos = window->Pos;
8292 if (!window->Viewport->PlatformRequestResize)
8293 window->Viewport->Size = window->Size;
8294 window->Viewport->UpdateWorkRect();
8295 viewport_rect = window->Viewport->GetMainRect();
8296 }
8297
8298 // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
8299 window->ViewportPos = window->Viewport->Pos;
8300
8301 // SCROLLBAR VISIBILITY
8302
8303 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
8304 if (!window->Collapsed)
8305 {
8306 // When reading the current size we need to read it after size constraints have been applied.
8307 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
8308 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
8309 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
8310 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
8311 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
8312 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
8313 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
8314 bool scrollbar_x_prev = window->ScrollbarX;
8315 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
8316 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
8317 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));
8318
8319 // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
8320 // (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.
8321 // 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)
8322 window->ScrollbarXStabilizeToggledHistory <<= 1;
8323 window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00;
8324 const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history.
8325 if (scrollbar_x_stabilize)
8326 window->ScrollbarX = true;
8327 //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled)
8328 // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name);
8329 window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize;
8330
8331 if (window->ScrollbarX && !window->ScrollbarY)
8332 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
8333 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
8334
8335 // Amend the partially filled window->DecorationXXX values.
8336 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
8337 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
8338 }
8339
8340 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
8341 // Update various regions. Variables they depend on should be set above in this function.
8342 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
8343
8344 // Outer rectangle
8345 // Not affected by window border size. Used by:
8346 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
8347 // - Begin() initial clipping rect for drawing window background and borders.
8348 // - Begin() clipping whole child
8349 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
8350 const ImRect outer_rect = window->Rect();
8351 const ImRect title_bar_rect = window->TitleBarRect();
8352 window->OuterRectClipped = outer_rect;
8353 if (window->DockIsActive)
8354 window->OuterRectClipped.Min.y += window->TitleBarHeight;
8355 window->OuterRectClipped.ClipWith(host_rect);
8356
8357 // Inner rectangle
8358 // Not affected by window border size. Used by:
8359 // - InnerClipRect
8360 // - ScrollToRectEx()
8361 // - NavUpdatePageUpPageDown()
8362 // - Scrollbar()
8363 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
8364 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
8365 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
8366 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
8367
8368 // Inner clipping rectangle.
8369 // - Extend a outside of normal work region up to borders.
8370 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
8371 // - It also makes clipped items be more noticeable.
8372 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
8373 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
8374 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
8375 // Affected by window/frame border size. Used by:
8376 // - Begin() initial clip rect
8377 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
8378
8379 // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner.
8380 // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize,
8381 // 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).
8382 window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f);
8383 window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size * 0.5f);
8384 window->InnerClipRect.Max.x = ImFloor(window->InnerRect.Max.x - window->WindowBorderSize * 0.5f);
8385 window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
8386 window->InnerClipRect.ClipWithFull(host_rect);
8387
8388 // SCROLLING
8389
8390 // Lock down maximum scrolling
8391 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
8392 // for right/bottom aligned items without creating a scrollbar.
8393 window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
8394 window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
8395
8396 // Inertial scroll
8397 if (g.IO.ConfigFlags & ImGuiConfigFlags_InertialScrollEnable) {
8398 if ((g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow) == window) {
8399 if ((g.IO.MouseDown[ImGuiMouseButton_Left] || g.IO.MouseReleased[ImGuiMouseButton_Left]) &&
8400 g.ActiveId!=GetWindowScrollbarID(window,ImGuiAxis_X) &&
8401 g.ActiveId!=GetWindowScrollbarID(window,ImGuiAxis_Y) &&
8402 !g.InertialScrollInhibited) {
8403 // launch inertial scroll
8404 if (g.IO.MouseClicked[ImGuiMouseButton_Left]) {
8405 window->InertialScrollSpeed=ImVec2(0.0f,0.0f);
8406 window->InertialScroll=false;
8407 g.InertialScroll=false;
8408 g.WasInertialScroll=false;
8409 } else {
8410 if (g.IO.MouseDragMaxDistanceSqr[ImGuiMouseButton_Left]>g.IO.ConfigInertialScrollToleranceSqr) {
8411 if (g.IO.MouseReleased[ImGuiMouseButton_Left]) {
8412 window->InertialScrollSpeed=ImVec2(window->ScrollbarX?-g.IO.MouseSpeed.x:0.0f,window->ScrollbarY?-g.IO.MouseSpeed.y:0.0f);
8413 window->InertialScroll=false;
8414 g.InertialScroll=false;
8415 } else {
8416 window->InertialScrollSpeed=ImVec2(window->ScrollbarX?-g.IO.MouseDelta.x:0.0f,window->ScrollbarY?-g.IO.MouseDelta.y:0.0f);
8417 if (window->ScrollbarX || window->ScrollbarY) {
8418 window->InertialScroll=true;
8419 g.InertialScroll=true;
8420 g.WasInertialScroll=true;
8421 }
8422 }
8423 } else {
8424 window->InertialScrollSpeed=ImVec2(0.0f,0.0f);
8425 window->InertialScroll=false;
8426 g.InertialScroll=false;
8427 }
8428 }
8429 } else if (g.InertialScrollInhibited) {
8430 window->InertialScrollSpeed=ImVec2(0.0f,0.0f);
8431 window->InertialScroll=false;
8432 g.InertialScroll=false;
8433 }
8434 }
8435
8436 if (window->ScrollTarget.x == FLT_MAX && window->ScrollTarget.y == FLT_MAX) {
8437 if (fabs(window->InertialScrollSpeed.x)>0.1f) {
8438 window->Scroll.x=window->Scroll.x+window->InertialScrollSpeed.x;
8439 window->InertialScrollSpeed.x*=0.95f;
8440 g.IO.IsSomethingHappening = true;
8441 } else {
8442 window->InertialScrollSpeed.x=0.0f;
8443 }
8444 if (fabs(window->InertialScrollSpeed.y)>0.1f) {
8445 window->Scroll.y=window->Scroll.y+window->InertialScrollSpeed.y;
8446 window->InertialScrollSpeed.y*=0.95f;
8447 g.IO.IsSomethingHappening = true;
8448 } else {
8449 window->InertialScrollSpeed.y=0.0f;
8450 }
8451 } else {
8452 window->InertialScrollSpeed.x=0.0f;
8453 window->InertialScrollSpeed.y=0.0f;
8454 window->InertialScroll=false;
8455 g.InertialScroll=false;
8456 }
8457
8458 if (g.IO.MouseDown[ImGuiMouseButton_Left]) {
8459 window->InertialScrollSpeed.x=0.0f;
8460 window->InertialScrollSpeed.y=0.0f;
8461 }
8462 }
8463
8464 // Apply scrolling
8465 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
8466 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
8467 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
8468
8469 // DRAWING
8470
8471 // Setup draw list and outer clipping rectangle
8472 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
8473 window->DrawList->PushTexture(g.Font->ContainerAtlas->TexRef);
8474 PushClipRect(host_rect.Min, host_rect.Max, false);
8475
8476 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
8477 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
8478 // 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)
8479 const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
8480 if (is_undocked_or_docked_visible)
8481 {
8482 bool render_decorations_in_parent = false;
8483 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
8484 {
8485 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
8486 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
8487 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
8488 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
8489 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
8490 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
8491 render_decorations_in_parent = true;
8492 }
8493 if (render_decorations_in_parent)
8494 window->DrawList = parent_window->DrawList;
8495
8496 // Handle title bar, scrollbar, resize grips and resize borders
8497 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
8498 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)));
8499 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
8500
8501 if (render_decorations_in_parent)
8502 window->DrawList = &window->DrawListInst;
8503 }
8504
8505 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
8506
8507 // Work rectangle.
8508 // Affected by window padding and border size. Used by:
8509 // - Columns() for right-most edge
8510 // - TreeNode(), CollapsingHeader() for right-most edge
8511 // - BeginTabBar() for right-most edge
8512 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
8513 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
8514 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)));
8515 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)));
8516 window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
8517 window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
8518 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
8519 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
8520 window->ParentWorkRect = window->WorkRect;
8521
8522 // [LEGACY] Content Region
8523 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
8524 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
8525 // Used by:
8526 // - Mouse wheel scrolling + many other things
8527 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
8528 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
8529 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)));
8530 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)));
8531
8532 // Setup drawing context
8533 // (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.)
8534 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
8535 window->DC.GroupOffset.x = 0.0f;
8536 window->DC.ColumnsOffset.x = 0.0f;
8537
8538 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
8539 // 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.
8540 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
8541 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
8542 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
8543 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
8544 window->DC.CursorPos = window->DC.CursorStartPos;
8545 window->DC.CursorPosPrevLine = window->DC.CursorPos;
8546 window->DC.CursorMaxPos = window->DC.CursorStartPos;
8547 window->DC.IdealMaxPos = window->DC.CursorStartPos;
8548 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
8549 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
8550 window->DC.IsSameLine = window->DC.IsSetPos = false;
8551
8552 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8553 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
8554 window->DC.NavLayersActiveMaskNext = 0x00;
8555 window->DC.NavIsScrollPushableX = true;
8556 window->DC.NavHideHighlightOneFrame = false;
8557 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
8558
8559 window->DC.MenuBarAppending = false;
8560 window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
8561 window->DC.TreeDepth = 0;
8562 window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00;
8563 window->DC.ChildWindows.resize(0);
8564 window->DC.StateStorage = &window->StateStorage;
8565 window->DC.CurrentColumns = NULL;
8566 window->DC.LayoutType = ImGuiLayoutType_Vertical;
8567 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
8568
8569 // Default item width. Make it proportional to window size if window manually resizes
8570 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
8571 window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
8572 else
8573 window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
8574 window->DC.ItemWidth = window->ItemWidthDefault;
8575 window->DC.TextWrapPos = -1.0f; // disabled
8576 window->DC.ItemWidthStack.resize(0);
8577 window->DC.TextWrapPosStack.resize(0);
8578 if (flags & ImGuiWindowFlags_Modal)
8579 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
8580
8581 if (window->AutoFitFramesX > 0)
8582 window->AutoFitFramesX--;
8583 if (window->AutoFitFramesY > 0)
8584 window->AutoFitFramesY--;
8585
8586 // Clear SetNextWindowXXX data (can aim to move this higher in the function)
8587 g.NextWindowData.ClearFlags();
8588
8589 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
8590 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
8591 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
8592 // - Position window behind the modal that is not a begin-parent of this window.
8593 if (want_focus)
8594 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
8595 if (want_focus && window == g.NavWindow)
8596 NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
8597
8598 // Close requested by platform window (apply to all windows in this viewport)
8599 if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
8600 {
8601 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
8602 *p_open = false;
8603 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.
8604 }
8605
8606 // Pressing CTRL+C copy window content into the clipboard
8607 // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
8608 // [EXPERIMENTAL] Text outputs has many issues.
8609 if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
8610 if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C))
8611 LogToClipboard(0);
8612
8613 // Title bar
8614 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
8615 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), displayedName == NULL ? name : displayedName, p_open);
8616 else if (!(flags & ImGuiWindowFlags_NoTitleBar) && window->DockIsActive)
8617 LogText("%.*s\n", (int)(FindRenderedTextEnd(window->Name) - window->Name), window->Name);
8618
8619 // Clear hit test shape every frame
8620 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
8621
8622 if (flags & ImGuiWindowFlags_Tooltip)
8623 g.TooltipPreviousWindow = window;
8624
8625 if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
8626 {
8627 // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
8628 // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
8629 if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
8630 BeginDockableDragDropSource(window);
8631
8632 // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
8633 if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
8634 if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
8635 if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
8636 BeginDockableDragDropTarget(window);
8637 }
8638
8639 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
8640 // This is useful to allow creating context menus on title bar only, etc.
8641 window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None;
8642 window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
8643 SetLastItemDataForWindow(window, title_bar_rect);
8644
8645 // [DEBUG]
8646 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8647 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
8648 DebugLocateItemResolveWithLastItem();
8649 #endif
8650
8651 // [Test Engine] Register title bar / tab with MoveId.
8652 #ifdef IMGUI_ENABLE_TEST_ENGINE
8653 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
8654 {
8655 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8656 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
8657 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8658 }
8659 #endif
8660 }
8661 else
8662 {
8663 // Skip refresh always mark active
8664 if (window->SkipRefresh)
8665 SetWindowActiveForSkipRefresh(window);
8666
8667 // Append
8668 SetCurrentViewport(window, window->Viewport);
8669 SetCurrentWindow(window);
8670 g.NextWindowData.ClearFlags();
8671 SetLastItemDataForWindow(window, window->TitleBarRect());
8672 }
8673
8674 if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
8675 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
8676
8677 // 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)
8678 window->WriteAccessed = false;
8679 window->BeginCount++;
8680
8681 // Update visibility
8682 if (first_begin_of_the_frame && !window->SkipRefresh)
8683 {
8684 // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
8685 // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
8686 // This is analogous to regular windows being hidden from one frame.
8687 // 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.
8688 if (window->DockIsActive && !window->DockTabIsVisible)
8689 {
8690 if (window->LastFrameJustFocused == g.FrameCount)
8691 window->HiddenFramesCannotSkipItems = 1;
8692 else
8693 window->HiddenFramesCanSkipItems = 1;
8694 }
8695
8696 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
8697 {
8698 // Child window can be out of sight and have "negative" clip windows.
8699 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
8700 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
8701 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
8702 if (!g.LogEnabled && !nav_request)
8703 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
8704 {
8705 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
8706 window->HiddenFramesCannotSkipItems = 1;
8707 else
8708 window->HiddenFramesCanSkipItems = 1;
8709 }
8710
8711 // Hide along with parent or if parent is collapsed
8712 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
8713 window->HiddenFramesCanSkipItems = 1;
8714 if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0)
8715 window->HiddenFramesCannotSkipItems = 1;
8716 }
8717
8718 // 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)
8719 if (style.Alpha <= 0.0f)
8720 window->HiddenFramesCanSkipItems = 1;
8721
8722 // Update the Hidden flag
8723 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
8724 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
8725
8726 // Disable inputs for requested number of frames
8727 if (window->DisableInputsFrames > 0)
8728 {
8729 window->DisableInputsFrames--;
8730 window->Flags |= ImGuiWindowFlags_NoInputs;
8731 }
8732
8733 // Update the SkipItems flag, used to early out of all items functions (no layout required)
8734 bool skip_items = false;
8735 if (window->Collapsed || !window->Active || hidden_regular)
8736 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
8737 skip_items = true;
8738 window->SkipItems = skip_items;
8739
8740 // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
8741 if (window->SkipItems)
8742 window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
8743
8744 // Sanity check: there are two spots which can set Appearing = true
8745 // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
8746 // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
8747 if (window->SkipItems && !window->Appearing)
8748 IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
8749 }
8750 else if (first_begin_of_the_frame)
8751 {
8752 // Skip refresh mode
8753 window->SkipItems = true;
8754 }
8755
8756 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
8757 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
8758 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8759 if (!window->IsFallbackWindow)
8760 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
8761 {
8762 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
8763 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
8764 return false;
8765 }
8766 #endif
8767
8768 return !window->SkipItems;
8769 }
8770
8771 void ImGui::End()
8772 {
8773 ImGuiContext& g = *GImGui;
8774 ImGuiWindow* window = g.CurrentWindow;
8775
8776 // Error checking: verify that user hasn't called End() too many times!
8777 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
8778 {
8779 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
8780 return;
8781 }
8782 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
8783
8784 // Error checking: verify that user doesn't directly call End() on a child window.
8785 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
8786 IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!");
8787
8788 // Close anything that is open
8789 if (window->DC.CurrentColumns)
8790 EndColumns();
8791 if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) // Pop inner window clip rectangle
8792 PopClipRect();
8793 PopFocusScope();
8794 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
8795 EndDisabledOverrideReenable();
8796
8797 if (window->SkipRefresh)
8798 {
8799 IM_ASSERT(window->DrawList == NULL);
8800 window->DrawList = &window->DrawListInst;
8801 }
8802
8803 // Stop logging
8804 if (g.LogWindow == window) // FIXME: add more options for scope of logging
8805 LogFinish();
8806
8807 if (window->DC.IsSetPos)
8808 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
8809
8810 // Docking: report contents sizes to parent to allow for auto-resize
8811 if (window->DockNode && window->DockTabIsVisible)
8812 if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
8813 host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
8814
8815 // Pop from window stack
8816 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
8817 if (window->Flags & ImGuiWindowFlags_ChildMenu)
8818 g.BeginMenuDepth--;
8819 if (window->Flags & ImGuiWindowFlags_Popup)
8820 g.BeginPopupStack.pop_back();
8821
8822 // Error handling, state recovery
8823 if (g.IO.ConfigErrorRecovery)
8824 ErrorRecoveryTryToRecoverWindowState(&window_stack_data.StackSizesInBegin);
8825
8826 g.CurrentWindowStack.pop_back();
8827 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
8828 if (g.CurrentWindow)
8829 SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
8830 }
8831
8832 void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8833 {
8834 ImGuiContext& g = *GImGui;
8835 ImGuiItemFlags item_flags = g.CurrentItemFlags;
8836 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8837 if (enabled)
8838 item_flags |= option;
8839 else
8840 item_flags &= ~option;
8841 g.CurrentItemFlags = item_flags;
8842 g.ItemFlagsStack.push_back(item_flags);
8843 }
8844
8845 void ImGui::PopItemFlag()
8846 {
8847 ImGuiContext& g = *GImGui;
8848 if (g.ItemFlagsStack.Size <= 1)
8849 {
8850 IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!");
8851 return;
8852 }
8853 g.ItemFlagsStack.pop_back();
8854 g.CurrentItemFlags = g.ItemFlagsStack.back();
8855 }
8856
8857 // BeginDisabled()/EndDisabled()
8858 // - 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)
8859 // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8860 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8861 // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
8862 // (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)
8863 // - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
8864 void ImGui::BeginDisabled(bool disabled)
8865 {
8866 ImGuiContext& g = *GImGui;
8867 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8868 if (!was_disabled && disabled)
8869 {
8870 g.DisabledAlphaBackup = g.Style.Alpha;
8871 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8872 }
8873 if (was_disabled || disabled)
8874 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8875 g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8876 g.DisabledStackSize++;
8877 }
8878
8879 void ImGui::EndDisabled()
8880 {
8881 ImGuiContext& g = *GImGui;
8882 if (g.DisabledStackSize <= 0)
8883 {
8884 IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!");
8885 return;
8886 }
8887 g.DisabledStackSize--;
8888 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8889 //PopItemFlag();
8890 g.ItemFlagsStack.pop_back();
8891 g.CurrentItemFlags = g.ItemFlagsStack.back();
8892 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8893 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8894 }
8895
8896 // IsInertialScroll()
8897
8898 bool ImGui::IsInertialScroll()
8899 {
8900 /*
8901 ImGuiWindow* window = GetCurrentWindow();
8902 if (window==NULL) return false;
8903 return window->InertialScroll;
8904 */
8905 ImGuiContext& g = *GImGui;
8906 return g.InertialScroll;
8907 }
8908
8909 // WasInertialScroll()
8910
8911 bool ImGui::WasInertialScroll()
8912 {
8913 ImGuiContext& g = *GImGui;
8914 return g.WasInertialScroll;
8915 }
8916
8917 // InhibitInertialScroll()
8918
8919 void ImGui::InhibitInertialScroll()
8920 {
8921 ImGuiContext& g = *GImGui;
8922 g.InertialScrollInhibited=true;
8923 }
8924
8925 // Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8926 // Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8927 // The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8928 void ImGui::BeginDisabledOverrideReenable()
8929 {
8930 ImGuiContext& g = *GImGui;
8931 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8932 g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha;
8933 g.Style.Alpha = g.DisabledAlphaBackup;
8934 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8935 g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8936 g.DisabledStackSize++;
8937 }
8938
8939 void ImGui::EndDisabledOverrideReenable()
8940 {
8941 ImGuiContext& g = *GImGui;
8942 g.DisabledStackSize--;
8943 IM_ASSERT(g.DisabledStackSize > 0);
8944 g.ItemFlagsStack.pop_back();
8945 g.CurrentItemFlags = g.ItemFlagsStack.back();
8946 g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup;
8947 }
8948
8949 void ImGui::PushTextWrapPos(float wrap_pos_x)
8950 {
8951 ImGuiContext& g = *GImGui;
8952 ImGuiWindow* window = g.CurrentWindow;
8953 window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8954 window->DC.TextWrapPos = wrap_pos_x;
8955 }
8956
8957 void ImGui::PopTextWrapPos()
8958 {
8959 ImGuiContext& g = *GImGui;
8960 ImGuiWindow* window = g.CurrentWindow;
8961 if (window->DC.TextWrapPosStack.Size <= 0)
8962 {
8963 IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
8964 return;
8965 }
8966 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8967 window->DC.TextWrapPosStack.pop_back();
8968 }
8969
8970 static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8971 {
8972 ImGuiWindow* last_window = NULL;
8973 while (last_window != window)
8974 {
8975 last_window = window;
8976 window = window->RootWindow;
8977 if (popup_hierarchy)
8978 window = window->RootWindowPopupTree;
8979 if (dock_hierarchy)
8980 window = window->RootWindowDockTree;
8981 }
8982 return window;
8983 }
8984
8985 bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8986 {
8987 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8988 if (window_root == potential_parent)
8989 return true;
8990 while (window != NULL)
8991 {
8992 if (window == potential_parent)
8993 return true;
8994 if (window == window_root) // end of chain
8995 return false;
8996 window = window->ParentWindow;
8997 }
8998 return false;
8999 }
9000
9001 bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
9002 {
9003 if (window->RootWindow == potential_parent)
9004 return true;
9005 while (window != NULL)
9006 {
9007 if (window == potential_parent)
9008 return true;
9009 window = window->ParentWindowInBeginStack;
9010 }
9011 return false;
9012 }
9013
9014 bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
9015 {
9016 ImGuiContext& g = *GImGui;
9017
9018 // 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
9019 const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
9020 if (display_layer_delta != 0)
9021 return display_layer_delta > 0;
9022
9023 for (int i = g.Windows.Size - 1; i >= 0; i--)
9024 {
9025 ImGuiWindow* candidate_window = g.Windows[i];
9026 if (candidate_window == potential_above)
9027 return true;
9028 if (candidate_window == potential_below)
9029 return false;
9030 }
9031 return false;
9032 }
9033
9034 // Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
9035 // IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
9036 // you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
9037 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
9038 bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
9039 {
9040 ImGuiContext& g = *GImGui;
9041 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
9042
9043 ImGuiWindow* ref_window = g.HoveredWindow;
9044 ImGuiWindow* cur_window = g.CurrentWindow;
9045 if (ref_window == NULL)
9046 return false;
9047
9048 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
9049 {
9050 IM_ASSERT(cur_window); // Not inside a Begin()/End()
9051 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
9052 const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
9053 if (flags & ImGuiHoveredFlags_RootWindow)
9054 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
9055
9056 bool result;
9057 if (flags & ImGuiHoveredFlags_ChildWindows)
9058 result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
9059 else
9060 result = (ref_window == cur_window);
9061 if (!result)
9062 return false;
9063 }
9064
9065 if (!IsWindowContentHoverable(ref_window, flags))
9066 return false;
9067 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
9068 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
9069 return false;
9070
9071 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
9072 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
9073 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
9074 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
9075 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
9076 if (flags & ImGuiHoveredFlags_ForTooltip)
9077 flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
9078 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
9079 return false;
9080
9081 return true;
9082 }
9083
9084 ImGuiID ImGui::GetWindowDockID()
9085 {
9086 ImGuiContext& g = *GImGui;
9087 return g.CurrentWindow->DockId;
9088 }
9089
9090 bool ImGui::IsWindowDocked()
9091 {
9092 ImGuiContext& g = *GImGui;
9093 return g.CurrentWindow->DockIsActive;
9094 }
9095
9096 float ImGui::GetWindowWidth()
9097 {
9098 ImGuiWindow* window = GImGui->CurrentWindow;
9099 return window->Size.x;
9100 }
9101
9102 float ImGui::GetWindowHeight()
9103 {
9104 ImGuiWindow* window = GImGui->CurrentWindow;
9105 return window->Size.y;
9106 }
9107
9108 ImVec2 ImGui::GetWindowPos()
9109 {
9110 ImGuiContext& g = *GImGui;
9111 ImGuiWindow* window = g.CurrentWindow;
9112 return window->Pos;
9113 }
9114
9115 void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
9116 {
9117 // Test condition (NB: bit 0 is always true) and clear flags for next time
9118 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
9119 return;
9120
9121 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9122 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
9123 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
9124
9125 // Set
9126 const ImVec2 old_pos = window->Pos;
9127 window->Pos = ImTrunc(pos);
9128 ImVec2 offset = window->Pos - old_pos;
9129 if (offset.x == 0.0f && offset.y == 0.0f)
9130 return;
9131 MarkIniSettingsDirty(window);
9132 // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
9133 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
9134 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
9135 window->DC.IdealMaxPos += offset;
9136 window->DC.CursorStartPos += offset;
9137 }
9138
9139 void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
9140 {
9141 ImGuiWindow* window = GetCurrentWindowRead();
9142 SetWindowPos(window, pos, cond);
9143 }
9144
9145 void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
9146 {
9147 if (ImGuiWindow* window = FindWindowByName(name))
9148 SetWindowPos(window, pos, cond);
9149 }
9150
9151 ImVec2 ImGui::GetWindowSize()
9152 {
9153 ImGuiWindow* window = GetCurrentWindowRead();
9154 return window->Size;
9155 }
9156
9157 void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
9158 {
9159 // Test condition (NB: bit 0 is always true) and clear flags for next time
9160 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
9161 return;
9162
9163 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9164 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
9165
9166 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
9167 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
9168 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
9169 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
9170 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
9171
9172 // Set
9173 ImVec2 old_size = window->SizeFull;
9174 if (size.x <= 0.0f)
9175 window->AutoFitOnlyGrows = false;
9176 else
9177 window->SizeFull.x = IM_TRUNC(size.x);
9178 if (size.y <= 0.0f)
9179 window->AutoFitOnlyGrows = false;
9180 else
9181 window->SizeFull.y = IM_TRUNC(size.y);
9182 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
9183 MarkIniSettingsDirty(window);
9184 }
9185
9186 void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
9187 {
9188 SetWindowSize(GImGui->CurrentWindow, size, cond);
9189 }
9190
9191 void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
9192 {
9193 if (ImGuiWindow* window = FindWindowByName(name))
9194 SetWindowSize(window, size, cond);
9195 }
9196
9197 void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
9198 {
9199 // Test condition (NB: bit 0 is always true) and clear flags for next time
9200 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
9201 return;
9202 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
9203
9204 // Queue applying in Begin()
9205 if (window->WantCollapseToggle)
9206 window->Collapsed ^= 1;
9207 window->WantCollapseToggle = (window->Collapsed != collapsed);
9208 }
9209
9210 void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
9211 {
9212 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
9213 window->HitTestHoleSize = ImVec2ih(size);
9214 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
9215 }
9216
9217 void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
9218 {
9219 window->Hidden = window->SkipItems = true;
9220 window->HiddenFramesCanSkipItems = 1;
9221 }
9222
9223 void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
9224 {
9225 SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
9226 }
9227
9228 bool ImGui::IsWindowCollapsed()
9229 {
9230 ImGuiWindow* window = GetCurrentWindowRead();
9231 return window->Collapsed;
9232 }
9233
9234 bool ImGui::IsWindowAppearing()
9235 {
9236 ImGuiWindow* window = GetCurrentWindowRead();
9237 return window->Appearing;
9238 }
9239
9240 void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
9241 {
9242 if (ImGuiWindow* window = FindWindowByName(name))
9243 SetWindowCollapsed(window, collapsed, cond);
9244 }
9245
9246 void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
9247 {
9248 ImGuiContext& g = *GImGui;
9249 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9250 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos;
9251 g.NextWindowData.PosVal = pos;
9252 g.NextWindowData.PosPivotVal = pivot;
9253 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
9254 g.NextWindowData.PosUndock = true;
9255 }
9256
9257 void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
9258 {
9259 ImGuiContext& g = *GImGui;
9260 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9261 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize;
9262 g.NextWindowData.SizeVal = size;
9263 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
9264 }
9265
9266 // For each axis:
9267 // - 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.
9268 // - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
9269 // - See "Demo->Examples->Constrained-resizing window" for examples.
9270 void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
9271 {
9272 ImGuiContext& g = *GImGui;
9273 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
9274 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
9275 g.NextWindowData.SizeCallback = custom_callback;
9276 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
9277 }
9278
9279 // Content size = inner scrollable rectangle, padded with WindowPadding.
9280 // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
9281 void ImGui::SetNextWindowContentSize(const ImVec2& size)
9282 {
9283 ImGuiContext& g = *GImGui;
9284 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize;
9285 g.NextWindowData.ContentSizeVal = ImTrunc(size);
9286 }
9287
9288 void ImGui::SetNextWindowScroll(const ImVec2& scroll)
9289 {
9290 ImGuiContext& g = *GImGui;
9291 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll;
9292 g.NextWindowData.ScrollVal = scroll;
9293 }
9294
9295 void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
9296 {
9297 ImGuiContext& g = *GImGui;
9298 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9299 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed;
9300 g.NextWindowData.CollapsedVal = collapsed;
9301 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
9302 }
9303
9304 void ImGui::SetNextWindowBgAlpha(float alpha)
9305 {
9306 ImGuiContext& g = *GImGui;
9307 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha;
9308 g.NextWindowData.BgAlphaVal = alpha;
9309 }
9310
9311 void ImGui::SetNextWindowViewport(ImGuiID id)
9312 {
9313 ImGuiContext& g = *GImGui;
9314 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasViewport;
9315 g.NextWindowData.ViewportId = id;
9316 }
9317
9318 void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
9319 {
9320 ImGuiContext& g = *GImGui;
9321 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasDock;
9322 g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
9323 g.NextWindowData.DockId = id;
9324 }
9325
9326 void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
9327 {
9328 ImGuiContext& g = *GImGui;
9329 IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
9330 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasWindowClass;
9331 g.NextWindowData.WindowClass = *window_class;
9332 }
9333
9334 // This is experimental and meant to be a toy for exploring a future/wider range of features.
9335 void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
9336 {
9337 ImGuiContext& g = *GImGui;
9338 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
9339 g.NextWindowData.RefreshFlagsVal = flags;
9340 }
9341
9342 ImDrawList* ImGui::GetWindowDrawList()
9343 {
9344 ImGuiWindow* window = GetCurrentWindow();
9345 return window->DrawList;
9346 }
9347
9348 float ImGui::GetWindowDpiScale()
9349 {
9350 ImGuiContext& g = *GImGui;
9351 return g.CurrentDpiScale;
9352 }
9353
9354 ImGuiViewport* ImGui::GetWindowViewport()
9355 {
9356 ImGuiContext& g = *GImGui;
9357 IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
9358 return g.CurrentViewport;
9359 }
9360
9361 ImFont* ImGui::GetFont()
9362 {
9363 return GImGui->Font;
9364 }
9365
9366 ImFontBaked* ImGui::GetFontBaked()
9367 {
9368 return GImGui->FontBaked;
9369 }
9370
9371 // Get current font size (= height in pixels) of current font, with global scale factors applied.
9372 // - Use style.FontSizeBase to get value before global scale factors.
9373 // - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors)
9374 float ImGui::GetFontSize()
9375 {
9376 return GImGui->FontSize;
9377 }
9378
9379 ImVec2 ImGui::GetFontTexUvWhitePixel()
9380 {
9381 return GImGui->DrawListSharedData.TexUvWhitePixel;
9382 }
9383
9384 // Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows.
9385 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9386 void ImGui::SetWindowFontScale(float scale)
9387 {
9388 IM_ASSERT(scale > 0.0f);
9389 ImGuiWindow* window = GetCurrentWindow();
9390 window->FontWindowScale = scale;
9391 UpdateCurrentFontSize(0.0f);
9392 }
9393 #endif
9394
9395 void ImGui::PushFocusScope(ImGuiID id)
9396 {
9397 ImGuiContext& g = *GImGui;
9398 ImGuiFocusScopeData data;
9399 data.ID = id;
9400 data.WindowID = g.CurrentWindow->ID;
9401 g.FocusScopeStack.push_back(data);
9402 g.CurrentFocusScopeId = id;
9403 }
9404
9405 void ImGui::PopFocusScope()
9406 {
9407 ImGuiContext& g = *GImGui;
9408 if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack)
9409 {
9410 IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
9411 return;
9412 }
9413 g.FocusScopeStack.pop_back();
9414 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
9415 }
9416
9417 void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
9418 {
9419 ImGuiContext& g = *GImGui;
9420 g.NavFocusScopeId = focus_scope_id;
9421 g.NavFocusRoute.resize(0); // Invalidate
9422 if (focus_scope_id == 0)
9423 return;
9424 IM_ASSERT(g.NavWindow != NULL);
9425
9426 // Store current path (in reverse order)
9427 if (focus_scope_id == g.CurrentFocusScopeId)
9428 {
9429 // Top of focus stack contains local focus scopes inside current window
9430 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
9431 g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
9432 }
9433 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
9434 g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
9435 else
9436 return;
9437
9438 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
9439 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
9440 g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
9441 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
9442 }
9443
9444 // Focus = move navigation cursor, set scrolling, set focus window.
9445 void ImGui::FocusItem()
9446 {
9447 ImGuiContext& g = *GImGui;
9448 ImGuiWindow* window = g.CurrentWindow;
9449 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
9450 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
9451 {
9452 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
9453 return;
9454 }
9455
9456 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
9457 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9458 SetNavWindow(window);
9459 NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
9460 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
9461 }
9462
9463 void ImGui::ActivateItemByID(ImGuiID id)
9464 {
9465 ImGuiContext& g = *GImGui;
9466 g.NavNextActivateId = id;
9467 g.NavNextActivateFlags = ImGuiActivateFlags_None;
9468 }
9469
9470 // Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
9471 // But ActivateItem() should function without altering scroll/focus?
9472 void ImGui::SetKeyboardFocusHere(int offset)
9473 {
9474 ImGuiContext& g = *GImGui;
9475 ImGuiWindow* window = g.CurrentWindow;
9476 IM_ASSERT(offset >= -1); // -1 is allowed but not below
9477 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
9478
9479 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
9480 // When we refactor this function into ActivateItem() we may want to make this an option.
9481 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
9482 // is also automatically dropped in the event g.ActiveId is stolen.
9483 if (g.DragDropActive || g.MovingWindow != NULL)
9484 {
9485 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
9486 return;
9487 }
9488
9489 SetNavWindow(window);
9490
9491 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
9492 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9493 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.
9494 if (offset == -1)
9495 {
9496 NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
9497 }
9498 else
9499 {
9500 g.NavTabbingDir = 1;
9501 g.NavTabbingCounter = offset + 1;
9502 }
9503 }
9504
9505 void ImGui::SetItemDefaultFocus()
9506 {
9507 ImGuiContext& g = *GImGui;
9508 ImGuiWindow* window = g.CurrentWindow;
9509 if (!window->Appearing)
9510 return;
9511 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
9512 return;
9513
9514 g.NavInitRequest = false;
9515 NavApplyItemToResult(&g.NavInitResult);
9516 NavUpdateAnyRequestFlag();
9517
9518 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
9519 if (!window->ClipRect.Contains(g.LastItemData.Rect))
9520 ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
9521 }
9522
9523 void ImGui::SetStateStorage(ImGuiStorage* tree)
9524 {
9525 ImGuiWindow* window = GImGui->CurrentWindow;
9526 window->DC.StateStorage = tree ? tree : &window->StateStorage;
9527 }
9528
9529 ImGuiStorage* ImGui::GetStateStorage()
9530 {
9531 ImGuiWindow* window = GImGui->CurrentWindow;
9532 return window->DC.StateStorage;
9533 }
9534
9535 bool ImGui::IsRectVisible(const ImVec2& size)
9536 {
9537 ImGuiWindow* window = GImGui->CurrentWindow;
9538 return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
9539 }
9540
9541 bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
9542 {
9543 ImGuiWindow* window = GImGui->CurrentWindow;
9544 return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
9545 }
9546
9547 //-----------------------------------------------------------------------------
9548 // [SECTION] FONTS, TEXTURES
9549 //-----------------------------------------------------------------------------
9550 // Most of the relevant font logic is in imgui_draw.cpp.
9551 // Those are high-level support functions.
9552 //-----------------------------------------------------------------------------
9553 // - UpdateTexturesNewFrame() [Internal]
9554 // - UpdateTexturesEndFrame() [Internal]
9555 // - UpdateFontsNewFrame() [Internal]
9556 // - UpdateFontsEndFrame() [Internal]
9557 // - GetDefaultFont() [Internal]
9558 // - RegisterUserTexture() [Internal]
9559 // - UnregisterUserTexture() [Internal]
9560 // - RegisterFontAtlas() [Internal]
9561 // - UnregisterFontAtlas() [Internal]
9562 // - SetCurrentFont() [Internal]
9563 // - UpdateCurrentFontSize() [Internal]
9564 // - SetFontRasterizerDensity() [Internal]
9565 // - PushFont()
9566 // - PopFont()
9567 //-----------------------------------------------------------------------------
9568
9569 static void ImGui::UpdateTexturesNewFrame()
9570 {
9571 // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count.
9572 ImGuiContext& g = *GImGui;
9573 const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
9574 for (ImFontAtlas* atlas : g.FontAtlases)
9575 {
9576 if (atlas->OwnerContext == &g)
9577 {
9578 ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures);
9579 }
9580 else
9581 {
9582 // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it.
9583 // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context.
9584 // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that.
9585 // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures.
9586 IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1);
9587 IM_ASSERT(atlas->RendererHasTextures == has_textures);
9588 }
9589 }
9590 }
9591
9592 // Build a single texture list
9593 static void ImGui::UpdateTexturesEndFrame()
9594 {
9595 ImGuiContext& g = *GImGui;
9596 g.PlatformIO.Textures.resize(0);
9597 for (ImFontAtlas* atlas : g.FontAtlases)
9598 for (ImTextureData* tex : atlas->TexList)
9599 {
9600 // We provide this information so backends can decide whether to destroy textures.
9601 // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized.
9602 tex->RefCount = (unsigned short)atlas->RefCount;
9603 g.PlatformIO.Textures.push_back(tex);
9604 }
9605 for (ImTextureData* tex : g.UserTextures)
9606 g.PlatformIO.Textures.push_back(tex);
9607 }
9608
9609 void ImGui::UpdateFontsNewFrame()
9610 {
9611 ImGuiContext& g = *GImGui;
9612 if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
9613 for (ImFontAtlas* atlas : g.FontAtlases)
9614 atlas->Locked = true;
9615
9616 if (g.Style._NextFrameFontSizeBase != 0.0f)
9617 {
9618 g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase;
9619 g.Style._NextFrameFontSizeBase = 0.0f;
9620 }
9621
9622 // Apply default font size the first time
9623 ImFont* font = ImGui::GetDefaultFont();
9624 if (g.Style.FontSizeBase <= 0.0f)
9625 g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE);
9626
9627 // Set initial font
9628 g.Font = font;
9629 g.FontSizeBase = g.Style.FontSizeBase;
9630 g.FontSize = 0.0f;
9631 ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize
9632 SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale
9633 g.FontStack.push_back(font_stack_data);
9634 IM_ASSERT(g.Font->IsLoaded());
9635 }
9636
9637 void ImGui::UpdateFontsEndFrame()
9638 {
9639 PopFont();
9640 }
9641
9642 ImFont* ImGui::GetDefaultFont()
9643 {
9644 ImGuiContext& g = *GImGui;
9645 ImFontAtlas* atlas = g.IO.Fonts;
9646 if (atlas->Builder == NULL || atlas->Fonts.Size == 0)
9647 ImFontAtlasBuildMain(atlas);
9648 return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0];
9649 }
9650
9651 // EXPERIMENTAL: DO NOT USE YET.
9652 void ImGui::RegisterUserTexture(ImTextureData* tex)
9653 {
9654 ImGuiContext& g = *GImGui;
9655 tex->RefCount++;
9656 g.UserTextures.push_back(tex);
9657 }
9658
9659 void ImGui::UnregisterUserTexture(ImTextureData* tex)
9660 {
9661 ImGuiContext& g = *GImGui;
9662 IM_ASSERT(tex->RefCount > 0);
9663 tex->RefCount--;
9664 g.UserTextures.find_erase(tex);
9665 }
9666
9667 void ImGui::RegisterFontAtlas(ImFontAtlas* atlas)
9668 {
9669 ImGuiContext& g = *GImGui;
9670 if (g.FontAtlases.Size == 0)
9671 IM_ASSERT(atlas == g.IO.Fonts);
9672 atlas->RefCount++;
9673 g.FontAtlases.push_back(atlas);
9674 ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData);
9675 }
9676
9677 void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas)
9678 {
9679 ImGuiContext& g = *GImGui;
9680 IM_ASSERT(atlas->RefCount > 0);
9681 ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData);
9682 g.FontAtlases.find_erase(atlas);
9683 atlas->RefCount--;
9684 }
9685
9686 // Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList.
9687 // - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls.
9688 // - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
9689 // - Some code paths never really fully worked with multiple atlas textures.
9690 // - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture()
9691 // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
9692 // because we have a concrete need and a test bed for multiple atlas textures.
9693 // FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ?
9694 void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling)
9695 {
9696 ImGuiContext& g = *GImGui;
9697 g.Font = font;
9698 g.FontSizeBase = font_size_before_scaling;
9699 UpdateCurrentFontSize(font_size_after_scaling);
9700
9701 if (font != NULL)
9702 {
9703 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
9704 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9705 IM_ASSERT(font->Scale > 0.0f);
9706 #endif
9707 ImFontAtlas* atlas = font->ContainerAtlas;
9708 g.DrawListSharedData.FontAtlas = atlas;
9709 g.DrawListSharedData.Font = font;
9710 ImFontAtlasUpdateDrawListsSharedData(atlas);
9711 if (g.CurrentWindow != NULL)
9712 g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef);
9713 }
9714 }
9715
9716 void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling)
9717 {
9718 ImGuiContext& g = *GImGui;
9719 ImGuiWindow* window = g.CurrentWindow;
9720
9721 g.Style.FontSizeBase = g.FontSizeBase;
9722
9723 // Early out to avoid hidden window keeping bakes referenced and out of GC reach.
9724 // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching.
9725 // FIXME: perhaps g.FontSize should be updated?
9726 if (window != NULL && window->SkipItems)
9727 {
9728 ImGuiTable* table = g.CurrentTable;
9729 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.
9730 return;
9731 }
9732
9733 // Restoring is pretty much only used by PopFont()
9734 float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f;
9735 if (final_size == 0.0f)
9736 {
9737 final_size = g.FontSizeBase;
9738
9739 // Global scale factors
9740 final_size *= g.Style.FontScaleMain; // Main global scale factor
9741 final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled.
9742
9743 // Window scale (mostly obsolete now)
9744 if (window != NULL)
9745 final_size *= window->FontWindowScale;
9746
9747 // Legacy scale factors
9748 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9749 final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead!
9750 if (g.Font != NULL)
9751 final_size *= g.Font->Scale; // Was never really useful.
9752 #endif
9753 }
9754
9755 // Round font size
9756 // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
9757 // - We may support it better later and remove this rounding.
9758 final_size = GetRoundedFontSize(final_size);
9759 final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX);
9760 if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures))
9761 g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity;
9762 g.FontSize = final_size;
9763 g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL;
9764 g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f;
9765 g.DrawListSharedData.FontSize = g.FontSize;
9766 g.DrawListSharedData.FontScale = g.FontBakedScale;
9767 }
9768
9769 // Exposed in case user may want to override setting density.
9770 // IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it.
9771 void ImGui::SetFontRasterizerDensity(float rasterizer_density)
9772 {
9773 ImGuiContext& g = *GImGui;
9774 IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures);
9775 if (g.FontRasterizerDensity == rasterizer_density)
9776 return;
9777 g.FontRasterizerDensity = rasterizer_density;
9778 UpdateCurrentFontSize(0.0f);
9779 }
9780
9781 // If you want to scale an existing font size! Read comments in imgui.h!
9782 void ImGui::PushFont(ImFont* font, float font_size_base)
9783 {
9784 ImGuiContext& g = *GImGui;
9785 if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont())
9786 font = g.Font;
9787 IM_ASSERT(font != NULL);
9788 IM_ASSERT(font_size_base >= 0.0f);
9789
9790 g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize });
9791 if (font_size_base == 0.0f)
9792 font_size_base = g.FontSizeBase; // Keep current font size
9793 SetCurrentFont(font, font_size_base, 0.0f);
9794 }
9795
9796 void ImGui::PopFont()
9797 {
9798 ImGuiContext& g = *GImGui;
9799 if (g.FontStack.Size <= 0)
9800 {
9801 IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
9802 return;
9803 }
9804 ImFontStackData* font_stack_data = &g.FontStack.back();
9805 SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling);
9806 g.FontStack.pop_back();
9807 }
9808
9809 //-----------------------------------------------------------------------------
9810 // [SECTION] ID STACK
9811 //-----------------------------------------------------------------------------
9812
9813 // This is one of the very rare legacy case where we use ImGuiWindow methods,
9814 // it should ideally be flattened at some point but it's been used a lots by widgets.
9815 IM_MSVC_RUNTIME_CHECKS_OFF
9816 ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
9817 {
9818 ImGuiID seed = IDStack.back();
9819 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
9820 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9821 ImGuiContext& g = *Ctx;
9822 if (g.DebugHookIdInfo == id)
9823 ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
9824 #endif
9825 return id;
9826 }
9827
9828 ImGuiID ImGuiWindow::GetID(const void* ptr)
9829 {
9830 ImGuiID seed = IDStack.back();
9831 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
9832 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9833 ImGuiContext& g = *Ctx;
9834 if (g.DebugHookIdInfo == id)
9835 ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
9836 #endif
9837 return id;
9838 }
9839
9840 ImGuiID ImGuiWindow::GetID(int n)
9841 {
9842 ImGuiID seed = IDStack.back();
9843 ImGuiID id = ImHashData(&n, sizeof(n), seed);
9844 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9845 ImGuiContext& g = *Ctx;
9846 if (g.DebugHookIdInfo == id)
9847 ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
9848 #endif
9849 return id;
9850 }
9851
9852 // This is only used in rare/specific situations to manufacture an ID out of nowhere.
9853 // FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
9854 ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs)
9855 {
9856 ImGuiID seed = IDStack.back();
9857 ImVec2 p_rel = ImGui::WindowPosAbsToRel(this, p_abs);
9858 ImGuiID id = ImHashData(&p_rel, sizeof(p_rel), seed);
9859 return id;
9860 }
9861
9862 // "
9863 ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
9864 {
9865 ImGuiID seed = IDStack.back();
9866 ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
9867 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
9868 return id;
9869 }
9870
9871 void ImGui::PushID(const char* str_id)
9872 {
9873 ImGuiContext& g = *GImGui;
9874 ImGuiWindow* window = g.CurrentWindow;
9875 ImGuiID id = window->GetID(str_id);
9876 window->IDStack.push_back(id);
9877 }
9878
9879 void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
9880 {
9881 ImGuiContext& g = *GImGui;
9882 ImGuiWindow* window = g.CurrentWindow;
9883 ImGuiID id = window->GetID(str_id_begin, str_id_end);
9884 window->IDStack.push_back(id);
9885 }
9886
9887 void ImGui::PushID(const void* ptr_id)
9888 {
9889 ImGuiContext& g = *GImGui;
9890 ImGuiWindow* window = g.CurrentWindow;
9891 ImGuiID id = window->GetID(ptr_id);
9892 window->IDStack.push_back(id);
9893 }
9894
9895 void ImGui::PushID(int int_id)
9896 {
9897 ImGuiContext& g = *GImGui;
9898 ImGuiWindow* window = g.CurrentWindow;
9899 ImGuiID id = window->GetID(int_id);
9900 window->IDStack.push_back(id);
9901 }
9902
9903 // Push a given id value ignoring the ID stack as a seed.
9904 void ImGui::PushOverrideID(ImGuiID id)
9905 {
9906 ImGuiContext& g = *GImGui;
9907 ImGuiWindow* window = g.CurrentWindow;
9908 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9909 if (g.DebugHookIdInfo == id)
9910 DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
9911 #endif
9912 window->IDStack.push_back(id);
9913 }
9914
9915 // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
9916 // (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
9917 // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
9918 ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
9919 {
9920 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
9921 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9922 ImGuiContext& g = *GImGui;
9923 if (g.DebugHookIdInfo == id)
9924 DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
9925 #endif
9926 return id;
9927 }
9928
9929 ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
9930 {
9931 ImGuiID id = ImHashData(&n, sizeof(n), seed);
9932 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
9933 ImGuiContext& g = *GImGui;
9934 if (g.DebugHookIdInfo == id)
9935 DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
9936 #endif
9937 return id;
9938 }
9939
9940 void ImGui::PopID()
9941 {
9942 ImGuiWindow* window = GImGui->CurrentWindow;
9943 if (window->IDStack.Size <= 1)
9944 {
9945 IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!");
9946 return;
9947 }
9948 window->IDStack.pop_back();
9949 }
9950
9951 ImGuiID ImGui::GetID(const char* str_id)
9952 {
9953 ImGuiWindow* window = GImGui->CurrentWindow;
9954 return window->GetID(str_id);
9955 }
9956
9957 ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9958 {
9959 ImGuiWindow* window = GImGui->CurrentWindow;
9960 return window->GetID(str_id_begin, str_id_end);
9961 }
9962
9963 ImGuiID ImGui::GetID(const void* ptr_id)
9964 {
9965 ImGuiWindow* window = GImGui->CurrentWindow;
9966 return window->GetID(ptr_id);
9967 }
9968
9969 ImGuiID ImGui::GetID(int int_id)
9970 {
9971 ImGuiWindow* window = GImGui->CurrentWindow;
9972 return window->GetID(int_id);
9973 }
9974 IM_MSVC_RUNTIME_CHECKS_RESTORE
9975
9976 //-----------------------------------------------------------------------------
9977 // [SECTION] INPUTS
9978 //-----------------------------------------------------------------------------
9979 // - GetModForLRModKey() [Internal]
9980 // - FixupKeyChord() [Internal]
9981 // - GetKeyData() [Internal]
9982 // - GetKeyIndex() [Internal]
9983 // - GetKeyName()
9984 // - GetKeyChordName() [Internal]
9985 // - CalcTypematicRepeatAmount() [Internal]
9986 // - GetTypematicRepeatRate() [Internal]
9987 // - GetKeyPressedAmount() [Internal]
9988 // - GetKeyMagnitude2d() [Internal]
9989 //-----------------------------------------------------------------------------
9990 // - UpdateKeyRoutingTable() [Internal]
9991 // - GetRoutingIdFromOwnerId() [Internal]
9992 // - GetShortcutRoutingData() [Internal]
9993 // - CalcRoutingScore() [Internal]
9994 // - SetShortcutRouting() [Internal]
9995 // - TestShortcutRouting() [Internal]
9996 //-----------------------------------------------------------------------------
9997 // - IsKeyDown()
9998 // - IsKeyPressed()
9999 // - IsKeyReleased()
10000 //-----------------------------------------------------------------------------
10001 // - IsMouseDown()
10002 // - IsMouseClicked()
10003 // - IsMouseReleased()
10004 // - IsMouseDoubleClicked()
10005 // - GetMouseClickedCount()
10006 // - IsMouseHoveringRect() [Internal]
10007 // - IsMouseDragPastThreshold() [Internal]
10008 // - IsMouseDragging()
10009 // - GetMousePos()
10010 // - SetMousePos() [Internal]
10011 // - GetMousePosOnOpeningCurrentPopup()
10012 // - IsMousePosValid()
10013 // - IsAnyMouseDown()
10014 // - GetMouseDragDelta()
10015 // - ResetMouseDragDelta()
10016 // - GetMouseCursor()
10017 // - SetMouseCursor()
10018 //-----------------------------------------------------------------------------
10019 // - UpdateAliasKey()
10020 // - GetMergedModsFromKeys()
10021 // - UpdateKeyboardInputs()
10022 // - UpdateMouseInputs()
10023 //-----------------------------------------------------------------------------
10024 // - LockWheelingWindow [Internal]
10025 // - FindBestWheelingWindow [Internal]
10026 // - UpdateMouseWheel() [Internal]
10027 //-----------------------------------------------------------------------------
10028 // - SetNextFrameWantCaptureKeyboard()
10029 // - SetNextFrameWantCaptureMouse()
10030 //-----------------------------------------------------------------------------
10031 // - GetInputSourceName() [Internal]
10032 // - DebugPrintInputEvent() [Internal]
10033 // - UpdateInputEvents() [Internal]
10034 //-----------------------------------------------------------------------------
10035 // - GetKeyOwner() [Internal]
10036 // - TestKeyOwner() [Internal]
10037 // - SetKeyOwner() [Internal]
10038 // - SetItemKeyOwner() [Internal]
10039 // - Shortcut() [Internal]
10040 //-----------------------------------------------------------------------------
10041
10042 static ImGuiKeyChord GetModForLRModKey(ImGuiKey key)
10043 {
10044 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
10045 return ImGuiMod_Ctrl;
10046 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
10047 return ImGuiMod_Shift;
10048 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
10049 return ImGuiMod_Alt;
10050 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
10051 return ImGuiMod_Super;
10052 return ImGuiMod_None;
10053 }
10054
10055 ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
10056 {
10057 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
10058 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10059 if (IsLRModKey(key))
10060 key_chord |= GetModForLRModKey(key);
10061 return key_chord;
10062 }
10063
10064 ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
10065 {
10066 ImGuiContext& g = *ctx;
10067
10068 // Special storage location for mods
10069 if (key & ImGuiMod_Mask_)
10070 key = ConvertSingleModFlagToKey(key);
10071
10072 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
10073 return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10074 }
10075
10076 // Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
10077 static const char* const GKeyNames[] =
10078 {
10079 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
10080 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
10081 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
10082 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
10083 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
10084 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
10085 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
10086 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
10087 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
10088 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
10089 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
10090 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
10091 "AppBack", "AppForward", "Oem102",
10092 "GamepadStart", "GamepadBack",
10093 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
10094 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
10095 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
10096 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
10097 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
10098 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
10099 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
10100 };
10101 IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
10102
10103 const char* ImGui::GetKeyName(ImGuiKey key)
10104 {
10105 if (key == ImGuiKey_None)
10106 return "None";
10107 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
10108 if (key & ImGuiMod_Mask_)
10109 key = ConvertSingleModFlagToKey(key);
10110 if (!IsNamedKey(key))
10111 return "Unknown";
10112
10113 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
10114 }
10115
10116 // Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
10117 // Lifetime of return value: valid until next call to same function.
10118 const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
10119 {
10120 ImGuiContext& g = *GImGui;
10121
10122 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10123 if (IsLRModKey(key))
10124 key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
10125 ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
10126 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
10127 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
10128 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
10129 (key_chord & ImGuiMod_Super) ? "Super+" : "",
10130 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
10131 size_t len;
10132 if (key == ImGuiKey_None && key_chord != 0)
10133 if ((len = ImStrlen(g.TempKeychordName)) != 0) // Remove trailing '+'
10134 g.TempKeychordName[len - 1] = 0;
10135 return g.TempKeychordName;
10136 }
10137
10138 // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
10139 // t1 = current time (e.g.: g.Time)
10140 // An event is triggered at:
10141 // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
10142 int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
10143 {
10144 if (t1 == 0.0f)
10145 return 1;
10146 if (t0 >= t1)
10147 return 0;
10148 if (repeat_rate <= 0.0f)
10149 return (t0 < repeat_delay) && (t1 >= repeat_delay);
10150 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
10151 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
10152 const int count = count_t1 - count_t0;
10153 return count;
10154 }
10155
10156 void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
10157 {
10158 ImGuiContext& g = *GImGui;
10159 switch (flags & ImGuiInputFlags_RepeatRateMask_)
10160 {
10161 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
10162 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
10163 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
10164 }
10165 }
10166
10167 // Return value representing the number of presses in the last time period, for the given repeat rate
10168 // (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
10169 int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
10170 {
10171 ImGuiContext& g = *GImGui;
10172 const ImGuiKeyData* key_data = GetKeyData(key);
10173 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)
10174 return 0;
10175 const float t = key_data->DownDuration;
10176 return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
10177 }
10178
10179 // Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
10180 ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
10181 {
10182 return ImVec2(
10183 GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
10184 GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
10185 }
10186
10187 // Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
10188 // Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
10189 // Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
10190 // See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
10191 static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
10192 {
10193 ImGuiContext& g = *GImGui;
10194 rt->EntriesNext.resize(0);
10195 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
10196 {
10197 const int new_routing_start_idx = rt->EntriesNext.Size;
10198 ImGuiKeyRoutingData* routing_entry;
10199 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
10200 {
10201 routing_entry = &rt->Entries[old_routing_idx];
10202 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
10203 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
10204 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
10205 routing_entry->RoutingNextScore = 255;
10206 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
10207 continue;
10208 rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
10209
10210 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
10211 // This is the result of previous frame's SetShortcutRouting() call.
10212 if (routing_entry->Mods == g.IO.KeyMods)
10213 {
10214 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10215 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
10216 {
10217 owner_data->OwnerCurr = routing_entry->RoutingCurr;
10218 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
10219 }
10220 }
10221 }
10222
10223 // Rewrite linked-list
10224 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
10225 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
10226 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
10227 }
10228 rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
10229 }
10230
10231 // owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
10232 static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
10233 {
10234 ImGuiContext& g = *GImGui;
10235 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
10236 }
10237
10238 ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
10239 {
10240 // Majority of shortcuts will be Key + any number of Mods
10241 // We accept _Single_ mod with ImGuiKey_None.
10242 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
10243 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
10244 // - Shortcut(ImGuiMod_Ctrl); // Legal
10245 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
10246 ImGuiContext& g = *GImGui;
10247 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
10248 ImGuiKeyRoutingData* routing_data;
10249 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10250 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10251 if (key == ImGuiKey_None)
10252 key = ConvertSingleModFlagToKey(mods);
10253 IM_ASSERT(IsNamedKey(key));
10254
10255 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
10256 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
10257 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
10258 {
10259 routing_data = &rt->Entries[idx];
10260 if (routing_data->Mods == mods)
10261 return routing_data;
10262 }
10263
10264 // Add to linked-list
10265 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
10266 rt->Entries.push_back(ImGuiKeyRoutingData());
10267 routing_data = &rt->Entries[routing_data_idx];
10268 routing_data->Mods = (ImU16)mods;
10269 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
10270 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
10271 return routing_data;
10272 }
10273
10274 // Current score encoding (lower is highest priority):
10275 // - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
10276 // - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
10277 // - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
10278 // - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
10279 // - 254: ImGuiInputFlags_RouteGlobal
10280 // - 255: never route
10281 // 'flags' should include an explicit routing policy
10282 static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
10283 {
10284 ImGuiContext& g = *GImGui;
10285 if (flags & ImGuiInputFlags_RouteFocused)
10286 {
10287 // ActiveID gets top priority
10288 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
10289 if (owner_id != 0 && g.ActiveId == owner_id)
10290 return 1;
10291
10292 // Score based on distance to focused window (lower is better)
10293 // Assuming both windows are submitting a routing request,
10294 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
10295 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
10296 // Assuming only WindowA is submitting a routing request,
10297 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
10298 // This essentially follow the window->ParentWindowForFocusRoute chain.
10299 if (focus_scope_id == 0)
10300 return 255;
10301 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
10302 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
10303 return 3 + index_in_focus_path;
10304 return 255;
10305 }
10306 else if (flags & ImGuiInputFlags_RouteActive)
10307 {
10308 if (owner_id != 0 && g.ActiveId == owner_id)
10309 return 1;
10310 return 255;
10311 }
10312 else if (flags & ImGuiInputFlags_RouteGlobal)
10313 {
10314 if (flags & ImGuiInputFlags_RouteOverActive)
10315 return 0;
10316 if (flags & ImGuiInputFlags_RouteOverFocused)
10317 return 2;
10318 return 254;
10319 }
10320 IM_ASSERT(0);
10321 return 0;
10322 }
10323
10324 // - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
10325 // e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
10326 // - 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.
10327 static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
10328 {
10329 // Mimic 'ignore_char_inputs' logic in InputText()
10330 ImGuiContext& g = *GImGui;
10331
10332 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
10333 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10334 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
10335 if (ignore_char_inputs)
10336 return false;
10337
10338 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
10339 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10340 if (key == ImGuiKey_None)
10341 return false;
10342 return g.KeysMayBeCharInput.TestBit(key);
10343 }
10344
10345 // Request a desired route for an input chord (key + mods).
10346 // Return true if the route is available this frame.
10347 // - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
10348 // (Conceptually this does a "Submit for next frame" + "Test for current frame".
10349 // As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
10350 bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10351 {
10352 ImGuiContext& g = *GImGui;
10353 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10354 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
10355 else
10356 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
10357 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
10358 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
10359 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
10360
10361 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
10362 key_chord = FixupKeyChord(key_chord);
10363
10364 // [DEBUG] Debug break requested by user
10365 if (g.DebugBreakInShortcutRouting == key_chord)
10366 IM_DEBUG_BREAK();
10367
10368 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
10369 if (g.NavWindow == NULL)
10370 return false;
10371
10372 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
10373 if (flags & ImGuiInputFlags_RouteAlways)
10374 {
10375 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
10376 return true;
10377 }
10378
10379 // Specific culling when there's an active item.
10380 if (g.ActiveId != 0 && g.ActiveId != owner_id)
10381 {
10382 if (flags & ImGuiInputFlags_RouteActive)
10383 return false;
10384
10385 // Cull shortcuts with no modifiers when it could generate a character.
10386 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
10387 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
10388 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
10389 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
10390 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
10391 {
10392 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
10393 return false;
10394 }
10395
10396 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
10397 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
10398 {
10399 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10400 if (key == ImGuiKey_None)
10401 key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
10402 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10403 return false;
10404 }
10405 }
10406
10407 // Where do we evaluate route for?
10408 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
10409 if (flags & ImGuiInputFlags_RouteFromRootWindow)
10410 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
10411
10412 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
10413 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
10414 if (score == 255)
10415 return false;
10416
10417 // Submit routing for NEXT frame (assuming score is sufficient)
10418 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
10419 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
10420 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
10421 if (score < routing_data->RoutingNextScore)
10422 {
10423 routing_data->RoutingNext = owner_id;
10424 routing_data->RoutingNextScore = (ImU8)score;
10425 }
10426
10427 // Return routing state for CURRENT frame
10428 if (routing_data->RoutingCurr == owner_id)
10429 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
10430 return routing_data->RoutingCurr == owner_id;
10431 }
10432
10433 // Currently unused by core (but used by tests)
10434 // Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
10435 bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
10436 {
10437 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
10438 key_chord = FixupKeyChord(key_chord);
10439 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
10440 return routing_data->RoutingCurr == routing_id;
10441 }
10442
10443 // Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
10444 // Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
10445 bool ImGui::IsKeyDown(ImGuiKey key)
10446 {
10447 return IsKeyDown(key, ImGuiKeyOwner_Any);
10448 }
10449
10450 bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
10451 {
10452 const ImGuiKeyData* key_data = GetKeyData(key);
10453 if (!key_data->Down)
10454 return false;
10455 if (!TestKeyOwner(key, owner_id))
10456 return false;
10457 return true;
10458 }
10459
10460 bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
10461 {
10462 return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10463 }
10464
10465 // Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
10466 bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
10467 {
10468 const ImGuiKeyData* key_data = GetKeyData(key);
10469 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)
10470 return false;
10471 const float t = key_data->DownDuration;
10472 if (t < 0.0f)
10473 return false;
10474 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
10475 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
10476 flags |= ImGuiInputFlags_Repeat;
10477
10478 bool pressed = (t == 0.0f);
10479 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
10480 {
10481 float repeat_delay, repeat_rate;
10482 GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
10483 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
10484 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
10485 {
10486 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
10487 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
10488 ImGuiContext& g = *GImGui;
10489 double key_pressed_time = g.Time - t + 0.00001f;
10490 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
10491 pressed = false;
10492 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
10493 pressed = false;
10494 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
10495 pressed = false;
10496 }
10497 }
10498 if (!pressed)
10499 return false;
10500 if (!TestKeyOwner(key, owner_id))
10501 return false;
10502 return true;
10503 }
10504
10505 bool ImGui::IsKeyReleased(ImGuiKey key)
10506 {
10507 return IsKeyReleased(key, ImGuiKeyOwner_Any);
10508 }
10509
10510 bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
10511 {
10512 const ImGuiKeyData* key_data = GetKeyData(key);
10513 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
10514 return false;
10515 if (!TestKeyOwner(key, owner_id))
10516 return false;
10517 return true;
10518 }
10519
10520 bool ImGui::IsMouseDown(ImGuiMouseButton button)
10521 {
10522 ImGuiContext& g = *GImGui;
10523 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10524 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.
10525 }
10526
10527 bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
10528 {
10529 ImGuiContext& g = *GImGui;
10530 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10531 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.
10532 }
10533
10534 bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
10535 {
10536 return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10537 }
10538
10539 bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
10540 {
10541 ImGuiContext& g = *GImGui;
10542 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10543 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)
10544 return false;
10545 const float t = g.IO.MouseDownDuration[button];
10546 if (t < 0.0f)
10547 return false;
10548 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
10549
10550 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
10551 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
10552 if (!pressed)
10553 return false;
10554
10555 if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
10556 return false;
10557
10558 return true;
10559 }
10560
10561 bool ImGui::IsMouseReleased(ImGuiMouseButton button)
10562 {
10563 ImGuiContext& g = *GImGui;
10564 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10565 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
10566 }
10567
10568 bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
10569 {
10570 ImGuiContext& g = *GImGui;
10571 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10572 return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
10573 }
10574
10575 // Use if you absolutely need to distinguish single-click from double-click by introducing a delay.
10576 // Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test.
10577 // This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
10578 bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay)
10579 {
10580 ImGuiContext& g = *GImGui;
10581 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10582 const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]);
10583 return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay);
10584 }
10585
10586 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
10587 {
10588 ImGuiContext& g = *GImGui;
10589 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10590 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
10591 }
10592
10593 bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
10594 {
10595 ImGuiContext& g = *GImGui;
10596 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10597 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
10598 }
10599
10600 int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
10601 {
10602 ImGuiContext& g = *GImGui;
10603 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10604 return g.IO.MouseClickedCount[button];
10605 }
10606
10607 // Test if mouse cursor is hovering given rectangle
10608 // NB- Rectangle is clipped by our current clip setting
10609 // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
10610 bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
10611 {
10612 ImGuiContext& g = *GImGui;
10613
10614 // Clip
10615 ImRect rect_clipped(r_min, r_max);
10616 if (clip)
10617 rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
10618
10619 // Hit testing, expanded for touch input
10620 if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
10621 return false;
10622 if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
10623 return false;
10624 return true;
10625 }
10626
10627 // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
10628 // [Internal] This doesn't test if the button is pressed
10629 bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
10630 {
10631 ImGuiContext& g = *GImGui;
10632 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10633 if (lock_threshold < 0.0f)
10634 lock_threshold = g.IO.MouseDragThreshold;
10635 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
10636 }
10637
10638 bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
10639 {
10640 ImGuiContext& g = *GImGui;
10641 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10642 if (!g.IO.MouseDown[button])
10643 return false;
10644 return IsMouseDragPastThreshold(button, lock_threshold);
10645 }
10646
10647 ImVec2 ImGui::GetMousePos()
10648 {
10649 ImGuiContext& g = *GImGui;
10650 return g.IO.MousePos;
10651 }
10652
10653 // This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
10654 // It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
10655 void ImGui::TeleportMousePos(const ImVec2& pos)
10656 {
10657 ImGuiContext& g = *GImGui;
10658 g.IO.MousePos = g.IO.MousePosPrev = pos;
10659 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
10660 g.IO.WantSetMousePos = true;
10661 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
10662 }
10663
10664 // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
10665 ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
10666 {
10667 ImGuiContext& g = *GImGui;
10668 if (g.BeginPopupStack.Size > 0)
10669 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
10670 return g.IO.MousePos;
10671 }
10672
10673 // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
10674 bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
10675 {
10676 // The assert is only to silence a false-positive in XCode Static Analysis.
10677 // 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).
10678 IM_ASSERT(GImGui != NULL);
10679 const float MOUSE_INVALID = -256000.0f;
10680 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
10681 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
10682 }
10683
10684 // [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.
10685 bool ImGui::IsAnyMouseDown()
10686 {
10687 ImGuiContext& g = *GImGui;
10688 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
10689 if (g.IO.MouseDown[n])
10690 return true;
10691 return false;
10692 }
10693
10694 // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
10695 // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
10696 // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
10697 ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
10698 {
10699 ImGuiContext& g = *GImGui;
10700 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10701 if (lock_threshold < 0.0f)
10702 lock_threshold = g.IO.MouseDragThreshold;
10703 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
10704 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
10705 if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
10706 return g.IO.MousePos - g.IO.MouseClickedPos[button];
10707 return ImVec2(0.0f, 0.0f);
10708 }
10709
10710 void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
10711 {
10712 ImGuiContext& g = *GImGui;
10713 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10714 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
10715 g.IO.MouseClickedPos[button] = g.IO.MousePos;
10716 }
10717
10718 // Get desired mouse cursor shape.
10719 // Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
10720 // updated during the frame, and locked in EndFrame()/Render().
10721 // If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
10722 ImGuiMouseCursor ImGui::GetMouseCursor()
10723 {
10724 ImGuiContext& g = *GImGui;
10725 return g.MouseCursor;
10726 }
10727
10728 // We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
10729 // 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
10730 // handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
10731 void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
10732 {
10733 ImGuiContext& g = *GImGui;
10734 g.MouseCursor = cursor_type;
10735 }
10736
10737 static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
10738 {
10739 IM_ASSERT(ImGui::IsAliasKey(key));
10740 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
10741 key_data->Down = v;
10742 key_data->AnalogValue = analog_value;
10743 }
10744
10745 // [Internal] Do not use directly
10746 static ImGuiKeyChord GetMergedModsFromKeys()
10747 {
10748 ImGuiKeyChord mods = 0;
10749 if (ImGui::IsKeyDown(ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
10750 if (ImGui::IsKeyDown(ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
10751 if (ImGui::IsKeyDown(ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
10752 if (ImGui::IsKeyDown(ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
10753 return mods;
10754 }
10755
10756 static void ImGui::UpdateKeyboardInputs()
10757 {
10758 ImGuiContext& g = *GImGui;
10759 ImGuiIO& io = g.IO;
10760
10761 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10762 io.ClearInputKeys();
10763
10764 // Update aliases
10765 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
10766 UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
10767 UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
10768 UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
10769
10770 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
10771 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10772 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10773 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
10774 const ImGuiKeyChord prev_key_mods = io.KeyMods;
10775 io.KeyMods = GetMergedModsFromKeys();
10776 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
10777 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
10778 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
10779 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
10780 if (prev_key_mods != io.KeyMods)
10781 g.LastKeyModsChangeTime = g.Time;
10782 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
10783 g.LastKeyModsChangeFromNoneTime = g.Time;
10784
10785 // Clear gamepad data if disabled
10786 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
10787 for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
10788 {
10789 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
10790 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
10791 }
10792
10793 // Update keys
10794 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
10795 {
10796 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10797 key_data->DownDurationPrev = key_data->DownDuration;
10798 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
10799 if (key_data->DownDuration == 0.0f)
10800 {
10801 if (IsKeyboardKey((ImGuiKey)key))
10802 g.LastKeyboardKeyPressTime = g.Time;
10803 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
10804 g.LastKeyboardKeyPressTime = g.Time;
10805 }
10806 }
10807
10808 // Update keys/input owner (named keys only): one entry per key
10809 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
10810 {
10811 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10812 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
10813 owner_data->OwnerCurr = owner_data->OwnerNext;
10814 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.
10815 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
10816 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
10817 }
10818
10819 // Update key routing (for e.g. shortcuts)
10820 UpdateKeyRoutingTable(&g.KeysRoutingTable);
10821 }
10822
10823 static void ImGui::UpdateMouseInputs()
10824 {
10825 ImGuiContext& g = *GImGui;
10826 ImGuiIO& io = g.IO;
10827
10828 // Mouse Wheel swapping flag
10829 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
10830 // - We avoid doing it on OSX as it the OS input layer handles this already.
10831 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
10832 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
10833 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
10834
10835 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
10836 if (IsMousePosValid(&io.MousePos))
10837 io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
10838
10839 io.MouseDeltaPrev=io.MouseDelta;
10840
10841 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
10842 if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
10843 io.MouseDelta = io.MousePos - io.MousePosPrev;
10844 else
10845 io.MouseDelta = ImVec2(0.0f, 0.0f);
10846
10847 // Update stationary timer.
10848 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
10849 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
10850 const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
10851 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
10852 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
10853
10854 // 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.
10855 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
10856 g.NavHighlightItemUnderNav = false;
10857
10858 // Update mouse speed
10859 if (ImFabs(io.MouseDelta.x)>ImFabs(io.MouseDeltaPrev.x)) {
10860 io.MouseSpeed.x=io.MouseDelta.x;
10861 } else {
10862 io.MouseSpeed.x=io.MouseDeltaPrev.x;
10863 }
10864 if (ImFabs(io.MouseDelta.y)>ImFabs(io.MouseDeltaPrev.y)) {
10865 io.MouseSpeed.y=io.MouseDelta.y;
10866 } else {
10867 io.MouseSpeed.y=io.MouseDeltaPrev.y;
10868 }
10869
10870 io.MousePosPrev = io.MousePos;
10871 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
10872 {
10873 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
10874 io.MouseClickedCount[i] = 0; // Will be filled below
10875 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
10876 if (io.MouseReleased[i])
10877 io.MouseReleasedTime[i] = g.Time;
10878 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
10879 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
10880 if (io.MouseClicked[i])
10881 {
10882 bool is_repeated_click = false;
10883 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
10884 {
10885 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10886 if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
10887 is_repeated_click = true;
10888 }
10889 if (is_repeated_click)
10890 io.MouseClickedLastCount[i]++;
10891 else
10892 io.MouseClickedLastCount[i] = 1;
10893 io.MouseClickedTime[i] = g.Time;
10894 io.MouseClickedPos[i] = io.MousePos;
10895 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10896 io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10897 io.MouseDragMaxDistanceSqr[i] = 0.0f;
10898 }
10899 else if (io.MouseDown[i])
10900 {
10901 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10902 ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10903 io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
10904 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);
10905 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);
10906 }
10907
10908 // We provide io.MouseDoubleClicked[] as a legacy service
10909 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10910
10911 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
10912 if (io.MouseClicked[i])
10913 g.NavHighlightItemUnderNav = false;
10914 }
10915 }
10916
10917 static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10918 {
10919 ImGuiContext& g = *GImGui;
10920 if (window)
10921 g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10922 else
10923 g.WheelingWindowReleaseTimer = 0.0f;
10924 if (g.WheelingWindow == window)
10925 return;
10926 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10927 g.WheelingWindow = window;
10928 g.WheelingWindowRefMousePos = g.IO.MousePos;
10929 if (window == NULL)
10930 {
10931 g.WheelingWindowStartFrame = -1;
10932 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10933 }
10934 }
10935
10936 static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10937 {
10938 // For each axis, find window in the hierarchy that may want to use scrolling
10939 ImGuiContext& g = *GImGui;
10940 ImGuiWindow* windows[2] = { NULL, NULL };
10941 for (int axis = 0; axis < 2; axis++)
10942 if (wheel[axis] != 0.0f)
10943 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10944 {
10945 // Bubble up into parent window if:
10946 // - a child window doesn't allow any scrolling.
10947 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10948 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10949 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10950 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10951 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10952 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10953 break; // select this window
10954 }
10955 if (windows[0] == NULL && windows[1] == NULL)
10956 return NULL;
10957
10958 // If there's only one window or only one axis then there's no ambiguity
10959 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10960 return windows[1] ? windows[1] : windows[0];
10961
10962 // If candidate are different windows we need to decide which one to prioritize
10963 // - First frame: only find a winner if one axis is zero.
10964 // - Subsequent frames: only find a winner when one is more than the other.
10965 if (g.WheelingWindowStartFrame == -1)
10966 g.WheelingWindowStartFrame = g.FrameCount;
10967 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10968 {
10969 g.WheelingWindowWheelRemainder = wheel;
10970 return NULL;
10971 }
10972 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10973 }
10974
10975 // Called by NewFrame()
10976 void ImGui::UpdateMouseWheel()
10977 {
10978 // Reset the locked window if we move the mouse or after the timer elapses.
10979 // 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)
10980 ImGuiContext& g = *GImGui;
10981 if (g.WheelingWindow != NULL)
10982 {
10983 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10984 if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10985 g.WheelingWindowReleaseTimer = 0.0f;
10986 if (g.WheelingWindowReleaseTimer <= 0.0f)
10987 LockWheelingWindow(NULL, 0.0f);
10988 }
10989
10990 ImVec2 wheel;
10991 wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10992 wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10993
10994 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10995 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10996 if (!mouse_window || mouse_window->Collapsed)
10997 return;
10998
10999 // Zoom / Scale window
11000 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
11001 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
11002 {
11003 LockWheelingWindow(mouse_window, wheel.y);
11004 ImGuiWindow* window = mouse_window;
11005 const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
11006 const float scale = new_font_scale / window->FontWindowScale;
11007 window->FontWindowScale = new_font_scale;
11008 if (window == window->RootWindow)
11009 {
11010 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
11011 SetWindowPos(window, window->Pos + offset, 0);
11012 window->Size = ImTrunc(window->Size * scale);
11013 window->SizeFull = ImTrunc(window->SizeFull * scale);
11014 }
11015 return;
11016 }
11017 if (g.IO.KeyCtrl)
11018 return;
11019
11020 // Mouse wheel scrolling
11021 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
11022 if (g.IO.MouseWheelRequestAxisSwap)
11023 wheel = ImVec2(wheel.y, 0.0f);
11024
11025 // Maintain a rough average of moving magnitude on both axes
11026 // FIXME: should by based on wall clock time rather than frame-counter
11027 g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
11028 g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
11029
11030 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
11031 wheel += g.WheelingWindowWheelRemainder;
11032 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
11033 if (wheel.x == 0.0f && wheel.y == 0.0f)
11034 return;
11035
11036 // Mouse wheel scrolling: find target and apply
11037 // - don't renew lock if axis doesn't apply on the window.
11038 // - select a main axis when both axes are being moved.
11039 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
11040 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
11041 {
11042 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
11043 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
11044 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
11045 if (do_scroll[ImGuiAxis_X])
11046 {
11047 LockWheelingWindow(window, wheel.x);
11048 float max_step = window->InnerRect.GetWidth() * 0.67f;
11049 float scroll_step = ImTrunc(ImMin(2 * window->FontRefSize, max_step));
11050 SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
11051 g.WheelingWindowScrolledFrame = g.FrameCount;
11052 }
11053 if (do_scroll[ImGuiAxis_Y])
11054 {
11055 LockWheelingWindow(window, wheel.y);
11056 float max_step = window->InnerRect.GetHeight() * 0.67f;
11057 float scroll_step = ImTrunc(ImMin(5 * window->FontRefSize, max_step));
11058 SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
11059 g.WheelingWindowScrolledFrame = g.FrameCount;
11060 }
11061 }
11062 }
11063
11064 void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
11065 {
11066 ImGuiContext& g = *GImGui;
11067 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
11068 }
11069
11070 void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
11071 {
11072 ImGuiContext& g = *GImGui;
11073 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
11074 }
11075
11076 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11077 static const char* GetInputSourceName(ImGuiInputSource source)
11078 {
11079 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
11080 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
11081 if (source < 0 || source >= ImGuiInputSource_COUNT)
11082 return "Unknown";
11083 return input_source_names[source];
11084 }
11085 static const char* GetMouseSourceName(ImGuiMouseSource source)
11086 {
11087 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
11088 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT);
11089 if (source < 0 || source >= ImGuiMouseSource_COUNT)
11090 return "Unknown";
11091 return mouse_source_names[source];
11092 }
11093 static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
11094 {
11095 ImGuiContext& g = *GImGui;
11096 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; }
11097 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; }
11098 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; }
11099 if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
11100 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; }
11101 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
11102 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
11103 }
11104 #endif
11105
11106 // Process input queue
11107 // We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
11108 // - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
11109 // - 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)
11110 void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
11111 {
11112 ImGuiContext& g = *GImGui;
11113 ImGuiIO& io = g.IO;
11114
11115 // Only trickle chars<>key when working with InputText()
11116 // FIXME: InputText() could parse event trail?
11117 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
11118 const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
11119
11120 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
11121 int mouse_button_changed = 0x00;
11122 ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
11123
11124 int event_n = 0;
11125 for (; event_n < g.InputEventsQueue.Size; event_n++)
11126 {
11127 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
11128 if (e->Type == ImGuiInputEventType_MousePos)
11129 {
11130 if (g.IO.WantSetMousePos)
11131 continue;
11132 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
11133 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
11134 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
11135 break;
11136 io.MousePos = event_pos;
11137 io.MouseSource = e->MousePos.MouseSource;
11138 mouse_moved = true;
11139 }
11140 else if (e->Type == ImGuiInputEventType_MouseButton)
11141 {
11142 bool trickle_fast_inputs = true; // forcing trickle for MouseButton event
11143
11144 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
11145 const ImGuiMouseButton button = e->MouseButton.Button;
11146 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
11147 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
11148 break;
11149 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
11150 break;
11151 io.MouseDown[button] = e->MouseButton.Down;
11152 io.MouseSource = e->MouseButton.MouseSource;
11153 mouse_button_changed |= (1 << button);
11154 }
11155 else if (e->Type == ImGuiInputEventType_MouseWheel)
11156 {
11157 // Trickling Rule: Stop processing queued events if we got multiple action on the event
11158 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
11159 break;
11160 io.MouseWheelH += e->MouseWheel.WheelX;
11161 io.MouseWheel += e->MouseWheel.WheelY;
11162 io.MouseSource = e->MouseWheel.MouseSource;
11163 mouse_wheeled = true;
11164 }
11165 else if (e->Type == ImGuiInputEventType_MouseViewport)
11166 {
11167 io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
11168 }
11169 else if (e->Type == ImGuiInputEventType_Key)
11170 {
11171 bool trickle_fast_inputs = true; // forcing trickle for Key event
11172
11173 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
11174 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
11175 continue;
11176 ImGuiKey key = e->Key.Key;
11177 IM_ASSERT(key != ImGuiKey_None);
11178 ImGuiKeyData* key_data = GetKeyData(key);
11179 const int key_data_index = (int)(key_data - g.IO.KeysData);
11180 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || mouse_button_changed != 0))
11181 break;
11182
11183 const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(GetMergedModsFromKeys() | key);
11184 if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
11185 break;
11186
11187 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.
11188 {
11189 key_changed = true;
11190 key_changed_mask.SetBit(key_data_index);
11191 if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
11192 key_changed_nonchar = true;
11193 }
11194
11195 key_data->Down = e->Key.Down;
11196 key_data->AnalogValue = e->Key.AnalogValue;
11197 }
11198 else if (e->Type == ImGuiInputEventType_Text)
11199 {
11200 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
11201 continue;
11202 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
11203 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
11204 break;
11205 if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar)
11206 break;
11207 unsigned int c = e->Text.Char;
11208 io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
11209 if (trickle_interleaved_nonchar_keys_and_text)
11210 text_inputted = true;
11211 }
11212 else if (e->Type == ImGuiInputEventType_Focus)
11213 {
11214 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
11215 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
11216 const bool focus_lost = !e->AppFocused.Focused;
11217 io.AppFocusLost = focus_lost;
11218 }
11219 else
11220 {
11221 IM_ASSERT(0 && "Unknown event!");
11222 }
11223 }
11224
11225 // Record trail (for domain-specific applications wanting to access a precise trail)
11226 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
11227 for (int n = 0; n < event_n; n++)
11228 g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
11229
11230 // [DEBUG]
11231 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11232 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
11233 for (int n = 0; n < g.InputEventsQueue.Size; n++)
11234 DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
11235 #endif
11236
11237 // Remaining events will be processed on the next frame
11238 if (event_n == g.InputEventsQueue.Size)
11239 g.InputEventsQueue.resize(0);
11240 else
11241 g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
11242
11243 // Clear buttons state when focus is lost
11244 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
11245 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
11246 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
11247 if (g.IO.AppFocusLost)
11248 {
11249 g.IO.ClearInputKeys();
11250 g.IO.ClearInputMouse();
11251 }
11252 }
11253
11254 ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
11255 {
11256 if (!IsNamedKeyOrMod(key))
11257 return ImGuiKeyOwner_NoOwner;
11258
11259 ImGuiContext& g = *GImGui;
11260 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
11261 ImGuiID owner_id = owner_data->OwnerCurr;
11262
11263 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
11264 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
11265 return ImGuiKeyOwner_NoOwner;
11266
11267 return owner_id;
11268 }
11269
11270 // TestKeyOwner(..., ID) : (owner == None || owner == ID)
11271 // TestKeyOwner(..., None) : (owner == None)
11272 // TestKeyOwner(..., Any) : no owner test
11273 // All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
11274 bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
11275 {
11276 if (!IsNamedKeyOrMod(key))
11277 return true;
11278
11279 ImGuiContext& g = *GImGui;
11280 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
11281 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
11282 return false;
11283
11284 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
11285 if (owner_id == ImGuiKeyOwner_Any)
11286 return (owner_data->LockThisFrame == false);
11287
11288 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
11289 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
11290 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
11291 if (owner_data->OwnerCurr != owner_id)
11292 {
11293 if (owner_data->LockThisFrame)
11294 return false;
11295 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
11296 return false;
11297 }
11298
11299 return true;
11300 }
11301
11302 // _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
11303 // When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
11304 // - SetKeyOwner(..., None) : clears owner
11305 // - SetKeyOwner(..., Any, !Lock) : illegal (assert)
11306 // - SetKeyOwner(..., Any or None, Lock) : set lock
11307 void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
11308 {
11309 ImGuiContext& g = *GImGui;
11310 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)
11311 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
11312 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
11313
11314 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
11315 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
11316
11317 // We cannot lock by default as it would likely break lots of legacy code.
11318 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
11319 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
11320 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
11321 }
11322
11323 // Rarely used helper
11324 void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
11325 {
11326 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
11327 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
11328 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
11329 if (key_chord & ImGuiMod_Super) { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
11330 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
11331 }
11332
11333 // This is more or less equivalent to:
11334 // if (IsItemHovered() || IsItemActive())
11335 // SetKeyOwner(key, GetItemID());
11336 // 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.
11337 // More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
11338 // 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.
11339 void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
11340 {
11341 ImGuiContext& g = *GImGui;
11342 ImGuiID id = g.LastItemData.ID;
11343 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
11344 return;
11345 if ((flags & ImGuiInputFlags_CondMask_) == 0)
11346 flags |= ImGuiInputFlags_CondDefault_;
11347 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
11348 {
11349 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
11350 SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
11351 }
11352 }
11353
11354 void ImGui::SetItemKeyOwner(ImGuiKey key)
11355 {
11356 SetItemKeyOwner(key, ImGuiInputFlags_None);
11357 }
11358
11359 // This is the only public API until we expose owner_id versions of the API as replacements.
11360 bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
11361 {
11362 return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
11363 }
11364
11365 // This is equivalent to comparing KeyMods + doing a IsKeyPressed()
11366 bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11367 {
11368 ImGuiContext& g = *GImGui;
11369 key_chord = FixupKeyChord(key_chord);
11370 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
11371 if (g.IO.KeyMods != mods)
11372 return false;
11373
11374 // Special storage location for mods
11375 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
11376 if (key == ImGuiKey_None)
11377 key = ConvertSingleModFlagToKey(mods);
11378 if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
11379 return false;
11380 return true;
11381 }
11382
11383 void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11384 {
11385 ImGuiContext& g = *GImGui;
11386 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
11387 g.NextItemData.Shortcut = key_chord;
11388 g.NextItemData.ShortcutFlags = flags;
11389 }
11390
11391 // Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
11392 void ImGui::ItemHandleShortcut(ImGuiID id)
11393 {
11394 ImGuiContext& g = *GImGui;
11395 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
11396 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
11397
11398 if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
11399 return;
11400 if (flags & ImGuiInputFlags_Tooltip)
11401 {
11402 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
11403 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
11404 }
11405 if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
11406 return;
11407
11408 // FIXME: Generalize Activation queue?
11409 g.NavActivateId = id; // Will effectively disable clipping.
11410 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
11411 //if (g.ActiveId == 0 || g.ActiveId == id)
11412 g.NavActivateDownId = g.NavActivatePressedId = id;
11413 NavHighlightActivated(id);
11414 }
11415
11416 bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11417 {
11418 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
11419 }
11420
11421 bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11422 {
11423 ImGuiContext& g = *GImGui;
11424 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
11425
11426 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
11427 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
11428 flags |= ImGuiInputFlags_RouteFocused;
11429
11430 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
11431 // Effectively makes Shortcut() always input-owner aware.
11432 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
11433 owner_id = GetRoutingIdFromOwnerId(owner_id);
11434
11435 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11436 return false;
11437
11438 // Submit route
11439 if (!SetShortcutRouting(key_chord, flags, owner_id))
11440 return false;
11441
11442 // Default repeat behavior for Shortcut()
11443 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
11444 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
11445 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
11446
11447 if (!IsKeyChordPressed(key_chord, flags, owner_id))
11448 return false;
11449
11450 // Claim mods during the press
11451 SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
11452
11453 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
11454 return true;
11455 }
11456
11457 //-----------------------------------------------------------------------------
11458 // [SECTION] ERROR CHECKING, STATE RECOVERY
11459 //-----------------------------------------------------------------------------
11460 // - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
11461 // - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11462 // - ErrorCheckNewFrameSanityChecks()
11463 // - ErrorCheckEndFrameSanityChecks()
11464 // - ErrorRecoveryStoreState()
11465 // - ErrorRecoveryTryToRecoverState()
11466 // - ErrorRecoveryTryToRecoverWindowState()
11467 // - ErrorLog()
11468 //-----------------------------------------------------------------------------
11469
11470 // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
11471 // Called by IMGUI_CHECKVERSION().
11472 // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
11473 // If this triggers you have mismatched headers and compiled code versions.
11474 // - It could be because of a build issue (using new headers with old compiled code)
11475 // - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
11476 // THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
11477 // Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
11478 // Otherwise it is possible that different compilation units would see different structure layout.
11479 // If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
11480 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)
11481 {
11482 bool error = false;
11483 if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
11484 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
11485 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
11486 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
11487 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
11488 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
11489 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
11490 return !error;
11491 }
11492
11493 // Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos()
11494 // to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing
11495 // windows, table column contents size used for auto-resizing columns, group size).
11496 // This was causing issues and ambiguities and we needed to retire that.
11497 // From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED.
11498 //
11499 // Previously this would make the window content size ~200x200:
11500 // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE
11501 // Instead, please submit an item:
11502 // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
11503 // Alternative:
11504 // Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
11505 //
11506 // The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item,
11507 // and with a position that would grow the parent contents size.
11508 //
11509 // Advanced:
11510 // - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos())
11511 // had a side-effect on layout! In particular this caused problem to compute group boundaries.
11512 // e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the
11513 // group to be taller because auto-sizing generally adds padding on bottom and right side.
11514 // - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect.
11515 // Using vertical alignment patterns would frequently trigger this sorts of issue.
11516 // - See https://github.com/ocornut/imgui/issues/5548 for more details.
11517 void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11518 {
11519 ImGuiContext& g = *GImGui;
11520 ImGuiWindow* window = g.CurrentWindow;
11521 IM_ASSERT(window->DC.IsSetPos);
11522 window->DC.IsSetPos = false;
11523 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
11524 return;
11525 if (window->SkipItems)
11526 return;
11527 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.");
11528
11529 // For reference, the old behavior was essentially:
11530 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11531 }
11532
11533 static void ImGui::ErrorCheckNewFrameSanityChecks()
11534 {
11535 ImGuiContext& g = *GImGui;
11536
11537 // Check user IM_ASSERT macro
11538 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
11539 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
11540 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
11541 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
11542 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
11543 if (true) IM_ASSERT(1); else IM_ASSERT(0);
11544
11545 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
11546 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
11547 #ifdef __EMSCRIPTEN__
11548 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
11549 g.IO.DeltaTime = 0.00001f;
11550 #endif
11551
11552 // Check user data
11553 // (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)
11554 IM_ASSERT(g.Initialized);
11555 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
11556 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
11557 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
11558 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
11559 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
11560 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
11561 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!");
11562 IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders.
11563 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
11564 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
11565 IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes);
11566
11567 // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
11568 if (g.IO.ConfigErrorRecovery)
11569 IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
11570
11571 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11572 if (g.IO.FontGlobalScale > 1.0f)
11573 IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!");
11574
11575 // Remap legacy names
11576 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
11577 {
11578 g.IO.ConfigNavMoveSetMousePos = true;
11579 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
11580 }
11581 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
11582 {
11583 g.IO.ConfigNavCaptureKeyboard = false;
11584 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
11585 }
11586 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts)
11587 {
11588 g.IO.ConfigDpiScaleFonts = false;
11589 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts;
11590 }
11591 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
11592 {
11593 g.IO.ConfigDpiScaleViewports = false;
11594 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports;
11595 }
11596
11597 // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
11598 if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
11599 g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
11600 if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
11601 g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); };
11602 #endif
11603
11604 // 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.
11605 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
11606 IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11607 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
11608 IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11609
11610 // Perform simple checks: multi-viewport and platform windows support
11611 if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
11612 {
11613 if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
11614 {
11615 IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
11616 IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
11617 IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
11618 IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
11619 IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
11620 IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
11621 IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
11622 IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
11623 IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
11624 if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
11625 IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
11626 }
11627 else
11628 {
11629 // Disable feature, our backends do not support it
11630 g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
11631 }
11632
11633 // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
11634 for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
11635 {
11636 IM_UNUSED(mon);
11637 IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
11638 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.");
11639 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
11640 }
11641 }
11642 }
11643
11644 static void ImGui::ErrorCheckEndFrameSanityChecks()
11645 {
11646 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
11647 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
11648 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
11649 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
11650 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
11651 // while still correctly asserting on mid-frame key press events.
11652 ImGuiContext& g = *GImGui;
11653 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
11654 IM_UNUSED(g);
11655 IM_UNUSED(key_mods);
11656 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
11657 IM_UNUSED(key_mods);
11658
11659 IM_ASSERT(g.CurrentWindowStack.Size == 1);
11660 IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
11661 }
11662
11663 // Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
11664 void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
11665 {
11666 ImGuiContext& g = *GImGui;
11667 state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
11668 state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
11669 state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
11670 state_out->SizeOfColorStack = (short)g.ColorStack.Size;
11671 state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
11672 state_out->SizeOfFontStack = (short)g.FontStack.Size;
11673 state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
11674 state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
11675 state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
11676 state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
11677 state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
11678 }
11679
11680 // Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
11681 // Called by e.g. EndFrame() but may be called for manual recovery.
11682 // Attempt to recover full window stack.
11683 void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
11684 {
11685 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
11686 ImGuiContext& g = *GImGui;
11687 while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
11688 {
11689 // Recap:
11690 // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
11691 // - Always call a matching End() for each Begin() call, regardless of its return value!
11692 // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
11693 // - We will fix that in a future major update.
11694 ImGuiWindow* window = g.CurrentWindow;
11695 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11696 {
11697 if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
11698 {
11699 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11700 EndTable();
11701 }
11702 else
11703 {
11704 IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
11705 EndChild();
11706 }
11707 }
11708 else
11709 {
11710 IM_ASSERT_USER_ERROR(0, "Missing End()");
11711 End();
11712 }
11713 }
11714 if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
11715 ErrorRecoveryTryToRecoverWindowState(state_in);
11716 }
11717
11718 // Called by e.g. End() but may be called for manual recovery.
11719 // Read '// Error Handling [BETA]' block in imgui_internal.h for details.
11720 // Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
11721 void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
11722 {
11723 ImGuiContext& g = *GImGui;
11724
11725 while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
11726 {
11727 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11728 EndTable();
11729 }
11730
11731 ImGuiWindow* window = g.CurrentWindow;
11732
11733 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
11734 while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
11735 {
11736 IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
11737 EndTabBar();
11738 }
11739 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
11740 {
11741 IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
11742 EndMultiSelect();
11743 }
11744 if (window->DC.MenuBarAppending) //-V1044
11745 {
11746 IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()");
11747 EndMenuBar();
11748 }
11749 while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
11750 {
11751 IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
11752 TreePop();
11753 }
11754 while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
11755 {
11756 IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
11757 EndGroup();
11758 }
11759 IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
11760 while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
11761 {
11762 IM_ASSERT_USER_ERROR(0, "Missing PopID()");
11763 PopID();
11764 }
11765 while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
11766 {
11767 IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
11768 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11769 EndDisabled();
11770 else
11771 {
11772 EndDisabledOverrideReenable();
11773 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
11774 }
11775 }
11776 IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
11777 while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
11778 {
11779 IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
11780 PopStyleColor();
11781 }
11782 while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
11783 {
11784 IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
11785 PopItemFlag();
11786 }
11787 while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
11788 {
11789 IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
11790 PopStyleVar();
11791 }
11792 while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
11793 {
11794 IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
11795 PopFont();
11796 }
11797 while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
11798 {
11799 IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
11800 PopFocusScope();
11801 }
11802 //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
11803 }
11804
11805 bool ImGui::ErrorLog(const char* msg)
11806 {
11807 ImGuiContext& g = *GImGui;
11808
11809 // Output to debug log
11810 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11811 ImGuiWindow* window = g.CurrentWindow;
11812
11813 if (g.IO.ConfigErrorRecoveryEnableDebugLog)
11814 {
11815 if (g.ErrorFirst)
11816 IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
11817 g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
11818 IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
11819 }
11820 g.ErrorFirst = false;
11821
11822 // Output to tooltip
11823 if (g.IO.ConfigErrorRecoveryEnableTooltip)
11824 {
11825 if (g.WithinFrameScope && BeginErrorTooltip())
11826 {
11827 if (g.ErrorCountCurrentFrame < 20)
11828 {
11829 Text("In window '%s': %s", window ? window->Name : "NULL", msg);
11830 if (window && (!window->IsFallbackWindow || window->WasActive))
11831 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
11832 }
11833 if (g.ErrorCountCurrentFrame == 20)
11834 Text("(and more errors)");
11835 // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
11836 EndErrorTooltip();
11837 }
11838 g.ErrorCountCurrentFrame++;
11839 }
11840 #endif
11841
11842 // Output to callback
11843 if (g.ErrorCallback != NULL)
11844 g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
11845
11846 // Return whether we should assert
11847 return g.IO.ConfigErrorRecoveryEnableAssert;
11848 }
11849
11850 void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
11851 {
11852 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
11853 ImGuiContext& g = *GImGui;
11854 if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false)
11855 g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
11856 if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
11857 {
11858 Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
11859 BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
11860 BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
11861 //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.
11862 BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
11863 Separator();
11864 if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker)
11865 {
11866 Text("(Hold CTRL to: use ");
11867 SameLine(0.0f, 0.0f);
11868 if (SmallButton("Item Picker"))
11869 DebugStartItemPicker();
11870 SameLine(0.0f, 0.0f);
11871 Text(" to break in item call-stack, or ");
11872 }
11873 else
11874 {
11875 Text("(Hold CTRL to ");
11876 }
11877 SameLine(0.0f, 0.0f);
11878 if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
11879 g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
11880 SameLine(0.0f, 0.0f);
11881 Text(")");
11882 EndErrorTooltip();
11883 }
11884
11885 if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
11886 {
11887 Separator();
11888 Text("(Hold CTRL to:");
11889 SameLine();
11890 if (SmallButton("Enable Asserts"))
11891 g.IO.ConfigErrorRecoveryEnableAssert = true;
11892 //SameLine();
11893 //if (SmallButton("Hide Error Tooltips"))
11894 // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
11895 SameLine(0, 0);
11896 Text(")");
11897 EndErrorTooltip();
11898 }
11899 #endif
11900 }
11901
11902 // Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it.
11903 bool ImGui::BeginErrorTooltip()
11904 {
11905 ImGuiContext& g = *GImGui;
11906 ImGuiWindow* window = FindWindowByName("##Tooltip_Error");
11907 const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
11908 PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.15f));
11909 if (use_locked_pos)
11910 SetNextWindowPos(g.ErrorTooltipLockedPos);
11911 bool is_visible = Begin("##Tooltip_Error", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
11912 PopStyleColor();
11913 if (is_visible && g.CurrentWindow->BeginCount == 1)
11914 {
11915 SeparatorText("MESSAGE FROM DEAR IMGUI");
11916 BringWindowToDisplayFront(g.CurrentWindow);
11917 BringWindowToFocusFront(g.CurrentWindow);
11918 g.ErrorTooltipLockedPos = GetWindowPos();
11919 }
11920 else if (!is_visible)
11921 {
11922 End();
11923 }
11924 return is_visible;
11925 }
11926
11927 void ImGui::EndErrorTooltip()
11928 {
11929 End();
11930 }
11931
11932 //-----------------------------------------------------------------------------
11933 // [SECTION] ITEM SUBMISSION
11934 //-----------------------------------------------------------------------------
11935 // - KeepAliveID()
11936 // - ItemAdd()
11937 //-----------------------------------------------------------------------------
11938
11939 // 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().
11940 void ImGui::KeepAliveID(ImGuiID id)
11941 {
11942 ImGuiContext& g = *GImGui;
11943 if (g.ActiveId == id)
11944 g.ActiveIdIsAlive = id;
11945 if (g.DeactivatedItemData.ID == id)
11946 g.DeactivatedItemData.IsAlive = true;
11947 }
11948
11949 // Declare item bounding box for clipping and interaction.
11950 // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
11951 // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
11952 // THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
11953 IM_MSVC_RUNTIME_CHECKS_OFF
11954 bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
11955 {
11956 ImGuiContext& g = *GImGui;
11957 ImGuiWindow* window = g.CurrentWindow;
11958
11959 // Set item data
11960 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
11961 g.LastItemData.ID = id;
11962 g.LastItemData.Rect = bb;
11963 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
11964 g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
11965 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
11966 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
11967
11968 if (id != 0)
11969 {
11970 KeepAliveID(id);
11971
11972 // Directional navigation processing
11973 // Runs prior to clipping early-out
11974 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
11975 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
11976 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
11977 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
11978 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
11979 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
11980 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
11981 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
11982 if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
11983 {
11984 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
11985 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
11986 if (g.NavId == id || g.NavAnyRequest)
11987 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
11988 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
11989 NavProcessItem();
11990 }
11991
11992 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
11993 ItemHandleShortcut(id);
11994 }
11995
11996 // Lightweight clear of SetNextItemXXX data.
11997 g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
11998 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
11999
12000 #ifdef IMGUI_ENABLE_TEST_ENGINE
12001 if (id != 0)
12002 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
12003 #endif
12004
12005 // Clipping test
12006 // (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')
12007 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
12008 const bool is_rect_visible = bb.Overlaps(window->ClipRect);
12009 if (!is_rect_visible)
12010 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
12011 if (!g.ItemUnclipByLog)
12012 return false;
12013
12014 // [DEBUG]
12015 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
12016 if (id != 0)
12017 {
12018 if (id == g.DebugLocateId)
12019 DebugLocateItemResolveWithLastItem();
12020
12021 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
12022 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
12023 // READ THE FAQ: https://dearimgui.com/faq
12024 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!");
12025
12026 // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED.
12027 // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd().
12028 #ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
12029 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0)
12030 {
12031 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.
12032 int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1);
12033 if (*p_alive == g.FrameCount)
12034 *p_highlight = g.FrameCount;
12035 *p_alive = g.FrameCount;
12036 if (*p_highlight >= g.FrameCount - 1)
12037 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);
12038 }
12039 #endif
12040 }
12041 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
12042 //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
12043 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
12044 #endif
12045
12046 if (id != 0 && g.DeactivatedItemData.ID == id)
12047 g.DeactivatedItemData.ElapseFrame = g.FrameCount;
12048
12049 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
12050 if (is_rect_visible)
12051 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
12052 if (IsMouseHoveringRect(bb.Min, bb.Max))
12053 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
12054 return true;
12055 }
12056 IM_MSVC_RUNTIME_CHECKS_RESTORE
12057
12058 //-----------------------------------------------------------------------------
12059 // [SECTION] LAYOUT
12060 //-----------------------------------------------------------------------------
12061 // - ItemSize()
12062 // - SameLine()
12063 // - GetCursorScreenPos()
12064 // - SetCursorScreenPos()
12065 // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
12066 // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
12067 // - GetCursorStartPos()
12068 // - Indent()
12069 // - Unindent()
12070 // - SetNextItemWidth()
12071 // - PushItemWidth()
12072 // - PushMultiItemsWidths()
12073 // - PopItemWidth()
12074 // - CalcItemWidth()
12075 // - CalcItemSize()
12076 // - GetTextLineHeight()
12077 // - GetTextLineHeightWithSpacing()
12078 // - GetFrameHeight()
12079 // - GetFrameHeightWithSpacing()
12080 // - GetContentRegionMax()
12081 // - GetContentRegionAvail(),
12082 // - BeginGroup()
12083 // - EndGroup()
12084 // Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
12085 //-----------------------------------------------------------------------------
12086
12087 // Advance cursor given item size for layout.
12088 // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
12089 // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
12090 // THIS IS IN THE PERFORMANCE CRITICAL PATH.
12091 IM_MSVC_RUNTIME_CHECKS_OFF
12092 void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
12093 {
12094 ImGuiContext& g = *GImGui;
12095 ImGuiWindow* window = g.CurrentWindow;
12096 if (window->SkipItems)
12097 return;
12098
12099 // We increase the height in this function to accommodate for baseline offset.
12100 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
12101 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
12102 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
12103
12104 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
12105 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);
12106
12107 // Always align ourselves on pixel boundaries
12108 //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]
12109 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
12110 window->DC.CursorPosPrevLine.y = line_y1;
12111 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
12112 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
12113 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
12114 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
12115 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
12116
12117 window->DC.PrevLineSize.y = line_height;
12118 window->DC.CurrLineSize.y = 0.0f;
12119 window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
12120 window->DC.CurrLineTextBaseOffset = 0.0f;
12121 window->DC.IsSameLine = window->DC.IsSetPos = false;
12122
12123 // Horizontal layout mode
12124 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
12125 SameLine();
12126 }
12127 IM_MSVC_RUNTIME_CHECKS_RESTORE
12128
12129 // Gets back to previous line and continue with horizontal layout
12130 // offset_from_start_x == 0 : follow right after previous item
12131 // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
12132 // spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
12133 // spacing_w >= 0 : enforce spacing amount
12134 void ImGui::SameLine(float offset_from_start_x, float spacing_w)
12135 {
12136 ImGuiContext& g = *GImGui;
12137 ImGuiWindow* window = g.CurrentWindow;
12138 if (window->SkipItems)
12139 return;
12140
12141 if (offset_from_start_x != 0.0f)
12142 {
12143 if (spacing_w < 0.0f)
12144 spacing_w = 0.0f;
12145 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
12146 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
12147 }
12148 else
12149 {
12150 if (spacing_w < 0.0f)
12151 spacing_w = g.Style.ItemSpacing.x;
12152 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
12153 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
12154 }
12155 window->DC.CurrLineSize = window->DC.PrevLineSize;
12156 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
12157 window->DC.IsSameLine = true;
12158 }
12159
12160 ImVec2 ImGui::GetCursorScreenPos()
12161 {
12162 ImGuiWindow* window = GetCurrentWindowRead();
12163 return window->DC.CursorPos;
12164 }
12165
12166 void ImGui::SetCursorScreenPos(const ImVec2& pos)
12167 {
12168 ImGuiWindow* window = GetCurrentWindow();
12169 window->DC.CursorPos = pos;
12170 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
12171 window->DC.IsSetPos = true;
12172 }
12173
12174 // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
12175 // 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'.
12176 ImVec2 ImGui::GetCursorPos()
12177 {
12178 ImGuiWindow* window = GetCurrentWindowRead();
12179 return window->DC.CursorPos - window->Pos + window->Scroll;
12180 }
12181
12182 float ImGui::GetCursorPosX()
12183 {
12184 ImGuiWindow* window = GetCurrentWindowRead();
12185 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
12186 }
12187
12188 float ImGui::GetCursorPosY()
12189 {
12190 ImGuiWindow* window = GetCurrentWindowRead();
12191 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
12192 }
12193
12194 void ImGui::SetCursorPos(const ImVec2& local_pos)
12195 {
12196 ImGuiWindow* window = GetCurrentWindow();
12197 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
12198 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
12199 window->DC.IsSetPos = true;
12200 }
12201
12202 void ImGui::SetCursorPosX(float x)
12203 {
12204 ImGuiWindow* window = GetCurrentWindow();
12205 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
12206 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
12207 window->DC.IsSetPos = true;
12208 }
12209
12210 void ImGui::SetCursorPosY(float y)
12211 {
12212 ImGuiWindow* window = GetCurrentWindow();
12213 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
12214 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
12215 window->DC.IsSetPos = true;
12216 }
12217
12218 ImVec2 ImGui::GetCursorStartPos()
12219 {
12220 ImGuiWindow* window = GetCurrentWindowRead();
12221 return window->DC.CursorStartPos - window->Pos;
12222 }
12223
12224 void ImGui::Indent(float indent_w)
12225 {
12226 ImGuiContext& g = *GImGui;
12227 ImGuiWindow* window = GetCurrentWindow();
12228 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
12229 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
12230 }
12231
12232 void ImGui::Unindent(float indent_w)
12233 {
12234 ImGuiContext& g = *GImGui;
12235 ImGuiWindow* window = GetCurrentWindow();
12236 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
12237 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
12238 }
12239
12240 // Affect large frame+labels widgets only.
12241 void ImGui::SetNextItemWidth(float item_width)
12242 {
12243 ImGuiContext& g = *GImGui;
12244 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
12245 g.NextItemData.Width = item_width;
12246 }
12247
12248 // FIXME: Remove the == 0.0f behavior?
12249 void ImGui::PushItemWidth(float item_width)
12250 {
12251 ImGuiContext& g = *GImGui;
12252 ImGuiWindow* window = g.CurrentWindow;
12253 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
12254 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
12255 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
12256 }
12257
12258 void ImGui::PushMultiItemsWidths(int components, float w_full)
12259 {
12260 ImGuiContext& g = *GImGui;
12261 ImGuiWindow* window = g.CurrentWindow;
12262 IM_ASSERT(components > 0);
12263 const ImGuiStyle& style = g.Style;
12264 window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
12265 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
12266 float prev_split = w_items;
12267 for (int i = components - 1; i > 0; i--)
12268 {
12269 float next_split = IM_TRUNC(w_items * i / components);
12270 window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
12271 prev_split = next_split;
12272 }
12273 window->DC.ItemWidth = ImMax(prev_split, 1.0f);
12274 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
12275 }
12276
12277 void ImGui::PopItemWidth()
12278 {
12279 ImGuiContext& g = *GImGui;
12280 ImGuiWindow* window = g.CurrentWindow;
12281 if (window->DC.ItemWidthStack.Size <= 0)
12282 {
12283 IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
12284 return;
12285 }
12286 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
12287 window->DC.ItemWidthStack.pop_back();
12288 }
12289
12290 // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
12291 // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
12292 float ImGui::CalcItemWidth()
12293 {
12294 ImGuiContext& g = *GImGui;
12295 ImGuiWindow* window = g.CurrentWindow;
12296 float w;
12297 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
12298 w = g.NextItemData.Width;
12299 else
12300 w = window->DC.ItemWidth;
12301 if (w < 0.0f)
12302 {
12303 float region_avail_x = GetContentRegionAvail().x;
12304 w = ImMax(1.0f, region_avail_x + w);
12305 }
12306 w = IM_TRUNC(w);
12307 return w;
12308 }
12309
12310 // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
12311 // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
12312 // Note that only CalcItemWidth() is publicly exposed.
12313 // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
12314 ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
12315 {
12316 ImVec2 avail;
12317 if (size.x < 0.0f || size.y < 0.0f)
12318 avail = GetContentRegionAvail();
12319
12320 if (size.x == 0.0f)
12321 size.x = default_w;
12322 else if (size.x < 0.0f)
12323 size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting
12324
12325 if (size.y == 0.0f)
12326 size.y = default_h;
12327 else if (size.y < 0.0f)
12328 size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting
12329
12330 return size;
12331 }
12332
12333 float ImGui::GetTextLineHeight()
12334 {
12335 ImGuiContext& g = *GImGui;
12336 return g.FontSize;
12337 }
12338
12339 float ImGui::GetTextLineHeightWithSpacing()
12340 {
12341 ImGuiContext& g = *GImGui;
12342 return g.FontSize + g.Style.ItemSpacing.y;
12343 }
12344
12345 float ImGui::GetFrameHeight()
12346 {
12347 ImGuiContext& g = *GImGui;
12348 return g.FontSize + g.Style.FramePadding.y * 2.0f;
12349 }
12350
12351 float ImGui::GetFrameHeightWithSpacing()
12352 {
12353 ImGuiContext& g = *GImGui;
12354 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
12355 }
12356
12357 ImVec2 ImGui::GetContentRegionAvail()
12358 {
12359 ImGuiContext& g = *GImGui;
12360 ImGuiWindow* window = g.CurrentWindow;
12361 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
12362 return mx - window->DC.CursorPos;
12363 }
12364
12365 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
12366
12367 // You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
12368 // They are bizarre local-coordinates which don't play well with scrolling.
12369 ImVec2 ImGui::GetContentRegionMax()
12370 {
12371 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
12372 }
12373
12374 ImVec2 ImGui::GetWindowContentRegionMin()
12375 {
12376 ImGuiWindow* window = GImGui->CurrentWindow;
12377 return window->ContentRegionRect.Min - window->Pos;
12378 }
12379
12380 ImVec2 ImGui::GetWindowContentRegionMax()
12381 {
12382 ImGuiWindow* window = GImGui->CurrentWindow;
12383 return window->ContentRegionRect.Max - window->Pos;
12384 }
12385 #endif
12386
12387 // 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.)
12388 // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
12389 // FIXME-OPT: Could we safely early out on ->SkipItems?
12390 void ImGui::BeginGroup()
12391 {
12392 ImGuiContext& g = *GImGui;
12393 ImGuiWindow* window = g.CurrentWindow;
12394
12395 g.GroupStack.resize(g.GroupStack.Size + 1);
12396 ImGuiGroupData& group_data = g.GroupStack.back();
12397 group_data.WindowID = window->ID;
12398 group_data.BackupCursorPos = window->DC.CursorPos;
12399 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
12400 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
12401 group_data.BackupIndent = window->DC.Indent;
12402 group_data.BackupGroupOffset = window->DC.GroupOffset;
12403 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
12404 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
12405 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
12406 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
12407 group_data.BackupIsSameLine = window->DC.IsSameLine;
12408 group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive;
12409 group_data.EmitItem = true;
12410
12411 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
12412 window->DC.Indent = window->DC.GroupOffset;
12413 window->DC.CursorMaxPos = window->DC.CursorPos;
12414 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
12415 if (g.LogEnabled)
12416 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12417 }
12418
12419 void ImGui::EndGroup()
12420 {
12421 ImGuiContext& g = *GImGui;
12422 ImGuiWindow* window = g.CurrentWindow;
12423 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
12424
12425 ImGuiGroupData& group_data = g.GroupStack.back();
12426 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
12427
12428 if (window->DC.IsSetPos)
12429 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
12430
12431 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
12432 ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos));
12433 window->DC.CursorPos = group_data.BackupCursorPos;
12434 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
12435 window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max);
12436 window->DC.Indent = group_data.BackupIndent;
12437 window->DC.GroupOffset = group_data.BackupGroupOffset;
12438 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
12439 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
12440 window->DC.IsSameLine = group_data.BackupIsSameLine;
12441 if (g.LogEnabled)
12442 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12443
12444 if (!group_data.EmitItem)
12445 {
12446 g.GroupStack.pop_back();
12447 return;
12448 }
12449
12450 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.
12451 ItemSize(group_bb.GetSize());
12452 ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
12453
12454 // 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.
12455 // 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.
12456 // Also if you grep for LastItemId you'll notice it is only used in that context.
12457 // (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.)
12458 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
12459 const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true);
12460 if (group_contains_curr_active_id)
12461 g.LastItemData.ID = g.ActiveId;
12462 else if (group_contains_deactivated_id)
12463 g.LastItemData.ID = g.DeactivatedItemData.ID;
12464 g.LastItemData.Rect = group_bb;
12465
12466 // Forward Hovered flag
12467 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
12468 if (group_contains_curr_hovered_id)
12469 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
12470
12471 // Forward Edited flag
12472 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
12473 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
12474
12475 // Forward Deactivated flag
12476 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
12477 if (group_contains_deactivated_id)
12478 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
12479
12480 g.GroupStack.pop_back();
12481 if (g.DebugShowGroupRects)
12482 window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
12483 }
12484
12485
12486 //-----------------------------------------------------------------------------
12487 // [SECTION] SCROLLING
12488 //-----------------------------------------------------------------------------
12489
12490 // Helper to snap on edges when aiming at an item very close to the edge,
12491 // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
12492 // When we refactor the scrolling API this may be configurable with a flag?
12493 // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
12494 static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
12495 {
12496 if (target <= snap_min + snap_threshold)
12497 return ImLerp(snap_min, target, center_ratio);
12498 if (target >= snap_max - snap_threshold)
12499 return ImLerp(target, snap_max, center_ratio);
12500 return target;
12501 }
12502
12503 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
12504 {
12505 ImVec2 scroll = window->Scroll;
12506 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
12507 for (int axis = 0; axis < 2; axis++)
12508 {
12509 if (window->ScrollTarget[axis] < FLT_MAX)
12510 {
12511 float center_ratio = window->ScrollTargetCenterRatio[axis];
12512 float scroll_target = window->ScrollTarget[axis];
12513 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
12514 {
12515 float snap_min = 0.0f;
12516 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
12517 scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
12518 }
12519 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
12520 }
12521 scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f));
12522 if (!window->Collapsed && !window->SkipItems)
12523 scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
12524 }
12525 return scroll;
12526 }
12527
12528 void ImGui::ScrollToItem(ImGuiScrollFlags flags)
12529 {
12530 ImGuiContext& g = *GImGui;
12531 ImGuiWindow* window = g.CurrentWindow;
12532 ScrollToRectEx(window, g.LastItemData.NavRect, flags);
12533 }
12534
12535 void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12536 {
12537 ScrollToRectEx(window, item_rect, flags);
12538 }
12539
12540 // Scroll to keep newly navigated item fully into view
12541 ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12542 {
12543 ImGuiContext& g = *GImGui;
12544 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
12545 scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
12546 scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
12547 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
12548 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
12549
12550 // Check that only one behavior is selected per axis
12551 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
12552 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
12553
12554 // Defaults
12555 ImGuiScrollFlags in_flags = flags;
12556 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
12557 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
12558 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
12559 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
12560
12561 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
12562 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
12563 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;
12564 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;
12565
12566 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
12567 {
12568 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
12569 SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
12570 else if (item_rect.Max.x >= scroll_rect.Max.x)
12571 SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
12572 }
12573 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
12574 {
12575 if (can_be_fully_visible_x)
12576 SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
12577 else
12578 SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
12579 }
12580
12581 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
12582 {
12583 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
12584 SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
12585 else if (item_rect.Max.y >= scroll_rect.Max.y)
12586 SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
12587 }
12588 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
12589 {
12590 if (can_be_fully_visible_y)
12591 SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
12592 else
12593 SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
12594 }
12595
12596 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12597 ImVec2 delta_scroll = next_scroll - window->Scroll;
12598
12599 // Also scroll parent window to keep us into view if necessary
12600 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
12601 {
12602 // FIXME-SCROLL: May be an option?
12603 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
12604 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
12605 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
12606 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
12607 delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
12608 }
12609
12610 return delta_scroll;
12611 }
12612
12613 float ImGui::GetScrollX()
12614 {
12615 ImGuiWindow* window = GImGui->CurrentWindow;
12616 return window->Scroll.x;
12617 }
12618
12619 float ImGui::GetScrollY()
12620 {
12621 ImGuiWindow* window = GImGui->CurrentWindow;
12622 return window->Scroll.y;
12623 }
12624
12625 float ImGui::GetScrollMaxX()
12626 {
12627 ImGuiWindow* window = GImGui->CurrentWindow;
12628 return window->ScrollMax.x;
12629 }
12630
12631 float ImGui::GetScrollMaxY()
12632 {
12633 ImGuiWindow* window = GImGui->CurrentWindow;
12634 return window->ScrollMax.y;
12635 }
12636
12637 void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
12638 {
12639 window->ScrollTarget.x = scroll_x;
12640 window->ScrollTargetCenterRatio.x = 0.0f;
12641 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12642 }
12643
12644 void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
12645 {
12646 window->ScrollTarget.y = scroll_y;
12647 window->ScrollTargetCenterRatio.y = 0.0f;
12648 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12649 }
12650
12651 void ImGui::SetScrollX(float scroll_x)
12652 {
12653 ImGuiContext& g = *GImGui;
12654 SetScrollX(g.CurrentWindow, scroll_x);
12655 }
12656
12657 void ImGui::SetScrollY(float scroll_y)
12658 {
12659 ImGuiContext& g = *GImGui;
12660 SetScrollY(g.CurrentWindow, scroll_y);
12661 }
12662
12663 // Note that a local position will vary depending on initial scroll value,
12664 // This is a little bit confusing so bear with us:
12665 // - local_pos = (absolution_pos - window->Pos)
12666 // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
12667 // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
12668 // - They mostly exist because of legacy API.
12669 // Following the rules above, when trying to work with scrolling code, consider that:
12670 // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
12671 // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
12672 // 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
12673 void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
12674 {
12675 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
12676 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
12677 window->ScrollTargetCenterRatio.x = center_x_ratio;
12678 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12679 }
12680
12681 void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
12682 {
12683 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
12684 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
12685 window->ScrollTargetCenterRatio.y = center_y_ratio;
12686 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12687 }
12688
12689 void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
12690 {
12691 ImGuiContext& g = *GImGui;
12692 SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
12693 }
12694
12695 void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
12696 {
12697 ImGuiContext& g = *GImGui;
12698 SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
12699 }
12700
12701 // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
12702 void ImGui::SetScrollHereX(float center_x_ratio)
12703 {
12704 ImGuiContext& g = *GImGui;
12705 ImGuiWindow* window = g.CurrentWindow;
12706 float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
12707 float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
12708 SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
12709
12710 // Tweak: snap on edges when aiming at an item very close to the edge
12711 window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
12712 }
12713
12714 // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
12715 void ImGui::SetScrollHereY(float center_y_ratio)
12716 {
12717 ImGuiContext& g = *GImGui;
12718 ImGuiWindow* window = g.CurrentWindow;
12719 float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
12720 float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
12721 SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
12722
12723 // Tweak: snap on edges when aiming at an item very close to the edge
12724 window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
12725 }
12726
12727 //-----------------------------------------------------------------------------
12728 // [SECTION] TOOLTIPS
12729 //-----------------------------------------------------------------------------
12730
12731 bool ImGui::BeginTooltip()
12732 {
12733 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
12734 }
12735
12736 bool ImGui::BeginItemTooltip()
12737 {
12738 if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12739 return false;
12740 return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
12741 }
12742
12743 bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
12744 {
12745 ImGuiContext& g = *GImGui;
12746
12747 const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
12748 if (is_dragdrop_tooltip)
12749 {
12750 // Drag and Drop tooltips are positioning differently than other tooltips:
12751 // - offset visibility to increase visibility around mouse.
12752 // - never clamp within outer viewport boundary.
12753 // We call SetNextWindowPos() to enforce position and disable clamping.
12754 // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones).
12755 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
12756 const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
12757 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12758 {
12759 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);
12760 ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
12761 SetNextWindowPos(tooltip_pos, ImGuiCond_None, tooltip_pivot);
12762 }
12763
12764 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
12765 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
12766 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
12767 }
12768
12769 const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
12770 char window_name[32];
12771 ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, g.TooltipOverrideCount);
12772 if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active)
12773 {
12774 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
12775 //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
12776 SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
12777 ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, ++g.TooltipOverrideCount);
12778 }
12779
12780 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
12781 Begin(window_name, NULL, flags | extra_window_flags);
12782 // 2023-03-09: Added bool return value to the API, but currently always returning true.
12783 // If this ever returns false we need to update BeginDragDropSource() accordingly.
12784 //if (!ret)
12785 // End();
12786 //return ret;
12787 return true;
12788 }
12789
12790 void ImGui::EndTooltip()
12791 {
12792 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
12793 End();
12794 }
12795
12796 void ImGui::SetTooltip(const char* fmt, ...)
12797 {
12798 va_list args;
12799 va_start(args, fmt);
12800 SetTooltipV(fmt, args);
12801 va_end(args);
12802 }
12803
12804 void ImGui::SetTooltipV(const char* fmt, va_list args)
12805 {
12806 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
12807 return;
12808 TextV(fmt, args);
12809 EndTooltip();
12810 }
12811
12812 // Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
12813 // Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
12814 void ImGui::SetItemTooltip(const char* fmt, ...)
12815 {
12816 va_list args;
12817 va_start(args, fmt);
12818 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12819 SetTooltipV(fmt, args);
12820 va_end(args);
12821 }
12822
12823 void ImGui::SetItemTooltipV(const char* fmt, va_list args)
12824 {
12825 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
12826 SetTooltipV(fmt, args);
12827 }
12828
12829
12830 //-----------------------------------------------------------------------------
12831 // [SECTION] POPUPS
12832 //-----------------------------------------------------------------------------
12833
12834 // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
12835 bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
12836 {
12837 ImGuiContext& g = *GImGui;
12838 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
12839 {
12840 // Return true if any popup is open at the current BeginPopup() level of the popup stack
12841 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
12842 IM_ASSERT(id == 0);
12843 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12844 return g.OpenPopupStack.Size > 0;
12845 else
12846 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
12847 }
12848 else
12849 {
12850 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12851 {
12852 // Return true if the popup is open anywhere in the popup stack
12853 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12854 if (popup_data.PopupId == id)
12855 return true;
12856 return false;
12857 }
12858 else
12859 {
12860 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
12861 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
12862 }
12863 }
12864 }
12865
12866 bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
12867 {
12868 ImGuiContext& g = *GImGui;
12869 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
12870 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
12871 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
12872 return IsPopupOpen(id, popup_flags);
12873 }
12874
12875 // Also see FindBlockingModal(NULL)
12876 ImGuiWindow* ImGui::GetTopMostPopupModal()
12877 {
12878 ImGuiContext& g = *GImGui;
12879 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12880 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12881 if (popup->Flags & ImGuiWindowFlags_Modal)
12882 return popup;
12883 return NULL;
12884 }
12885
12886 // See Demo->Stacked Modal to confirm what this is for.
12887 ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
12888 {
12889 ImGuiContext& g = *GImGui;
12890 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12891 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12892 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
12893 return popup;
12894 return NULL;
12895 }
12896
12897
12898 // When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
12899 // should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
12900 // In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
12901 // - WindowA // FindBlockingModal() returns Modal1
12902 // - WindowB // .. returns Modal1
12903 // - Modal1 // .. returns Modal2
12904 // - WindowC // .. returns Modal2
12905 // - WindowD // .. returns Modal2
12906 // - Modal2 // .. returns Modal2
12907 // - WindowE // .. returns NULL
12908 // Notes:
12909 // - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
12910 // Only difference is here we check for ->Active/WasActive but it may be unnecessary.
12911 ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
12912 {
12913 ImGuiContext& g = *GImGui;
12914 if (g.OpenPopupStack.Size <= 0)
12915 return NULL;
12916
12917 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
12918 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12919 {
12920 ImGuiWindow* popup_window = popup_data.Window;
12921 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
12922 continue;
12923 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.
12924 continue;
12925 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
12926 return popup_window;
12927 if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal
12928 continue;
12929 return popup_window; // Place window right below first block modal
12930 }
12931 return NULL;
12932 }
12933
12934 void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
12935 {
12936 ImGuiContext& g = *GImGui;
12937 ImGuiID id = g.CurrentWindow->GetID(str_id);
12938 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
12939 OpenPopupEx(id, popup_flags);
12940 }
12941
12942 void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
12943 {
12944 OpenPopupEx(id, popup_flags);
12945 }
12946
12947 // Mark popup as open (toggle toward open state).
12948 // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
12949 // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
12950 // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
12951 void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
12952 {
12953 ImGuiContext& g = *GImGui;
12954 ImGuiWindow* parent_window = g.CurrentWindow;
12955 const int current_stack_size = g.BeginPopupStack.Size;
12956
12957 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
12958 if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
12959 return;
12960
12961 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
12962 popup_ref.PopupId = id;
12963 popup_ref.Window = NULL;
12964 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
12965 popup_ref.OpenFrameCount = g.FrameCount;
12966 popup_ref.OpenParentId = parent_window->IDStack.back();
12967 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
12968 popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
12969
12970 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
12971 if (g.OpenPopupStack.Size < current_stack_size + 1)
12972 {
12973 g.OpenPopupStack.push_back(popup_ref);
12974 }
12975 else
12976 {
12977 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
12978 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
12979 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
12980 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
12981 bool keep_existing = false;
12982 if (g.OpenPopupStack[current_stack_size].PopupId == id)
12983 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
12984 keep_existing = true;
12985 if (keep_existing)
12986 {
12987 // No reopen
12988 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
12989 }
12990 else
12991 {
12992 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
12993 ClosePopupToLevel(current_stack_size, true);
12994 g.OpenPopupStack.push_back(popup_ref);
12995 }
12996
12997 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
12998 // This is equivalent to what ClosePopupToLevel() does.
12999 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
13000 // FocusWindow(parent_window);
13001 }
13002 }
13003
13004 // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
13005 // This function closes any popups that are over 'ref_window'.
13006 void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
13007 {
13008 ImGuiContext& g = *GImGui;
13009 if (g.OpenPopupStack.Size == 0)
13010 return;
13011
13012 // Don't close our own child popup windows.
13013 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
13014 int popup_count_to_keep = 0;
13015 if (ref_window)
13016 {
13017 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
13018 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
13019 {
13020 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
13021 if (!popup.Window)
13022 continue;
13023 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
13024
13025 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
13026 // - Clicking/Focusing Window2 won't close Popup1:
13027 // Window -> Popup1 -> Window2(Ref)
13028 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
13029 // Window -> Popup1(Ref) -> Popup2 -> Popup3
13030 // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
13031 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
13032 // We step through every popup from bottom to top to validate their position relative to reference window.
13033 bool ref_window_is_descendent_of_popup = false;
13034 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
13035 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
13036 //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
13037 if (IsWindowWithinBeginStackOf(ref_window, popup_window))
13038 {
13039 ref_window_is_descendent_of_popup = true;
13040 break;
13041 }
13042 if (!ref_window_is_descendent_of_popup)
13043 break;
13044 }
13045 }
13046 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
13047 {
13048 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
13049 ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
13050 }
13051 }
13052
13053 void ImGui::ClosePopupsExceptModals()
13054 {
13055 ImGuiContext& g = *GImGui;
13056
13057 int popup_count_to_keep;
13058 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
13059 {
13060 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
13061 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
13062 break;
13063 }
13064 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
13065 ClosePopupToLevel(popup_count_to_keep, true);
13066 }
13067
13068 void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
13069 {
13070 ImGuiContext& g = *GImGui;
13071 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
13072 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
13073 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)
13074 for (int n = remaining; n < g.OpenPopupStack.Size; n++)
13075 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);
13076
13077 // Trim open popup stack
13078 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
13079 g.OpenPopupStack.resize(remaining);
13080
13081 // 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)
13082 if (restore_focus_to_window_under_popup && prev_popup.Window)
13083 {
13084 ImGuiWindow* popup_window = prev_popup.Window;
13085 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
13086 if (focus_window && !focus_window->WasActive)
13087 FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
13088 else
13089 FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
13090 }
13091 }
13092
13093 // Close the popup we have begin-ed into.
13094 void ImGui::CloseCurrentPopup()
13095 {
13096 ImGuiContext& g = *GImGui;
13097 int popup_idx = g.BeginPopupStack.Size - 1;
13098 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
13099 return;
13100
13101 // Closing a menu closes its top-most parent popup (unless a modal)
13102 while (popup_idx > 0)
13103 {
13104 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
13105 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
13106 bool close_parent = false;
13107 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
13108 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
13109 close_parent = true;
13110 if (!close_parent)
13111 break;
13112 popup_idx--;
13113 }
13114 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
13115 ClosePopupToLevel(popup_idx, true);
13116
13117 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
13118 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
13119 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
13120 if (ImGuiWindow* window = g.NavWindow)
13121 window->DC.NavHideHighlightOneFrame = true;
13122 }
13123
13124 // Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
13125 bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
13126 {
13127 ImGuiContext& g = *GImGui;
13128 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
13129 {
13130 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
13131 return false;
13132 }
13133
13134 char name[20];
13135 IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx()
13136 ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame
13137
13138 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
13139 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
13140 EndPopup();
13141 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
13142 return is_open;
13143 }
13144
13145 bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags)
13146 {
13147 ImGuiContext& g = *GImGui;
13148 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
13149 {
13150 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
13151 return false;
13152 }
13153
13154 char name[128];
13155 IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu);
13156 ImFormatString(name, IM_ARRAYSIZE(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth
13157 bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup);
13158 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
13159 EndPopup();
13160 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
13161 return is_open;
13162 }
13163
13164 bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
13165 {
13166 ImGuiContext& g = *GImGui;
13167 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
13168 {
13169 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
13170 return false;
13171 }
13172 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
13173 ImGuiID id = g.CurrentWindow->GetID(str_id);
13174 return BeginPopupEx(id, flags);
13175 }
13176
13177 // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
13178 // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
13179 // - *p_open set back to false in BeginPopupModal() when popup is not open.
13180 // - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
13181 bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
13182 {
13183 ImGuiContext& g = *GImGui;
13184 ImGuiWindow* window = g.CurrentWindow;
13185 const ImGuiID id = window->GetID(name);
13186 if (!IsPopupOpen(id, ImGuiPopupFlags_None))
13187 {
13188 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
13189 if (p_open && *p_open)
13190 *p_open = false;
13191 return false;
13192 }
13193
13194 // Center modal windows by default for increased visibility
13195 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
13196 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
13197 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
13198 {
13199 const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
13200 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
13201 }
13202
13203 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
13204 const bool is_open = Begin(name, p_open, flags);
13205 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
13206 {
13207 EndPopup();
13208 if (is_open)
13209 ClosePopupToLevel(g.BeginPopupStack.Size, true);
13210 return false;
13211 }
13212 return is_open;
13213 }
13214
13215 void ImGui::EndPopup()
13216 {
13217 ImGuiContext& g = *GImGui;
13218 ImGuiWindow* window = g.CurrentWindow;
13219 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0)
13220 {
13221 IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!");
13222 return;
13223 }
13224
13225 // 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)
13226 if (g.NavWindow == window)
13227 NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
13228
13229 // Child-popups don't need to be laid out
13230 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
13231 if (window->Flags & ImGuiWindowFlags_ChildWindow)
13232 g.WithinEndChildID = window->ID;
13233 End();
13234 g.WithinEndChildID = backup_within_end_child_id;
13235 }
13236
13237 // Helper to open a popup if mouse button is released over the item
13238 // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
13239 void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
13240 {
13241 ImGuiContext& g = *GImGui;
13242 ImGuiWindow* window = g.CurrentWindow;
13243 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13244 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13245 {
13246 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!
13247 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
13248 OpenPopupEx(id, popup_flags);
13249 }
13250 }
13251
13252 // This is a helper to handle the simplest case of associating one named popup to one given widget.
13253 // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
13254 // - To create a popup with a specific identifier, pass it in str_id.
13255 // - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
13256 // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
13257 // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
13258 // This is essentially the same as:
13259 // id = str_id ? GetID(str_id) : GetItemID();
13260 // OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
13261 // return BeginPopup(id);
13262 // Which is essentially the same as:
13263 // id = str_id ? GetID(str_id) : GetItemID();
13264 // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
13265 // OpenPopup(id);
13266 // return BeginPopup(id);
13267 // The main difference being that this is tweaked to avoid computing the ID twice.
13268 bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
13269 {
13270 ImGuiContext& g = *GImGui;
13271 ImGuiWindow* window = g.CurrentWindow;
13272 if (window->SkipItems)
13273 return false;
13274 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!
13275 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
13276 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13277 if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13278 OpenPopupEx(id, popup_flags);
13279 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13280 }
13281
13282 bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
13283 {
13284 ImGuiContext& g = *GImGui;
13285 ImGuiWindow* window = g.CurrentWindow;
13286 if (!str_id)
13287 str_id = "window_context";
13288 ImGuiID id = window->GetID(str_id);
13289 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13290 if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13291 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
13292 OpenPopupEx(id, popup_flags);
13293 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13294 }
13295
13296 bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
13297 {
13298 ImGuiContext& g = *GImGui;
13299 ImGuiWindow* window = g.CurrentWindow;
13300 if (!str_id)
13301 str_id = "void_context";
13302 ImGuiID id = window->GetID(str_id);
13303 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13304 if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
13305 if (GetTopMostPopupModal() == NULL)
13306 OpenPopupEx(id, popup_flags);
13307 return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13308 }
13309
13310 // 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.)
13311 // 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.
13312 // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
13313 // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
13314 // this allows us to have tooltips/popups displayed out of the parent viewport.)
13315 ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
13316 {
13317 ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
13318 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
13319 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
13320
13321 // Combo Box policy (we want a connecting edge)
13322 if (policy == ImGuiPopupPositionPolicy_ComboBox)
13323 {
13324 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
13325 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13326 {
13327 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13328 if (n != -1 && dir == *last_dir) // Already tried this direction?
13329 continue;
13330 ImVec2 pos;
13331 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
13332 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
13333 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
13334 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
13335 if (!r_outer.Contains(ImRect(pos, pos + size)))
13336 continue;
13337 *last_dir = dir;
13338 return pos;
13339 }
13340 }
13341
13342 // Tooltip and Default popup policy
13343 // (Always first try the direction we used on the last frame, if any)
13344 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
13345 {
13346 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
13347 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13348 {
13349 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13350 if (n != -1 && dir == *last_dir) // Already tried this direction?
13351 continue;
13352
13353 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);
13354 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);
13355
13356 // 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)
13357 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
13358 continue;
13359 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
13360 continue;
13361
13362 ImVec2 pos;
13363 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
13364 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
13365
13366 // Clamp top-left corner of popup
13367 pos.x = ImMax(pos.x, r_outer.Min.x);
13368 pos.y = ImMax(pos.y, r_outer.Min.y);
13369
13370 *last_dir = dir;
13371 return pos;
13372 }
13373 }
13374
13375 // Fallback when not enough room:
13376 *last_dir = ImGuiDir_None;
13377
13378 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
13379 if (policy == ImGuiPopupPositionPolicy_Tooltip)
13380 return ref_pos + ImVec2(2, 2);
13381
13382 // Otherwise try to keep within display
13383 ImVec2 pos = ref_pos;
13384 pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
13385 pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
13386 return pos;
13387 }
13388
13389 // Note that this is used for popups, which can overlap the non work-area of individual viewports.
13390 ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
13391 {
13392 ImGuiContext& g = *GImGui;
13393 ImRect r_screen;
13394 if (window->ViewportAllowPlatformMonitorExtend >= 0)
13395 {
13396 // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
13397 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
13398 r_screen.Min = monitor.WorkPos;
13399 r_screen.Max = monitor.WorkPos + monitor.WorkSize;
13400 }
13401 else
13402 {
13403 // Use the full viewport area (not work area) for popups
13404 r_screen = window->Viewport->GetMainRect();
13405 }
13406 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
13407 r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
13408 return r_screen;
13409 }
13410
13411 ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
13412 {
13413 ImGuiContext& g = *GImGui;
13414
13415 ImRect r_outer = GetPopupAllowedExtentRect(window);
13416 if (window->Flags & ImGuiWindowFlags_ChildMenu)
13417 {
13418 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
13419 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
13420 ImGuiWindow* parent_window = window->ParentWindow;
13421 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).
13422 ImRect r_avoid;
13423 if (parent_window->DC.MenuBarAppending)
13424 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
13425 else
13426 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);
13427 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
13428 }
13429 if (window->Flags & ImGuiWindowFlags_Popup)
13430 {
13431 return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
13432 }
13433 if (window->Flags & ImGuiWindowFlags_Tooltip)
13434 {
13435 // Position tooltip (always follows mouse + clamp within outer boundaries)
13436 // FIXME:
13437 // - 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).
13438 // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
13439 // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
13440 // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
13441 IM_ASSERT(g.CurrentWindow == window);
13442 const float scale = g.Style.MouseCursorScale;
13443 const ImVec2 ref_pos = NavCalcPreferredRefPos();
13444
13445 if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
13446 {
13447 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
13448 if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
13449 return tooltip_pos;
13450 }
13451
13452 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
13453 ImRect r_avoid;
13454 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
13455 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
13456 else
13457 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.
13458 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
13459
13460 return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
13461 }
13462 IM_ASSERT(0);
13463 return window->Pos;
13464 }
13465
13466 //-----------------------------------------------------------------------------
13467 // [SECTION] WINDOW FOCUS
13468 //----------------------------------------------------------------------------
13469 // - SetWindowFocus()
13470 // - SetNextWindowFocus()
13471 // - IsWindowFocused()
13472 // - UpdateWindowInFocusOrderList() [Internal]
13473 // - BringWindowToFocusFront() [Internal]
13474 // - BringWindowToDisplayFront() [Internal]
13475 // - BringWindowToDisplayBack() [Internal]
13476 // - BringWindowToDisplayBehind() [Internal]
13477 // - FindWindowDisplayIndex() [Internal]
13478 // - FocusWindow() [Internal]
13479 // - FocusTopMostWindowUnderOne() [Internal]
13480 //-----------------------------------------------------------------------------
13481
13482 void ImGui::SetWindowFocus()
13483 {
13484 FocusWindow(GImGui->CurrentWindow);
13485 }
13486
13487 void ImGui::SetWindowFocus(const char* name)
13488 {
13489 if (name)
13490 {
13491 if (ImGuiWindow* window = FindWindowByName(name))
13492 FocusWindow(window);
13493 }
13494 else
13495 {
13496 FocusWindow(NULL);
13497 }
13498 }
13499
13500 void ImGui::SetNextWindowFocus()
13501 {
13502 ImGuiContext& g = *GImGui;
13503 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus;
13504 }
13505
13506 // Similar to IsWindowHovered()
13507 bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
13508 {
13509 ImGuiContext& g = *GImGui;
13510 ImGuiWindow* ref_window = g.NavWindow;
13511 ImGuiWindow* cur_window = g.CurrentWindow;
13512
13513 if (ref_window == NULL)
13514 return false;
13515 if (flags & ImGuiFocusedFlags_AnyWindow)
13516 return true;
13517
13518 IM_ASSERT(cur_window); // Not inside a Begin()/End()
13519 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
13520 const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
13521 if (flags & ImGuiFocusedFlags_RootWindow)
13522 cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
13523
13524 if (flags & ImGuiFocusedFlags_ChildWindows)
13525 return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
13526 else
13527 return (ref_window == cur_window);
13528 }
13529
13530 static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13531 {
13532 ImGuiContext& g = *GImGui;
13533 IM_UNUSED(g);
13534 int order = window->FocusOrder;
13535 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13536 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13537 return order;
13538 }
13539
13540 static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
13541 {
13542 ImGuiContext& g = *GImGui;
13543
13544 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
13545 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
13546 if ((just_created || child_flag_changed) && !new_is_explicit_child)
13547 {
13548 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
13549 g.WindowsFocusOrder.push_back(window);
13550 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
13551 }
13552 else if (!just_created && child_flag_changed && new_is_explicit_child)
13553 {
13554 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
13555 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
13556 g.WindowsFocusOrder[n]->FocusOrder--;
13557 g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
13558 window->FocusOrder = -1;
13559 }
13560 window->IsExplicitChild = new_is_explicit_child;
13561 }
13562
13563 void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
13564 {
13565 ImGuiContext& g = *GImGui;
13566 IM_ASSERT(window == window->RootWindow);
13567
13568 const int cur_order = window->FocusOrder;
13569 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
13570 if (g.WindowsFocusOrder.back() == window)
13571 return;
13572
13573 const int new_order = g.WindowsFocusOrder.Size - 1;
13574 for (int n = cur_order; n < new_order; n++)
13575 {
13576 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
13577 g.WindowsFocusOrder[n]->FocusOrder--;
13578 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
13579 }
13580 g.WindowsFocusOrder[new_order] = window;
13581 window->FocusOrder = (short)new_order;
13582 }
13583
13584 // Note technically focus related but rather adjacent and close to BringWindowToFocusFront()
13585 void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
13586 {
13587 ImGuiContext& g = *GImGui;
13588 ImGuiWindow* current_front_window = g.Windows.back();
13589 if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
13590 return;
13591 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
13592 if (g.Windows[i] == window)
13593 {
13594 memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
13595 g.Windows[g.Windows.Size - 1] = window;
13596 break;
13597 }
13598 }
13599
13600 void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
13601 {
13602 ImGuiContext& g = *GImGui;
13603 if (g.Windows[0] == window)
13604 return;
13605 for (int i = 0; i < g.Windows.Size; i++)
13606 if (g.Windows[i] == window)
13607 {
13608 memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
13609 g.Windows[0] = window;
13610 break;
13611 }
13612 }
13613
13614 void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
13615 {
13616 IM_ASSERT(window != NULL && behind_window != NULL);
13617 ImGuiContext& g = *GImGui;
13618 window = window->RootWindow;
13619 behind_window = behind_window->RootWindow;
13620 int pos_wnd = FindWindowDisplayIndex(window);
13621 int pos_beh = FindWindowDisplayIndex(behind_window);
13622 if (pos_wnd < pos_beh)
13623 {
13624 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
13625 memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
13626 g.Windows[pos_beh - 1] = window;
13627 }
13628 else
13629 {
13630 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
13631 memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
13632 g.Windows[pos_beh] = window;
13633 }
13634 }
13635
13636 int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
13637 {
13638 ImGuiContext& g = *GImGui;
13639 return g.Windows.index_from_ptr(g.Windows.find(window));
13640 }
13641
13642 // Moving window to front of display and set focus (which happens to be back of our sorted list)
13643 void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
13644 {
13645 ImGuiContext& g = *GImGui;
13646
13647 // Modal check?
13648 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
13649 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
13650 {
13651 // This block would typically be reached in two situations:
13652 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
13653 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
13654 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
13655 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13656 BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
13657 ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
13658 return;
13659 }
13660
13661 // Find last focused child (if any) and focus it instead.
13662 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
13663 window = NavRestoreLastChildNavWindow(window);
13664
13665 // Apply focus
13666 if (g.NavWindow != window)
13667 {
13668 SetNavWindow(window);
13669 if (window && g.NavHighlightItemUnderNav)
13670 g.NavMousePosDirty = true;
13671 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
13672 g.NavLayer = ImGuiNavLayer_Main;
13673 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
13674 g.NavIdIsAlive = false;
13675 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13676
13677 // Close popups if any
13678 ClosePopupsOverWindow(window, false);
13679 }
13680
13681 // Move the root window to the top of the pile
13682 IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
13683 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
13684 ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
13685 ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
13686 bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
13687
13688 // Steal active widgets. Some of the cases it triggers includes:
13689 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
13690 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
13691 // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
13692 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
13693 if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
13694 ClearActiveID();
13695
13696 // Passing NULL allow to disable keyboard focus
13697 if (!window)
13698 return;
13699 window->LastFrameJustFocused = g.FrameCount;
13700
13701 // Select in dock node
13702 // For #2304 we avoid applying focus immediately before the tabbar is visible.
13703 //if (dock_node && dock_node->TabBar)
13704 // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
13705
13706 // Bring to front
13707 BringWindowToFocusFront(focus_front_window);
13708 if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13709 BringWindowToDisplayFront(display_front_window);
13710 }
13711
13712 void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
13713 {
13714 ImGuiContext& g = *GImGui;
13715 int start_idx = g.WindowsFocusOrder.Size - 1;
13716 if (under_this_window != NULL)
13717 {
13718 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
13719 int offset = -1;
13720 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
13721 {
13722 under_this_window = under_this_window->ParentWindow;
13723 offset = 0;
13724 }
13725 start_idx = FindWindowFocusIndex(under_this_window) + offset;
13726 }
13727 for (int i = start_idx; i >= 0; i--)
13728 {
13729 // 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.
13730 ImGuiWindow* window = g.WindowsFocusOrder[i];
13731 if (window == ignore_window || !window->WasActive)
13732 continue;
13733 if (filter_viewport != NULL && window->Viewport != filter_viewport)
13734 continue;
13735 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
13736 {
13737 // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
13738 // This is failing (lagging by one frame) for docked windows.
13739 // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
13740 // 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)
13741 // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
13742 FocusWindow(window, flags);
13743 return;
13744 }
13745 }
13746 FocusWindow(NULL, flags);
13747 }
13748
13749 //-----------------------------------------------------------------------------
13750 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
13751 //-----------------------------------------------------------------------------
13752
13753 // FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
13754 // In our terminology those should be interchangeable, yet right now this is super confusing.
13755 // Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
13756
13757 void ImGui::SetNavCursorVisible(bool visible)
13758 {
13759 ImGuiContext& g = *GImGui;
13760 if (g.IO.ConfigNavCursorVisibleAlways)
13761 visible = true;
13762 g.NavCursorVisible = visible;
13763 }
13764
13765 // (was called NavRestoreHighlightAfterMove() before 1.91.4)
13766 void ImGui::SetNavCursorVisibleAfterMove()
13767 {
13768 ImGuiContext& g = *GImGui;
13769 if (g.IO.ConfigNavCursorVisibleAuto)
13770 g.NavCursorVisible = true;
13771 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
13772 }
13773
13774 void ImGui::SetNavWindow(ImGuiWindow* window)
13775 {
13776 ImGuiContext& g = *GImGui;
13777 if (g.NavWindow != window)
13778 {
13779 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
13780 g.NavWindow = window;
13781 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13782 }
13783 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13784 NavUpdateAnyRequestFlag();
13785 }
13786
13787 void ImGui::NavHighlightActivated(ImGuiID id)
13788 {
13789 ImGuiContext& g = *GImGui;
13790 g.NavHighlightActivatedId = id;
13791 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
13792 }
13793
13794 void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
13795 {
13796 ImGuiContext& g = *GImGui;
13797 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
13798 }
13799
13800 void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
13801 {
13802 ImGuiContext& g = *GImGui;
13803 IM_ASSERT(g.NavWindow != NULL);
13804 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
13805 g.NavId = id;
13806 g.NavLayer = nav_layer;
13807 SetNavFocusScope(focus_scope_id);
13808 g.NavWindow->NavLastIds[nav_layer] = id;
13809 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
13810
13811 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13812 NavClearPreferredPosForAxis(ImGuiAxis_X);
13813 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13814 }
13815
13816 void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
13817 {
13818 ImGuiContext& g = *GImGui;
13819 IM_ASSERT(id != 0);
13820
13821 if (g.NavWindow != window)
13822 SetNavWindow(window);
13823
13824 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
13825 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
13826 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
13827 g.NavId = id;
13828 g.NavLayer = nav_layer;
13829 SetNavFocusScope(g.CurrentFocusScopeId);
13830 window->NavLastIds[nav_layer] = id;
13831 if (g.LastItemData.ID == id)
13832 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
13833
13834 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
13835 g.NavHighlightItemUnderNav = true;
13836 else if (g.IO.ConfigNavCursorVisibleAuto)
13837 g.NavCursorVisible = false;
13838
13839 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13840 NavClearPreferredPosForAxis(ImGuiAxis_X);
13841 NavClearPreferredPosForAxis(ImGuiAxis_Y);
13842 }
13843
13844 static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
13845 {
13846 if (ImFabs(dx) > ImFabs(dy))
13847 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
13848 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
13849 }
13850
13851 static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
13852 {
13853 if (cand_max < curr_min)
13854 return cand_max - curr_min;
13855 if (curr_max < cand_min)
13856 return cand_min - curr_max;
13857 return 0.0f;
13858 }
13859
13860 // Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
13861 static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb)
13862 {
13863 ImGuiContext& g = *GImGui;
13864 ImGuiWindow* window = g.CurrentWindow;
13865 if (g.NavLayer != window->DC.NavLayerCurrent)
13866 return false;
13867
13868 // FIXME: Those are not good variables names
13869 ImRect cand = nav_bb; // Current item nav rectangle
13870 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)
13871 g.NavScoringDebugCount++;
13872
13873 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
13874 if (window->ParentWindow == g.NavWindow)
13875 {
13876 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
13877 if (!window->ClipRect.Overlaps(cand))
13878 return false;
13879 cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
13880 }
13881
13882 // Compute distance between boxes
13883 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
13884 float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
13885 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
13886 if (dby != 0.0f && dbx != 0.0f)
13887 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
13888 float dist_box = ImFabs(dbx) + ImFabs(dby);
13889
13890 // 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)
13891 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
13892 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
13893 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
13894
13895 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
13896 ImGuiDir quadrant;
13897 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
13898 if (dbx != 0.0f || dby != 0.0f)
13899 {
13900 // For non-overlapping boxes, use distance between boxes
13901 // 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
13902 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
13903 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
13904 dax = dbx;
13905 day = dby;
13906 dist_axial = dist_box;
13907 quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
13908 }
13909 else if (dcx != 0.0f || dcy != 0.0f)
13910 {
13911 // For overlapping boxes with different centers, use distance between centers
13912 dax = dcx;
13913 day = dcy;
13914 dist_axial = dist_center;
13915 quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
13916 }
13917 else
13918 {
13919 // 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)
13920 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
13921 }
13922
13923 const ImGuiDir move_dir = g.NavMoveDir;
13924 #if IMGUI_DEBUG_NAV_SCORING
13925 char buf[200];
13926 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
13927 {
13928 if (quadrant == move_dir)
13929 {
13930 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
13931 ImDrawList* draw_list = GetForegroundDrawList(window);
13932 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
13933 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
13934 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
13935 }
13936 }
13937 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
13938 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
13939 if (debug_hovering || debug_tty)
13940 {
13941 ImFormatString(buf, IM_ARRAYSIZE(buf),
13942 "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",
13943 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
13944 if (debug_hovering)
13945 {
13946 ImDrawList* draw_list = GetForegroundDrawList(window);
13947 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
13948 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
13949 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
13950 draw_list->AddText(cand.Max, ~0U, buf);
13951 }
13952 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
13953 }
13954 #endif
13955
13956 // Is it in the quadrant we're interested in moving to?
13957 bool new_best = false;
13958 if (quadrant == move_dir)
13959 {
13960 // Does it beat the current best candidate?
13961 if (dist_box < result->DistBox)
13962 {
13963 result->DistBox = dist_box;
13964 result->DistCenter = dist_center;
13965 return true;
13966 }
13967 if (dist_box == result->DistBox)
13968 {
13969 // Try using distance between center points to break ties
13970 if (dist_center < result->DistCenter)
13971 {
13972 result->DistCenter = dist_center;
13973 new_best = true;
13974 }
13975 else if (dist_center == result->DistCenter)
13976 {
13977 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
13978 // (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),
13979 // 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.
13980 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
13981 new_best = true;
13982 }
13983 }
13984 }
13985
13986 // 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
13987 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
13988 // 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.
13989 // 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.
13990 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
13991 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
13992 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
13993 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))
13994 {
13995 result->DistAxial = dist_axial;
13996 new_best = true;
13997 }
13998
13999 return new_best;
14000 }
14001
14002 static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
14003 {
14004 ImGuiContext& g = *GImGui;
14005 ImGuiWindow* window = g.CurrentWindow;
14006 result->Window = window;
14007 result->ID = g.LastItemData.ID;
14008 result->FocusScopeId = g.CurrentFocusScopeId;
14009 result->ItemFlags = g.LastItemData.ItemFlags;
14010 result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
14011 if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
14012 {
14013 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
14014 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
14015 }
14016 }
14017
14018 // True when current work location may be scrolled horizontally when moving left / right.
14019 // This is generally always true UNLESS within a column. We don't have a vertical equivalent.
14020 void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
14021 {
14022 ImGuiContext& g = *GImGui;
14023 ImGuiWindow* window = g.CurrentWindow;
14024 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
14025 }
14026
14027 // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
14028 // This is called after LastItemData is set, but NextItemData is also still valid.
14029 static void ImGui::NavProcessItem()
14030 {
14031 ImGuiContext& g = *GImGui;
14032 ImGuiWindow* window = g.CurrentWindow;
14033 const ImGuiID id = g.LastItemData.ID;
14034 const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
14035
14036 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816)
14037 ImRect nav_bb = g.LastItemData.NavRect;
14038 if (window->DC.NavIsScrollPushableX == false)
14039 {
14040 nav_bb.Min.x = ImClamp(nav_bb.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
14041 nav_bb.Max.x = ImClamp(nav_bb.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
14042 }
14043
14044 // Process Init Request
14045 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
14046 {
14047 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
14048 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
14049 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
14050 {
14051 NavApplyItemToResult(&g.NavInitResult);
14052 }
14053 if (candidate_for_nav_default_focus)
14054 {
14055 g.NavInitRequest = false; // Found a match, clear request
14056 NavUpdateAnyRequestFlag();
14057 }
14058 }
14059
14060 // Process Move Request (scoring for navigation)
14061 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
14062 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
14063 {
14064 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
14065 {
14066 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
14067 if (is_tabbing)
14068 {
14069 NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
14070 }
14071 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
14072 {
14073 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
14074 if (NavScoreItem(result, nav_bb))
14075 NavApplyItemToResult(result);
14076
14077 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
14078 const float VISIBLE_RATIO = 0.70f;
14079 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
14080 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)
14081 if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb))
14082 NavApplyItemToResult(&g.NavMoveResultLocalVisible);
14083 }
14084 }
14085 }
14086
14087 // Update information for currently focused/navigated item
14088 if (g.NavId == id)
14089 {
14090 if (g.NavWindow != window)
14091 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
14092 g.NavLayer = window->DC.NavLayerCurrent;
14093 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
14094 g.NavFocusScopeId = g.CurrentFocusScopeId;
14095 g.NavIdIsAlive = true;
14096 if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
14097 {
14098 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
14099 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
14100 }
14101 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
14102 }
14103 }
14104
14105 // Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
14106 // Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
14107 // - Case 1: no nav/active id: set result to first eligible item, stop storing.
14108 // - Case 2: tab forward: on ref id set counter, on counter elapse store result
14109 // - 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
14110 // - Case 4: tab backward: store all results, on ref id pick prev, stop storing
14111 // - 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
14112 void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
14113 {
14114 ImGuiContext& g = *GImGui;
14115
14116 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
14117 {
14118 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
14119 return;
14120 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
14121 return;
14122 }
14123
14124 // - Can always land on an item when using API call.
14125 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
14126 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
14127 bool can_stop;
14128 if (move_flags & ImGuiNavMoveFlags_FocusApi)
14129 can_stop = true;
14130 else
14131 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
14132
14133 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
14134 ImGuiNavItemData* result = &g.NavMoveResultLocal;
14135 if (g.NavTabbingDir == +1)
14136 {
14137 // Tab Forward or SetKeyboardFocusHere() with >= 0
14138 if (can_stop && g.NavTabbingResultFirst.ID == 0)
14139 NavApplyItemToResult(&g.NavTabbingResultFirst);
14140 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
14141 NavMoveRequestResolveWithLastItem(result);
14142 else if (g.NavId == id)
14143 g.NavTabbingCounter = 1;
14144 }
14145 else if (g.NavTabbingDir == -1)
14146 {
14147 // Tab Backward
14148 if (g.NavId == id)
14149 {
14150 if (result->ID)
14151 {
14152 g.NavMoveScoringItems = false;
14153 NavUpdateAnyRequestFlag();
14154 }
14155 }
14156 else if (can_stop)
14157 {
14158 // Keep applying until reaching NavId
14159 NavApplyItemToResult(result);
14160 }
14161 }
14162 else if (g.NavTabbingDir == 0)
14163 {
14164 if (can_stop && g.NavId == id)
14165 NavMoveRequestResolveWithLastItem(result);
14166 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
14167 NavApplyItemToResult(&g.NavTabbingResultFirst);
14168 }
14169 }
14170
14171 bool ImGui::NavMoveRequestButNoResultYet()
14172 {
14173 ImGuiContext& g = *GImGui;
14174 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
14175 }
14176
14177 // FIXME: ScoringRect is not set
14178 void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
14179 {
14180 ImGuiContext& g = *GImGui;
14181 IM_ASSERT(g.NavWindow != NULL);
14182 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
14183
14184 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
14185 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
14186
14187 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
14188 g.NavMoveDir = move_dir;
14189 g.NavMoveDirForDebug = move_dir;
14190 g.NavMoveClipDir = clip_dir;
14191 g.NavMoveFlags = move_flags;
14192 g.NavMoveScrollFlags = scroll_flags;
14193 g.NavMoveForwardToNextFrame = false;
14194 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
14195 g.NavMoveResultLocal.Clear();
14196 g.NavMoveResultLocalVisible.Clear();
14197 g.NavMoveResultOther.Clear();
14198 g.NavTabbingCounter = 0;
14199 g.NavTabbingResultFirst.Clear();
14200 NavUpdateAnyRequestFlag();
14201 }
14202
14203 void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
14204 {
14205 ImGuiContext& g = *GImGui;
14206 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
14207 NavApplyItemToResult(result);
14208 NavUpdateAnyRequestFlag();
14209 }
14210
14211 // Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent
14212 void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data)
14213 {
14214 ImGuiContext& g = *GImGui;
14215 g.NavMoveScoringItems = false;
14216 g.LastItemData.ID = tree_node_data->ID;
14217 g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
14218 g.LastItemData.NavRect = tree_node_data->NavRect;
14219 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
14220 NavClearPreferredPosForAxis(ImGuiAxis_Y);
14221 NavUpdateAnyRequestFlag();
14222 }
14223
14224 void ImGui::NavMoveRequestCancel()
14225 {
14226 ImGuiContext& g = *GImGui;
14227 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
14228 NavUpdateAnyRequestFlag();
14229 }
14230
14231 // Forward will reuse the move request again on the next frame (generally with modifications done to it)
14232 void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
14233 {
14234 ImGuiContext& g = *GImGui;
14235 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
14236 NavMoveRequestCancel();
14237 g.NavMoveForwardToNextFrame = true;
14238 g.NavMoveDir = move_dir;
14239 g.NavMoveClipDir = clip_dir;
14240 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
14241 g.NavMoveScrollFlags = scroll_flags;
14242 }
14243
14244 // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
14245 // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
14246 void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
14247 {
14248 ImGuiContext& g = *GImGui;
14249 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
14250
14251 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
14252 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
14253 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
14254 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
14255 }
14256
14257 // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
14258 // This way we could find the last focused window among our children. It would be much less confusing this way?
14259 static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
14260 {
14261 ImGuiWindow* parent = nav_window;
14262 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
14263 parent = parent->ParentWindow;
14264 if (parent && parent != nav_window)
14265 parent->NavLastChildNavWindow = nav_window;
14266 }
14267
14268 // Restore the last focused child.
14269 // Call when we are expected to land on the Main Layer (0) after FocusWindow()
14270 static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
14271 {
14272 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
14273 return window->NavLastChildNavWindow;
14274 if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
14275 if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
14276 return tab->Window;
14277 return window;
14278 }
14279
14280 void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
14281 {
14282 ImGuiContext& g = *GImGui;
14283 if (layer == ImGuiNavLayer_Main)
14284 {
14285 ImGuiWindow* prev_nav_window = g.NavWindow;
14286 g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
14287 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14288 if (prev_nav_window)
14289 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
14290 }
14291 ImGuiWindow* window = g.NavWindow;
14292 if (window->NavLastIds[layer] != 0)
14293 {
14294 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
14295 }
14296 else
14297 {
14298 g.NavLayer = layer;
14299 NavInitWindow(window, true);
14300 }
14301 }
14302
14303 static inline void ImGui::NavUpdateAnyRequestFlag()
14304 {
14305 ImGuiContext& g = *GImGui;
14306 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
14307 if (g.NavAnyRequest)
14308 IM_ASSERT(g.NavWindow != NULL);
14309 }
14310
14311 // This needs to be called before we submit any widget (aka in or before Begin)
14312 void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
14313 {
14314 // FIXME: ChildWindow test here is wrong for docking
14315 ImGuiContext& g = *GImGui;
14316 IM_ASSERT(window == g.NavWindow);
14317
14318 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
14319 {
14320 g.NavId = 0;
14321 SetNavFocusScope(window->NavRootFocusScopeId);
14322 return;
14323 }
14324
14325 bool init_for_nav = false;
14326 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
14327 init_for_nav = true;
14328 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
14329 if (init_for_nav)
14330 {
14331 SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
14332 g.NavInitRequest = true;
14333 g.NavInitRequestFromMove = false;
14334 g.NavInitResult.ID = 0;
14335 NavUpdateAnyRequestFlag();
14336 }
14337 else
14338 {
14339 g.NavId = window->NavLastIds[0];
14340 SetNavFocusScope(window->NavRootFocusScopeId);
14341 }
14342 }
14343
14344 static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
14345 {
14346 ImGuiContext& g = *GImGui;
14347 ImGuiWindow* window = g.NavWindow;
14348 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14349
14350 // 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.
14351 if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut)
14352 return ImGuiInputSource_Mouse;
14353 else
14354 return ImGuiInputSource_Keyboard; // or Nav in general
14355 }
14356
14357 static ImVec2 ImGui::NavCalcPreferredRefPos()
14358 {
14359 ImGuiContext& g = *GImGui;
14360 ImGuiWindow* window = g.NavWindow;
14361 ImGuiInputSource source = NavCalcPreferredRefPosSource();
14362
14363 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14364
14365 // 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.
14366 if (source == ImGuiInputSource_Mouse)
14367 {
14368 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
14369 // 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.
14370 // In theory we could move that +1.0f offset in OpenPopupEx()
14371 ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
14372 return ImVec2(p.x + 1.0f, p.y);
14373 }
14374 else
14375 {
14376 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
14377 ImRect ref_rect;
14378 if (activated_shortcut)
14379 ref_rect = g.LastItemData.NavRect;
14380 else
14381 ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
14382
14383 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
14384 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
14385 {
14386 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
14387 ref_rect.Translate(window->Scroll - next_scroll);
14388 }
14389 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()));
14390 ImGuiViewport* viewport = window->Viewport;
14391 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.
14392 }
14393 }
14394
14395 float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
14396 {
14397 ImGuiContext& g = *GImGui;
14398 float repeat_delay, repeat_rate;
14399 GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
14400
14401 ImGuiKey key_less, key_more;
14402 if (g.NavInputSource == ImGuiInputSource_Gamepad)
14403 {
14404 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
14405 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
14406 }
14407 else
14408 {
14409 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
14410 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
14411 }
14412 float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
14413 if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
14414 amount = 0.0f;
14415 return amount;
14416 }
14417
14418 static void ImGui::NavUpdate()
14419 {
14420 ImGuiContext& g = *GImGui;
14421 ImGuiIO& io = g.IO;
14422
14423 io.WantSetMousePos = false;
14424 //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);
14425
14426 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
14427 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
14428 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14429 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
14430 if (nav_gamepad_active)
14431 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
14432 if (IsKeyDown(key))
14433 g.NavInputSource = ImGuiInputSource_Gamepad;
14434 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14435 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
14436 if (nav_keyboard_active)
14437 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
14438 if (IsKeyDown(key))
14439 g.NavInputSource = ImGuiInputSource_Keyboard;
14440
14441 // Process navigation init request (select first/default focus)
14442 g.NavJustMovedToId = 0;
14443 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
14444 if (g.NavInitResult.ID != 0)
14445 NavInitRequestApplyResult();
14446 g.NavInitRequest = false;
14447 g.NavInitRequestFromMove = false;
14448 g.NavInitResult.ID = 0;
14449
14450 // Process navigation move request
14451 if (g.NavMoveSubmitted)
14452 NavMoveRequestApplyResult();
14453 g.NavTabbingCounter = 0;
14454 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
14455 if (g.NavCursorHideFrames > 0)
14456 if (--g.NavCursorHideFrames == 0)
14457 g.NavCursorVisible = true;
14458
14459 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
14460 bool set_mouse_pos = false;
14461 if (g.NavMousePosDirty && g.NavIdIsAlive)
14462 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
14463 set_mouse_pos = true;
14464 g.NavMousePosDirty = false;
14465 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
14466
14467 // 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
14468 if (g.NavWindow)
14469 NavSaveLastChildNavWindowIntoParent(g.NavWindow);
14470 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
14471 g.NavWindow->NavLastChildNavWindow = NULL;
14472
14473 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
14474 NavUpdateWindowing();
14475
14476 // Set output flags for user application
14477 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
14478 io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
14479
14480 // Process NavCancel input (to close a popup, get back to parent, clear focus)
14481 NavUpdateCancelRequest();
14482
14483 // Process manual activation request
14484 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
14485 g.NavActivateFlags = ImGuiActivateFlags_None;
14486 if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14487 {
14488 const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
14489 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
14490 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));
14491 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)));
14492 if (g.ActiveId == 0 && activate_pressed)
14493 {
14494 g.NavActivateId = g.NavId;
14495 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
14496 }
14497 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
14498 {
14499 g.NavActivateId = g.NavId;
14500 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
14501 }
14502 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
14503 g.NavActivateDownId = g.NavId;
14504 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
14505 {
14506 g.NavActivatePressedId = g.NavId;
14507 NavHighlightActivated(g.NavId);
14508 }
14509 }
14510 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14511 g.NavCursorVisible = false;
14512 else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
14513 g.NavCursorVisible = true;
14514 if (g.NavActivateId != 0)
14515 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
14516
14517 // Highlight
14518 if (g.NavHighlightActivatedTimer > 0.0f)
14519 g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
14520 if (g.NavHighlightActivatedTimer == 0.0f)
14521 g.NavHighlightActivatedId = 0;
14522
14523 // Process programmatic activation request
14524 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
14525 if (g.NavNextActivateId != 0)
14526 {
14527 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
14528 g.NavActivateFlags = g.NavNextActivateFlags;
14529 }
14530 g.NavNextActivateId = 0;
14531
14532 // Process move requests
14533 NavUpdateCreateMoveRequest();
14534 if (g.NavMoveDir == ImGuiDir_None)
14535 NavUpdateCreateTabbingRequest();
14536 NavUpdateAnyRequestFlag();
14537 g.NavIdIsAlive = false;
14538
14539 // Scrolling
14540 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
14541 {
14542 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
14543 ImGuiWindow* window = g.NavWindow;
14544 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.
14545 const ImGuiDir move_dir = g.NavMoveDir;
14546 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
14547 {
14548 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
14549 SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
14550 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
14551 SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
14552 }
14553
14554 // *Normal* Manual scroll with LStick
14555 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
14556 if (nav_gamepad_active)
14557 {
14558 const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
14559 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
14560 if (scroll_dir.x != 0.0f && window->ScrollbarX)
14561 SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
14562 if (scroll_dir.y != 0.0f)
14563 SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
14564 }
14565 }
14566
14567 // Always prioritize mouse highlight if navigation is disabled
14568 if (!nav_keyboard_active && !nav_gamepad_active)
14569 {
14570 g.NavCursorVisible = false;
14571 g.NavHighlightItemUnderNav = set_mouse_pos = false;
14572 }
14573
14574 // Update mouse position if requested
14575 // (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)
14576 if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
14577 TeleportMousePos(NavCalcPreferredRefPos());
14578
14579 // [DEBUG]
14580 g.NavScoringDebugCount = 0;
14581 #if IMGUI_DEBUG_NAV_RECTS
14582 if (ImGuiWindow* debug_window = g.NavWindow)
14583 {
14584 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
14585 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)); }
14586 //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); }
14587 }
14588 #endif
14589 }
14590
14591 void ImGui::NavInitRequestApplyResult()
14592 {
14593 // 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)
14594 ImGuiContext& g = *GImGui;
14595 if (!g.NavWindow)
14596 return;
14597
14598 ImGuiNavItemData* result = &g.NavInitResult;
14599 if (g.NavId != result->ID)
14600 {
14601 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14602 g.NavJustMovedToId = result->ID;
14603 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14604 g.NavJustMovedToKeyMods = 0;
14605 g.NavJustMovedToIsTabbing = false;
14606 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14607 }
14608
14609 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
14610 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
14611 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14612 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
14613 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
14614 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14615 g.NavLastValidSelectionUserData = result->SelectionUserData;
14616 if (g.NavInitRequestFromMove)
14617 SetNavCursorVisibleAfterMove();
14618 }
14619
14620 // Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
14621 static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
14622 {
14623 // Bias initial rect
14624 ImGuiContext& g = *GImGui;
14625 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
14626
14627 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
14628 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
14629 // - But each successful move sets new bias on one axis, only cleared when using mouse.
14630 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
14631 {
14632 if (preferred_pos_rel.x == FLT_MAX)
14633 preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
14634 if (preferred_pos_rel.y == FLT_MAX)
14635 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
14636 }
14637
14638 // Apply general bias on the other axis
14639 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
14640 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
14641 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
14642 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
14643 }
14644
14645 void ImGui::NavUpdateCreateMoveRequest()
14646 {
14647 ImGuiContext& g = *GImGui;
14648 ImGuiIO& io = g.IO;
14649 ImGuiWindow* window = g.NavWindow;
14650 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14651 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14652
14653 if (g.NavMoveForwardToNextFrame && window != NULL)
14654 {
14655 // 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)
14656 // (preserve most state, which were already set by the NavMoveRequestForward() function)
14657 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
14658 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
14659 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
14660 }
14661 else
14662 {
14663 // Initiate directional inputs request
14664 g.NavMoveDir = ImGuiDir_None;
14665 g.NavMoveFlags = ImGuiNavMoveFlags_None;
14666 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
14667 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
14668 {
14669 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
14670 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; }
14671 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; }
14672 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; }
14673 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; }
14674 }
14675 g.NavMoveClipDir = g.NavMoveDir;
14676 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14677 }
14678
14679 // Update PageUp/PageDown/Home/End scroll
14680 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
14681 float scoring_rect_offset_y = 0.0f;
14682 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
14683 scoring_rect_offset_y = NavUpdatePageUpPageDown();
14684 if (scoring_rect_offset_y != 0.0f)
14685 {
14686 g.NavScoringNoClipRect = window->InnerRect;
14687 g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
14688 }
14689
14690 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
14691 #if IMGUI_DEBUG_NAV_SCORING
14692 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
14693 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
14694 if (io.KeyCtrl)
14695 {
14696 if (g.NavMoveDir == ImGuiDir_None)
14697 g.NavMoveDir = g.NavMoveDirForDebug;
14698 g.NavMoveClipDir = g.NavMoveDir;
14699 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
14700 }
14701 #endif
14702
14703 // Submit
14704 g.NavMoveForwardToNextFrame = false;
14705 if (g.NavMoveDir != ImGuiDir_None)
14706 NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
14707
14708 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
14709 if (g.NavMoveSubmitted && g.NavId == 0)
14710 {
14711 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
14712 g.NavInitRequest = g.NavInitRequestFromMove = true;
14713 g.NavInitResult.ID = 0;
14714 if (g.IO.ConfigNavCursorVisibleAuto)
14715 g.NavCursorVisible = true;
14716 }
14717
14718 // When using gamepad, we project the reference nav bounding box into window visible area.
14719 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
14720 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
14721 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
14722 {
14723 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
14724 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
14725 ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
14726
14727 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
14728 // Otherwise 'inner_rect_rel' would be off on the move result frame.
14729 inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
14730
14731 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
14732 {
14733 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
14734 float pad_x = ImMin(inner_rect_rel.GetWidth(), window->FontRefSize * 0.5f);
14735 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
14736 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
14737 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
14738 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
14739 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
14740 window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
14741 g.NavId = 0;
14742 }
14743 }
14744
14745 // Prepare scoring rectangle.
14746 // 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)
14747 ImRect scoring_rect;
14748 if (window != NULL)
14749 {
14750 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
14751 scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
14752 scoring_rect.TranslateY(scoring_rect_offset_y);
14753 if (g.NavMoveSubmitted)
14754 NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
14755 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
14756 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
14757 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
14758 }
14759 g.NavScoringRect = scoring_rect;
14760 //g.NavScoringNoClipRect.Add(scoring_rect);
14761 }
14762
14763 void ImGui::NavUpdateCreateTabbingRequest()
14764 {
14765 ImGuiContext& g = *GImGui;
14766 ImGuiWindow* window = g.NavWindow;
14767 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
14768 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
14769 return;
14770
14771 const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
14772 if (!tab_pressed)
14773 return;
14774
14775 // Initiate tabbing request
14776 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
14777 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
14778 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14779 if (nav_keyboard_active)
14780 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
14781 else
14782 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
14783 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
14784 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
14785 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
14786 NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
14787 g.NavTabbingCounter = -1;
14788 }
14789
14790 // Apply result from previous frame navigation directional move request. Always called from NavUpdate()
14791 void ImGui::NavMoveRequestApplyResult()
14792 {
14793 ImGuiContext& g = *GImGui;
14794 #if IMGUI_DEBUG_NAV_SCORING
14795 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
14796 return;
14797 #endif
14798
14799 // Select which result to use
14800 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
14801
14802 // Tabbing forward wrap
14803 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
14804 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
14805 result = &g.NavTabbingResultFirst;
14806
14807 // 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)
14808 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14809 if (result == NULL)
14810 {
14811 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14812 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
14813 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14814 SetNavCursorVisibleAfterMove();
14815 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
14816 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
14817 return;
14818 }
14819
14820 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
14821 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
14822 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
14823 result = &g.NavMoveResultLocalVisible;
14824
14825 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
14826 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
14827 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
14828 result = &g.NavMoveResultOther;
14829 IM_ASSERT(g.NavWindow && result->Window);
14830
14831 // Scroll to keep newly navigated item fully into view.
14832 if (g.NavLayer == ImGuiNavLayer_Main)
14833 {
14834 ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
14835 ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
14836
14837 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
14838 {
14839 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
14840 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
14841 SetScrollY(result->Window, scroll_target);
14842 }
14843 }
14844
14845 if (g.NavWindow != result->Window)
14846 {
14847 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
14848 g.NavWindow = result->Window;
14849 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14850 }
14851
14852 // Clear active id unless requested not to
14853 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
14854 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
14855 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
14856 ClearActiveID();
14857
14858 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
14859 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
14860 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
14861 {
14862 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14863 g.NavJustMovedToId = result->ID;
14864 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14865 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
14866 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
14867 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14868 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
14869 }
14870
14871 // Apply new NavID/Focus
14872 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14873 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
14874 SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
14875 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14876 g.NavLastValidSelectionUserData = result->SelectionUserData;
14877
14878 // Restore last preferred position for current axis
14879 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
14880 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
14881 {
14882 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
14883 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
14884 }
14885
14886 // Tabbing: Activates Inputable, otherwise only Focus
14887 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
14888 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
14889
14890 // Activate
14891 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
14892 {
14893 g.NavNextActivateId = result->ID;
14894 g.NavNextActivateFlags = ImGuiActivateFlags_None;
14895 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14896 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
14897 }
14898
14899 // Make nav cursor visible
14900 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14901 SetNavCursorVisibleAfterMove();
14902 }
14903
14904 // Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
14905 // FIXME: In order to support e.g. Escape to clear a selection we'll need:
14906 // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
14907 // - 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
14908 static void ImGui::NavUpdateCancelRequest()
14909 {
14910 ImGuiContext& g = *GImGui;
14911 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14912 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14913 if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
14914 return;
14915
14916 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
14917 if (g.ActiveId != 0)
14918 {
14919 ClearActiveID();
14920 }
14921 else if (g.NavLayer != ImGuiNavLayer_Main)
14922 {
14923 // Leave the "menu" layer
14924 NavRestoreLayer(ImGuiNavLayer_Main);
14925 SetNavCursorVisibleAfterMove();
14926 }
14927 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
14928 {
14929 // Exit child window
14930 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
14931 ImGuiWindow* parent_window = child_window->ParentWindow;
14932 IM_ASSERT(child_window->ChildId != 0);
14933 FocusWindow(parent_window);
14934 SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
14935 SetNavCursorVisibleAfterMove();
14936 }
14937 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
14938 {
14939 // Close open popup/menu
14940 ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
14941 }
14942 else
14943 {
14944 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
14945 // FIXME-NAV: This should happen on window appearing.
14946 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14947 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
14948 g.NavWindow->NavLastIds[0] = 0;
14949
14950 // Clear nav focus
14951 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14952 g.NavId = 0;
14953 if (g.IO.ConfigNavEscapeClearFocusWindow)
14954 FocusWindow(NULL);
14955 }
14956 }
14957
14958 // Handle PageUp/PageDown/Home/End keys
14959 // Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
14960 // FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
14961 // FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
14962 static float ImGui::NavUpdatePageUpPageDown()
14963 {
14964 ImGuiContext& g = *GImGui;
14965 ImGuiWindow* window = g.NavWindow;
14966 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
14967 return 0.0f;
14968
14969 const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
14970 const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
14971 const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14972 const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14973 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
14974 return 0.0f;
14975
14976 if (g.NavLayer != ImGuiNavLayer_Main)
14977 NavRestoreLayer(ImGuiNavLayer_Main);
14978
14979 if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY)
14980 {
14981 // Fallback manual-scroll when window has no navigable item
14982 if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14983 SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
14984 else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14985 SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
14986 else if (home_pressed)
14987 SetScrollY(window, 0.0f);
14988 else if (end_pressed)
14989 SetScrollY(window, window->ScrollMax.y);
14990 }
14991 else
14992 {
14993 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
14994 const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight());
14995 float nav_scoring_rect_offset_y = 0.0f;
14996 if (IsKeyPressed(ImGuiKey_PageUp, true))
14997 {
14998 nav_scoring_rect_offset_y = -page_offset_y;
14999 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)
15000 g.NavMoveClipDir = ImGuiDir_Up;
15001 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
15002 }
15003 else if (IsKeyPressed(ImGuiKey_PageDown, true))
15004 {
15005 nav_scoring_rect_offset_y = +page_offset_y;
15006 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)
15007 g.NavMoveClipDir = ImGuiDir_Down;
15008 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
15009 }
15010 else if (home_pressed)
15011 {
15012 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
15013 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
15014 // Preserve current horizontal position if we have any.
15015 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
15016 if (nav_rect_rel.IsInverted())
15017 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
15018 g.NavMoveDir = ImGuiDir_Down;
15019 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
15020 // FIXME-NAV: MoveClipDir left to _None, intentional?
15021 }
15022 else if (end_pressed)
15023 {
15024 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
15025 if (nav_rect_rel.IsInverted())
15026 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
15027 g.NavMoveDir = ImGuiDir_Up;
15028 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
15029 // FIXME-NAV: MoveClipDir left to _None, intentional?
15030 }
15031 return nav_scoring_rect_offset_y;
15032 }
15033 return 0.0f;
15034 }
15035
15036 static void ImGui::NavEndFrame()
15037 {
15038 ImGuiContext& g = *GImGui;
15039
15040 // Show CTRL+TAB list window
15041 if (g.NavWindowingTarget != NULL)
15042 NavUpdateWindowingOverlay();
15043
15044 // Perform wrap-around in menus
15045 // 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.
15046 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
15047 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
15048 NavUpdateCreateWrappingRequest();
15049 }
15050
15051 static void ImGui::NavUpdateCreateWrappingRequest()
15052 {
15053 ImGuiContext& g = *GImGui;
15054 ImGuiWindow* window = g.NavWindow;
15055
15056 bool do_forward = false;
15057 ImRect bb_rel = window->NavRectRel[g.NavLayer];
15058 ImGuiDir clip_dir = g.NavMoveDir;
15059
15060 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
15061 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
15062 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
15063 {
15064 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
15065 if (move_flags & ImGuiNavMoveFlags_WrapX)
15066 {
15067 bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
15068 clip_dir = ImGuiDir_Up;
15069 }
15070 do_forward = true;
15071 }
15072 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
15073 {
15074 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
15075 if (move_flags & ImGuiNavMoveFlags_WrapX)
15076 {
15077 bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
15078 clip_dir = ImGuiDir_Down;
15079 }
15080 do_forward = true;
15081 }
15082 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
15083 {
15084 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
15085 if (move_flags & ImGuiNavMoveFlags_WrapY)
15086 {
15087 bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
15088 clip_dir = ImGuiDir_Left;
15089 }
15090 do_forward = true;
15091 }
15092 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
15093 {
15094 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
15095 if (move_flags & ImGuiNavMoveFlags_WrapY)
15096 {
15097 bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
15098 clip_dir = ImGuiDir_Right;
15099 }
15100 do_forward = true;
15101 }
15102 if (!do_forward)
15103 return;
15104 window->NavRectRel[g.NavLayer] = bb_rel;
15105 NavClearPreferredPosForAxis(ImGuiAxis_X);
15106 NavClearPreferredPosForAxis(ImGuiAxis_Y);
15107 NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
15108 }
15109
15110 // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
15111 // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
15112 // If you want a window to never be focused, you may use the e.g. NoInputs flag.
15113 bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
15114 {
15115 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
15116 }
15117
15118 static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
15119 {
15120 ImGuiContext& g = *GImGui;
15121 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
15122 if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
15123 return g.WindowsFocusOrder[i];
15124 return NULL;
15125 }
15126
15127 static void NavUpdateWindowingTarget(int focus_change_dir)
15128 {
15129 ImGuiContext& g = *GImGui;
15130 IM_ASSERT(g.NavWindowingTarget);
15131 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
15132 return;
15133
15134 const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
15135 ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
15136 if (!window_target)
15137 window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
15138 if (window_target) // Don't reset windowing target if there's a single window in the list
15139 {
15140 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
15141 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
15142 }
15143 g.NavWindowingToggleLayer = false;
15144 }
15145
15146 // Apply focus and close overlay
15147 static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window)
15148 {
15149 // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ?
15150 // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
15151 ImGuiContext& g = *GImGui;
15152 if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)
15153 {
15154 ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
15155 ClearActiveID();
15156 SetNavCursorVisibleAfterMove();
15157 ClosePopupsOverWindow(apply_focus_window, false);
15158 FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
15159 IM_ASSERT(g.NavWindow != NULL);
15160 apply_focus_window = g.NavWindow;
15161 if (apply_focus_window->NavLastIds[0] == 0)
15162 NavInitWindow(apply_focus_window, false);
15163
15164 // If the window has ONLY a menu layer (no main layer), select it directly
15165 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
15166 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
15167 // the target window as already been previewed once.
15168 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
15169 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
15170 // won't be valid.
15171 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
15172 g.NavLayer = ImGuiNavLayer_Menu;
15173
15174 // Request OS level focus
15175 if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
15176 g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
15177 }
15178 g.NavWindowingTarget = NULL;
15179 }
15180
15181 // Windowing management mode
15182 // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
15183 // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
15184 static void ImGui::NavUpdateWindowing()
15185 {
15186 ImGuiContext& g = *GImGui;
15187 ImGuiIO& io = g.IO;
15188
15189 ImGuiWindow* apply_focus_window = NULL;
15190 bool apply_toggle_layer = false;
15191
15192 ImGuiWindow* modal_window = GetTopMostPopupModal();
15193 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.
15194 if (!allow_windowing)
15195 g.NavWindowingTarget = NULL;
15196
15197 // Fade out
15198 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
15199 {
15200 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
15201 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
15202 g.NavWindowingTargetAnim = NULL;
15203 }
15204
15205 // Start CTRL+Tab or Square+L/R window selection
15206 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
15207 const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing");
15208 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
15209 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
15210 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
15211 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
15212 const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id);
15213 const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad;
15214 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
15215 bool just_started_windowing_from_null_focus = false;
15216 if (start_toggling_with_gamepad)
15217 {
15218 g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer
15219 g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu;
15220 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad;
15221 }
15222 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
15223 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
15224 {
15225 if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad)
15226 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
15227 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
15228 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
15229 g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
15230 if (g.NavWindow == NULL)
15231 just_started_windowing_from_null_focus = true;
15232
15233 // 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.
15234 if (keyboard_next_window || keyboard_prev_window)
15235 SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
15236 }
15237
15238 // Gamepad update
15239 if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad)
15240 {
15241 if (g.NavWindowingTarget != NULL)
15242 {
15243 // 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
15244 // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast.
15245 g.NavWindowingTimer += io.DeltaTime;
15246 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
15247
15248 // Select window to focus
15249 const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
15250 if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
15251 {
15252 NavUpdateWindowingTarget(focus_change_dir);
15253 g.NavWindowingHighlightAlpha = 1.0f;
15254 }
15255 }
15256
15257 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
15258 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
15259 {
15260 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
15261 if (g.NavWindowingToggleLayer && g.NavWindow)
15262 apply_toggle_layer = true;
15263 else if (!g.NavWindowingToggleLayer)
15264 apply_focus_window = g.NavWindowingTarget;
15265 g.NavWindowingTarget = NULL;
15266 g.NavWindowingToggleLayer = false;
15267 }
15268 }
15269
15270 // Keyboard: Focus
15271 if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
15272 {
15273 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
15274 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
15275 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
15276 g.NavWindowingTimer += io.DeltaTime;
15277 g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
15278 if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
15279 NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1);
15280 else if ((io.KeyMods & shared_mods) != shared_mods)
15281 apply_focus_window = g.NavWindowingTarget;
15282 }
15283
15284 // Keyboard: Press and Release ALT to toggle menu layer
15285 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
15286 bool windowing_toggle_layer_start = false;
15287 if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
15288 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
15289 if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
15290 {
15291 windowing_toggle_layer_start = true;
15292 g.NavWindowingToggleLayer = true;
15293 g.NavWindowingToggleKey = windowing_toggle_key;
15294 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard;
15295 break;
15296 }
15297 if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard)
15298 {
15299 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
15300 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
15301 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
15302 // We cancel toggling nav layer if an owner has claimed the key.
15303 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
15304 g.NavWindowingToggleLayer = false;
15305 else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time)
15306 g.NavWindowingToggleLayer = false;
15307 else if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
15308 g.NavWindowingToggleLayer = false;
15309
15310 // Apply layer toggle on Alt release
15311 // 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.
15312 if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
15313 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
15314 if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
15315 apply_toggle_layer = true;
15316 if (!IsKeyDown(g.NavWindowingToggleKey))
15317 g.NavWindowingToggleLayer = false;
15318 }
15319
15320 // Move window
15321 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
15322 {
15323 ImVec2 nav_move_dir;
15324 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
15325 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
15326 if (g.NavInputSource == ImGuiInputSource_Gamepad)
15327 nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
15328 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
15329 {
15330 const float NAV_MOVE_SPEED = 800.0f;
15331 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
15332 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
15333 g.NavHighlightItemUnderNav = true;
15334 ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
15335 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
15336 {
15337 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
15338 SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
15339 g.NavWindowingAccumDeltaPos -= accum_floored;
15340 }
15341 }
15342 }
15343
15344 // Apply final focus
15345 if (apply_focus_window)
15346 NavUpdateWindowingApplyFocus(apply_focus_window);
15347
15348 // Apply menu/layer toggle
15349 if (apply_toggle_layer && g.NavWindow)
15350 {
15351 ClearActiveID();
15352
15353 // Move to parent menu if necessary
15354 ImGuiWindow* new_nav_window = g.NavWindow;
15355 while (new_nav_window->ParentWindow
15356 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
15357 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
15358 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
15359 new_nav_window = new_nav_window->ParentWindow;
15360 if (new_nav_window != g.NavWindow)
15361 {
15362 ImGuiWindow* old_nav_window = g.NavWindow;
15363 FocusWindow(new_nav_window);
15364 new_nav_window->NavLastChildNavWindow = old_nav_window;
15365 }
15366
15367 // Toggle layer
15368 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
15369 if (new_nav_layer != g.NavLayer)
15370 {
15371 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
15372 const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
15373 if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
15374 g.NavWindow->NavLastIds[new_nav_layer] = 0;
15375 NavRestoreLayer(new_nav_layer);
15376 SetNavCursorVisibleAfterMove();
15377 }
15378 }
15379 }
15380
15381 // Window has already passed the IsWindowNavFocusable()
15382 static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
15383 {
15384 if (window->Flags & ImGuiWindowFlags_Popup)
15385 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
15386 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
15387 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
15388 if (window->DockNodeAsHost)
15389 return "(Dock node)"; // Not normally shown to user.
15390 return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
15391 }
15392
15393 // Overlay displayed when using CTRL+TAB. Called by EndFrame().
15394 void ImGui::NavUpdateWindowingOverlay()
15395 {
15396 ImGuiContext& g = *GImGui;
15397 IM_ASSERT(g.NavWindowingTarget != NULL);
15398
15399 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
15400 return;
15401
15402 if (g.NavWindowingListWindow == NULL)
15403 g.NavWindowingListWindow = FindWindowByName("##NavWindowingOverlay");
15404 const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
15405 SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
15406 SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
15407 PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
15408 Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
15409 if (g.ContextName[0] != 0)
15410 SeparatorText(g.ContextName);
15411 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
15412 {
15413 ImGuiWindow* window = g.WindowsFocusOrder[n];
15414 IM_ASSERT(window != NULL); // Fix static analyzers
15415 if (!IsWindowNavFocusable(window))
15416 continue;
15417 const char* label = window->Name;
15418 if (label == FindRenderedTextEnd(label))
15419 label = GetFallbackWindowNameForWindowingList(window);
15420 Selectable(label, g.NavWindowingTarget == window);
15421 }
15422 End();
15423 PopStyleVar();
15424 }
15425
15426 //-----------------------------------------------------------------------------
15427 // [SECTION] DRAG AND DROP
15428 //-----------------------------------------------------------------------------
15429
15430 bool ImGui::IsDragDropActive()
15431 {
15432 ImGuiContext& g = *GImGui;
15433 return g.DragDropActive;
15434 }
15435
15436 void ImGui::ClearDragDrop()
15437 {
15438 ImGuiContext& g = *GImGui;
15439 if (g.DragDropActive)
15440 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
15441 g.DragDropActive = false;
15442 g.DragDropPayload.Clear();
15443 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
15444 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
15445 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
15446 g.DragDropAcceptFrameCount = -1;
15447
15448 g.DragDropPayloadBufHeap.clear();
15449 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
15450 }
15451
15452 bool ImGui::BeginTooltipHidden()
15453 {
15454 ImGuiContext& g = *GImGui;
15455 bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
15456 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
15457 return ret;
15458 }
15459
15460 // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
15461 // If the item has an identifier:
15462 // - This assume/require the item to be activated (typically via ButtonBehavior).
15463 // - 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.
15464 // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
15465 // If the item has no identifier:
15466 // - Currently always assume left mouse button.
15467 bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
15468 {
15469 ImGuiContext& g = *GImGui;
15470 ImGuiWindow* window = g.CurrentWindow;
15471
15472 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
15473 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
15474 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
15475
15476 bool source_drag_active = false;
15477 ImGuiID source_id = 0;
15478 ImGuiID source_parent_id = 0;
15479 if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
15480 {
15481 source_id = g.LastItemData.ID;
15482 if (source_id != 0)
15483 {
15484 // Common path: items with ID
15485 if (g.ActiveId != source_id)
15486 return false;
15487 if (g.ActiveIdMouseButton != -1)
15488 mouse_button = g.ActiveIdMouseButton;
15489 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15490 return false;
15491 g.ActiveIdAllowOverlap = false;
15492 }
15493 else
15494 {
15495 // Uncommon path: items without ID
15496 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
15497 return false;
15498 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
15499 return false;
15500
15501 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
15502 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
15503 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
15504 {
15505 IM_ASSERT(0);
15506 return false;
15507 }
15508
15509 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
15510 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
15511 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
15512 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
15513 // Rely on keeping other window->LastItemXXX fields intact.
15514 source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
15515 KeepAliveID(source_id);
15516 bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.ItemFlags);
15517 if (is_hovered && g.IO.MouseClicked[mouse_button])
15518 {
15519 SetActiveID(source_id, window);
15520 FocusWindow(window);
15521 }
15522 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
15523 g.ActiveIdAllowOverlap = is_hovered;
15524 }
15525 if (g.ActiveId != source_id)
15526 return false;
15527 source_parent_id = window->IDStack.back();
15528 source_drag_active = IsMouseDragging(mouse_button);
15529
15530 // Disable navigation and key inputs while dragging + cancel existing request if any
15531 SetActiveIdUsingAllKeyboardKeys();
15532 }
15533 else
15534 {
15535 // When ImGuiDragDropFlags_SourceExtern is set:
15536 window = NULL;
15537 source_id = ImHashStr("#SourceExtern");
15538 source_drag_active = true;
15539 mouse_button = g.IO.MouseDown[0] ? 0 : -1;
15540 KeepAliveID(source_id);
15541 SetActiveID(source_id, NULL);
15542 }
15543
15544 IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15545 if (!source_drag_active)
15546 return false;
15547
15548 // Activate drag and drop
15549 if (!g.DragDropActive)
15550 {
15551 IM_ASSERT(source_id != 0);
15552 ClearDragDrop();
15553 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
15554 source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
15555 ImGuiPayload& payload = g.DragDropPayload;
15556 payload.SourceId = source_id;
15557 payload.SourceParentId = source_parent_id;
15558 g.DragDropActive = true;
15559 g.DragDropSourceFlags = flags;
15560 g.DragDropMouseButton = mouse_button;
15561 if (payload.SourceId == g.ActiveId)
15562 g.ActiveIdNoClearOnFocusLoss = true;
15563 }
15564 g.DragDropSourceFrameCount = g.FrameCount;
15565 g.DragDropWithinSource = true;
15566
15567 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15568 {
15569 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
15570 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
15571 bool ret;
15572 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
15573 ret = BeginTooltipHidden();
15574 else
15575 ret = BeginTooltip();
15576 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
15577 IM_UNUSED(ret);
15578 }
15579
15580 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
15581 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
15582
15583 return true;
15584 }
15585
15586 void ImGui::EndDragDropSource()
15587 {
15588 ImGuiContext& g = *GImGui;
15589 IM_ASSERT(g.DragDropActive);
15590 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
15591
15592 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
15593 EndTooltip();
15594
15595 // Discard the drag if have not called SetDragDropPayload()
15596 if (g.DragDropPayload.DataFrameCount == -1)
15597 ClearDragDrop();
15598 g.DragDropWithinSource = false;
15599 }
15600
15601 // Use 'cond' to choose to submit payload on drag start or every frame
15602 bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
15603 {
15604 ImGuiContext& g = *GImGui;
15605 ImGuiPayload& payload = g.DragDropPayload;
15606 if (cond == 0)
15607 cond = ImGuiCond_Always;
15608
15609 IM_ASSERT(type != NULL);
15610 IM_ASSERT(ImStrlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
15611 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
15612 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
15613 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
15614
15615 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
15616 {
15617 // Copy payload
15618 ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
15619 g.DragDropPayloadBufHeap.resize(0);
15620 if (data_size > sizeof(g.DragDropPayloadBufLocal))
15621 {
15622 // Store in heap
15623 g.DragDropPayloadBufHeap.resize((int)data_size);
15624 payload.Data = g.DragDropPayloadBufHeap.Data;
15625 memcpy(payload.Data, data, data_size);
15626 }
15627 else if (data_size > 0)
15628 {
15629 // Store locally
15630 memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
15631 payload.Data = g.DragDropPayloadBufLocal;
15632 memcpy(payload.Data, data, data_size);
15633 }
15634 else
15635 {
15636 payload.Data = NULL;
15637 }
15638 payload.DataSize = (int)data_size;
15639 }
15640 payload.DataFrameCount = g.FrameCount;
15641
15642 // Return whether the payload has been accepted
15643 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
15644 }
15645
15646 bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
15647 {
15648 ImGuiContext& g = *GImGui;
15649 if (!g.DragDropActive)
15650 return false;
15651
15652 ImGuiWindow* window = g.CurrentWindow;
15653 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15654 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
15655 return false;
15656 IM_ASSERT(id != 0);
15657 if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
15658 return false;
15659 if (window->SkipItems)
15660 return false;
15661
15662 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15663 g.DragDropTargetRect = bb;
15664 g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
15665 g.DragDropTargetId = id;
15666 g.DragDropWithinTarget = true;
15667 return true;
15668 }
15669
15670 // We don't use BeginDragDropTargetCustom() and duplicate its code because:
15671 // 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.
15672 // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
15673 // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
15674 bool ImGui::BeginDragDropTarget()
15675 {
15676 ImGuiContext& g = *GImGui;
15677 if (!g.DragDropActive)
15678 return false;
15679
15680 ImGuiWindow* window = g.CurrentWindow;
15681 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
15682 return false;
15683 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
15684 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
15685 return false;
15686
15687 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
15688 ImGuiID id = g.LastItemData.ID;
15689 if (id == 0)
15690 {
15691 id = window->GetIDFromRectangle(display_rect);
15692 KeepAliveID(id);
15693 }
15694 if (g.DragDropPayload.SourceId == id)
15695 return false;
15696
15697 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
15698 g.DragDropTargetRect = display_rect;
15699 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
15700 g.DragDropTargetId = id;
15701 g.DragDropWithinTarget = true;
15702 return true;
15703 }
15704
15705 bool ImGui::IsDragDropPayloadBeingAccepted()
15706 {
15707 ImGuiContext& g = *GImGui;
15708 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
15709 }
15710
15711 const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
15712 {
15713 ImGuiContext& g = *GImGui;
15714 ImGuiPayload& payload = g.DragDropPayload;
15715 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
15716 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
15717 if (type != NULL && !payload.IsDataType(type))
15718 return NULL;
15719
15720 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
15721 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
15722 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
15723 ImRect r = g.DragDropTargetRect;
15724 float r_surface = r.GetWidth() * r.GetHeight();
15725 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
15726 return NULL;
15727
15728 g.DragDropAcceptFlags = flags;
15729 g.DragDropAcceptIdCurr = g.DragDropTargetId;
15730 g.DragDropAcceptIdCurrRectSurface = r_surface;
15731 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
15732
15733 // Render default drop visuals
15734 payload.Preview = was_accepted_previously;
15735 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
15736 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
15737 RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
15738
15739 g.DragDropAcceptFrameCount = g.FrameCount;
15740 if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
15741 payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
15742 else
15743 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()
15744 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
15745 return NULL;
15746
15747 if (payload.Delivery)
15748 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
15749 return &payload;
15750 }
15751
15752 // FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
15753 void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
15754 {
15755 ImGuiContext& g = *GImGui;
15756 ImGuiWindow* window = g.CurrentWindow;
15757 ImRect bb_display = bb;
15758 bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
15759 bb_display.Expand(3.5f);
15760 bool push_clip_rect = !window->ClipRect.Contains(bb_display);
15761 if (push_clip_rect)
15762 window->DrawList->PushClipRectFullScreen();
15763 window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI
15764 if (push_clip_rect)
15765 window->DrawList->PopClipRect();
15766 }
15767
15768 const ImGuiPayload* ImGui::GetDragDropPayload()
15769 {
15770 ImGuiContext& g = *GImGui;
15771 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
15772 }
15773
15774 void ImGui::EndDragDropTarget()
15775 {
15776 ImGuiContext& g = *GImGui;
15777 IM_ASSERT(g.DragDropActive);
15778 IM_ASSERT(g.DragDropWithinTarget);
15779 g.DragDropWithinTarget = false;
15780
15781 // Clear drag and drop state payload right after delivery
15782 if (g.DragDropPayload.Delivery)
15783 ClearDragDrop();
15784 }
15785
15786 //-----------------------------------------------------------------------------
15787 // [SECTION] LOGGING/CAPTURING
15788 //-----------------------------------------------------------------------------
15789 // All text output from the interface can be captured into tty/file/clipboard.
15790 // By default, tree nodes are automatically opened during logging.
15791 //-----------------------------------------------------------------------------
15792
15793 // Pass text data straight to log (without being displayed)
15794 static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
15795 {
15796 if (g.LogFile)
15797 {
15798 g.LogBuffer.Buf.resize(0);
15799 g.LogBuffer.appendfv(fmt, args);
15800 ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
15801 }
15802 else
15803 {
15804 g.LogBuffer.appendfv(fmt, args);
15805 }
15806 }
15807
15808 void ImGui::LogText(const char* fmt, ...)
15809 {
15810 ImGuiContext& g = *GImGui;
15811 if (!g.LogEnabled)
15812 return;
15813
15814 va_list args;
15815 va_start(args, fmt);
15816 LogTextV(g, fmt, args);
15817 va_end(args);
15818 }
15819
15820 void ImGui::LogTextV(const char* fmt, va_list args)
15821 {
15822 ImGuiContext& g = *GImGui;
15823 if (!g.LogEnabled)
15824 return;
15825
15826 LogTextV(g, fmt, args);
15827 }
15828
15829 // Internal version that takes a position to decide on newline placement and pad items according to their depth.
15830 // We split text into individual lines to add current tree level padding
15831 // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
15832 void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
15833 {
15834 ImGuiContext& g = *GImGui;
15835 ImGuiWindow* window = g.CurrentWindow;
15836
15837 const char* prefix = g.LogNextPrefix;
15838 const char* suffix = g.LogNextSuffix;
15839 g.LogNextPrefix = g.LogNextSuffix = NULL;
15840
15841 if (!text_end)
15842 text_end = FindRenderedTextEnd(text, text_end);
15843
15844 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
15845 if (ref_pos)
15846 g.LogLinePosY = ref_pos->y;
15847 if (log_new_line)
15848 {
15849 LogText(IM_NEWLINE);
15850 g.LogLineFirstItem = true;
15851 }
15852
15853 if (prefix)
15854 LogRenderedText(ref_pos, prefix, prefix + ImStrlen(prefix)); // Calculate end ourself to ensure "##" are included here.
15855
15856 // Re-adjust padding if we have popped out of our starting depth
15857 if (g.LogDepthRef > window->DC.TreeDepth)
15858 g.LogDepthRef = window->DC.TreeDepth;
15859 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
15860
15861 const char* text_remaining = text;
15862 for (;;)
15863 {
15864 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
15865 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
15866 const char* line_start = text_remaining;
15867 const char* line_end = ImStreolRange(line_start, text_end);
15868 const bool is_last_line = (line_end == text_end);
15869 if (line_start != line_end || !is_last_line)
15870 {
15871 const int line_length = (int)(line_end - line_start);
15872 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
15873 LogText("%*s%.*s", indentation, "", line_length, line_start);
15874 g.LogLineFirstItem = false;
15875 if (*line_end == '\n')
15876 {
15877 LogText(IM_NEWLINE);
15878 g.LogLineFirstItem = true;
15879 }
15880 }
15881 if (is_last_line)
15882 break;
15883 text_remaining = line_end + 1;
15884 }
15885
15886 if (suffix)
15887 LogRenderedText(ref_pos, suffix, suffix + ImStrlen(suffix));
15888 }
15889
15890 // Start logging/capturing text output
15891 void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
15892 {
15893 ImGuiContext& g = *GImGui;
15894 ImGuiWindow* window = g.CurrentWindow;
15895 IM_ASSERT(g.LogEnabled == false);
15896 IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
15897 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
15898
15899 g.LogEnabled = g.ItemUnclipByLog = true;
15900 g.LogFlags = flags;
15901 g.LogWindow = window;
15902 g.LogNextPrefix = g.LogNextSuffix = NULL;
15903 g.LogDepthRef = window->DC.TreeDepth;
15904 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
15905 g.LogLinePosY = FLT_MAX;
15906 g.LogLineFirstItem = true;
15907 }
15908
15909 // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
15910 void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
15911 {
15912 ImGuiContext& g = *GImGui;
15913 g.LogNextPrefix = prefix;
15914 g.LogNextSuffix = suffix;
15915 }
15916
15917 void ImGui::LogToTTY(int auto_open_depth)
15918 {
15919 ImGuiContext& g = *GImGui;
15920 if (g.LogEnabled)
15921 return;
15922 IM_UNUSED(auto_open_depth);
15923 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15924 LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth);
15925 g.LogFile = stdout;
15926 #endif
15927 }
15928
15929 // Start logging/capturing text output to given file
15930 void ImGui::LogToFile(int auto_open_depth, const char* filename)
15931 {
15932 ImGuiContext& g = *GImGui;
15933 if (g.LogEnabled)
15934 return;
15935
15936 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
15937 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
15938 // By opening the file in binary mode "ab" we have consistent output everywhere.
15939 if (!filename)
15940 filename = g.IO.LogFilename;
15941 if (!filename || !filename[0])
15942 return;
15943 ImFileHandle f = ImFileOpen(filename, "ab");
15944 if (!f)
15945 {
15946 IM_ASSERT(0);
15947 return;
15948 }
15949
15950 LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth);
15951 g.LogFile = f;
15952 }
15953
15954 // Start logging/capturing text output to clipboard
15955 void ImGui::LogToClipboard(int auto_open_depth)
15956 {
15957 ImGuiContext& g = *GImGui;
15958 if (g.LogEnabled)
15959 return;
15960 LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth);
15961 }
15962
15963 void ImGui::LogToBuffer(int auto_open_depth)
15964 {
15965 ImGuiContext& g = *GImGui;
15966 if (g.LogEnabled)
15967 return;
15968 LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth);
15969 }
15970
15971 void ImGui::LogFinish()
15972 {
15973 ImGuiContext& g = *GImGui;
15974 if (!g.LogEnabled)
15975 return;
15976
15977 LogText(IM_NEWLINE);
15978 switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
15979 {
15980 case ImGuiLogFlags_OutputTTY:
15981 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
15982 fflush(g.LogFile);
15983 #endif
15984 break;
15985 case ImGuiLogFlags_OutputFile:
15986 ImFileClose(g.LogFile);
15987 break;
15988 case ImGuiLogFlags_OutputBuffer:
15989 break;
15990 case ImGuiLogFlags_OutputClipboard:
15991 if (!g.LogBuffer.empty())
15992 SetClipboardText(g.LogBuffer.begin());
15993 break;
15994 default:
15995 IM_ASSERT(0);
15996 break;
15997 }
15998
15999 g.LogEnabled = g.ItemUnclipByLog = false;
16000 g.LogFlags = ImGuiLogFlags_None;
16001 g.LogFile = NULL;
16002 g.LogBuffer.clear();
16003 }
16004
16005 // Helper to display logging buttons
16006 // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
16007 void ImGui::LogButtons()
16008 {
16009 ImGuiContext& g = *GImGui;
16010
16011 PushID("LogButtons");
16012 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
16013 const bool log_to_tty = Button("Log To TTY"); SameLine();
16014 #else
16015 const bool log_to_tty = false;
16016 #endif
16017 const bool log_to_file = Button("Log To File"); SameLine();
16018 const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
16019 PushItemFlag(ImGuiItemFlags_NoTabStop, true);
16020 SetNextItemWidth(80.0f);
16021 SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
16022 PopItemFlag();
16023 PopID();
16024
16025 // Start logging at the end of the function so that the buttons don't appear in the log
16026 if (log_to_tty)
16027 LogToTTY();
16028 if (log_to_file)
16029 LogToFile();
16030 if (log_to_clipboard)
16031 LogToClipboard();
16032 }
16033
16034 //-----------------------------------------------------------------------------
16035 // [SECTION] SETTINGS
16036 //-----------------------------------------------------------------------------
16037 // - UpdateSettings() [Internal]
16038 // - MarkIniSettingsDirty() [Internal]
16039 // - FindSettingsHandler() [Internal]
16040 // - ClearIniSettings() [Internal]
16041 // - LoadIniSettingsFromDisk()
16042 // - LoadIniSettingsFromMemory()
16043 // - SaveIniSettingsToDisk()
16044 // - SaveIniSettingsToMemory()
16045 //-----------------------------------------------------------------------------
16046 // - CreateNewWindowSettings() [Internal]
16047 // - FindWindowSettingsByID() [Internal]
16048 // - FindWindowSettingsByWindow() [Internal]
16049 // - ClearWindowSettings() [Internal]
16050 // - WindowSettingsHandler_***() [Internal]
16051 //-----------------------------------------------------------------------------
16052
16053 // Called by NewFrame()
16054 void ImGui::UpdateSettings()
16055 {
16056 // Load settings on first frame (if not explicitly loaded manually before)
16057 ImGuiContext& g = *GImGui;
16058 if (!g.SettingsLoaded)
16059 {
16060 IM_ASSERT(g.SettingsWindows.empty());
16061 if (g.IO.IniFilename)
16062 LoadIniSettingsFromDisk(g.IO.IniFilename);
16063 g.SettingsLoaded = true;
16064 }
16065
16066 // Save settings (with a delay after the last modification, so we don't spam disk too much)
16067 if (g.SettingsDirtyTimer > 0.0f)
16068 {
16069 g.SettingsDirtyTimer -= g.IO.DeltaTime;
16070 if (g.SettingsDirtyTimer <= 0.0f)
16071 {
16072 if (g.IO.IniFilename != NULL)
16073 SaveIniSettingsToDisk(g.IO.IniFilename);
16074 else
16075 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
16076 g.SettingsDirtyTimer = 0.0f;
16077 }
16078 }
16079 }
16080
16081 void ImGui::MarkIniSettingsDirty()
16082 {
16083 ImGuiContext& g = *GImGui;
16084 if (g.SettingsDirtyTimer <= 0.0f)
16085 g.SettingsDirtyTimer = g.IO.IniSavingRate;
16086 }
16087
16088 void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
16089 {
16090 ImGuiContext& g = *GImGui;
16091 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
16092 if (g.SettingsDirtyTimer <= 0.0f)
16093 g.SettingsDirtyTimer = g.IO.IniSavingRate;
16094 }
16095
16096 void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
16097 {
16098 ImGuiContext& g = *GImGui;
16099 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
16100 g.SettingsHandlers.push_back(*handler);
16101 }
16102
16103 void ImGui::RemoveSettingsHandler(const char* type_name)
16104 {
16105 ImGuiContext& g = *GImGui;
16106 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
16107 g.SettingsHandlers.erase(handler);
16108 }
16109
16110 ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
16111 {
16112 ImGuiContext& g = *GImGui;
16113 const ImGuiID type_hash = ImHashStr(type_name);
16114 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
16115 if (handler.TypeHash == type_hash)
16116 return &handler;
16117 return NULL;
16118 }
16119
16120 // Clear all settings (windows, tables, docking etc.)
16121 void ImGui::ClearIniSettings()
16122 {
16123 ImGuiContext& g = *GImGui;
16124 g.SettingsIniData.clear();
16125 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
16126 if (handler.ClearAllFn != NULL)
16127 handler.ClearAllFn(&g, &handler);
16128 }
16129
16130 bool ImGui::LoadIniSettingsFromDisk(const char* ini_filename, bool redundancy)
16131 {
16132 size_t file_data_size = 0;
16133 char* file_data = NULL;
16134
16135 if (redundancy) {
16136 char fileName[4096];
16137
16138 for (int i=0; i<5; i++) {
16139 bool viable=false;
16140 if (i>0) {
16141 snprintf(fileName,4095,"%s.%d",ini_filename,i);
16142 } else {
16143 strncpy(fileName,ini_filename,4095);
16144 }
16145 file_data=(char*)ImFileLoadToMemory(fileName, "rb", &file_data_size);
16146 if (!file_data) continue;
16147
16148 for (size_t j=0; j<file_data_size; j++) {
16149 if (file_data[j]==0) {
16150 viable=false;
16151 break;
16152 }
16153 if (file_data[j]!='\r' && file_data[j]!='\n' && file_data[j]!=' ') {
16154 viable=true;
16155 }
16156 }
16157
16158 if (!viable) {
16159 IM_FREE(file_data);
16160 file_data=NULL;
16161 file_data_size=0;
16162 } else {
16163 break;
16164 }
16165 }
16166 } else {
16167 file_data=(char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
16168 }
16169 if (!file_data)
16170 return false;
16171 if (file_data_size > 0)
16172 LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
16173 IM_FREE(file_data);
16174 return true;
16175 }
16176
16177 // Zero-tolerance, no error reporting, cheap .ini parsing
16178 // 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!
16179 void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
16180 {
16181 ImGuiContext& g = *GImGui;
16182 IM_ASSERT(g.Initialized);
16183 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
16184 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
16185
16186 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
16187 // 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..
16188 if (ini_size == 0)
16189 ini_size = ImStrlen(ini_data);
16190 g.SettingsIniData.Buf.resize((int)ini_size + 1);
16191 char* const buf = g.SettingsIniData.Buf.Data;
16192 char* const buf_end = buf + ini_size;
16193 memcpy(buf, ini_data, ini_size);
16194 buf_end[0] = 0;
16195
16196 // Call pre-read handlers
16197 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
16198 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
16199 if (handler.ReadInitFn != NULL)
16200 handler.ReadInitFn(&g, &handler);
16201
16202 void* entry_data = NULL;
16203 ImGuiSettingsHandler* entry_handler = NULL;
16204
16205 char* line_end = NULL;
16206 for (char* line = buf; line < buf_end; line = line_end + 1)
16207 {
16208 // Skip new lines markers, then find end of the line
16209 while (*line == '\n' || *line == '\r')
16210 line++;
16211 line_end = line;
16212 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
16213 line_end++;
16214 line_end[0] = 0;
16215 if (line[0] == ';')
16216 continue;
16217 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
16218 {
16219 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
16220 line_end[-1] = 0;
16221 const char* name_end = line_end - 1;
16222 const char* type_start = line + 1;
16223 char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
16224 const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
16225 if (!type_end || !name_start)
16226 continue;
16227 *type_end = 0; // Overwrite first ']'
16228 name_start++; // Skip second '['
16229 entry_handler = FindSettingsHandler(type_start);
16230 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
16231 }
16232 else if (entry_handler != NULL && entry_data != NULL)
16233 {
16234 // Let type handler parse the line
16235 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
16236 }
16237 }
16238 g.SettingsLoaded = true;
16239
16240 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
16241 memcpy(buf, ini_data, ini_size);
16242
16243 // Call post-read handlers
16244 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
16245 if (handler.ApplyAllFn != NULL)
16246 handler.ApplyAllFn(&g, &handler);
16247 }
16248
16249 bool ImGui::SaveIniSettingsToDisk(const char* ini_filename, bool redundancy)
16250 {
16251 ImGuiContext& g = *GImGui;
16252 g.SettingsDirtyTimer = 0.0f;
16253 if (!ini_filename)
16254 return false;
16255
16256 if (redundancy) {
16257 char oldPath[4096];
16258 char newPath[4096];
16259
16260 if (fileExists(ini_filename)==1) {
16261 for (int i=4; i>=0; i--) {
16262 if (i>0) {
16263 snprintf(oldPath,4095,"%s.%d",ini_filename,i);
16264 } else {
16265 strncpy(oldPath,ini_filename,4095);
16266 }
16267 snprintf(newPath,4095,"%s.%d",ini_filename,i+1);
16268
16269 if (i>=4) {
16270 deleteFile(oldPath);
16271 } else {
16272 moveFiles(oldPath,newPath);
16273 }
16274 }
16275 }
16276 }
16277
16278 size_t ini_data_size = 0;
16279 const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
16280 ImFileHandle f = ImFileOpen(ini_filename, "wt");
16281 if (!f)
16282 return false;
16283 bool areEqual=ImFileWrite(ini_data, sizeof(char), ini_data_size, f)==ini_data_size;
16284 IM_ASSERT_USER_ERROR(areEqual, "ImFileWrite failed to write file!");
16285 ImFileClose(f);
16286 if (!areEqual && redundancy) deleteFile(ini_filename);
16287 return areEqual;
16288 }
16289
16290 // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
16291 const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
16292 {
16293 ImGuiContext& g = *GImGui;
16294 g.SettingsDirtyTimer = 0.0f;
16295 g.SettingsIniData.Buf.resize(0);
16296 g.SettingsIniData.Buf.push_back(0);
16297 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
16298 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
16299 if (out_size)
16300 *out_size = (size_t)g.SettingsIniData.size();
16301 return g.SettingsIniData.c_str();
16302 }
16303
16304 ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
16305 {
16306 ImGuiContext& g = *GImGui;
16307
16308 if (g.IO.ConfigDebugIniSettings == false)
16309 {
16310 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
16311 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
16312 if (const char* p = strstr(name, "###"))
16313 name = p;
16314 }
16315 const size_t name_len = ImStrlen(name);
16316
16317 // Allocate chunk
16318 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
16319 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
16320 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
16321 settings->ID = ImHashStr(name, name_len);
16322 memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
16323
16324 return settings;
16325 }
16326
16327 // We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
16328 // This is called once per window .ini entry + once per newly instantiated window.
16329 ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
16330 {
16331 ImGuiContext& g = *GImGui;
16332 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16333 if (settings->ID == id && !settings->WantDelete)
16334 return settings;
16335 return NULL;
16336 }
16337
16338 // This is faster if you are holding on a Window already as we don't need to perform a search.
16339 ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
16340 {
16341 ImGuiContext& g = *GImGui;
16342 if (window->SettingsOffset != -1)
16343 return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
16344 return FindWindowSettingsByID(window->ID);
16345 }
16346
16347 // This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
16348 void ImGui::ClearWindowSettings(const char* name)
16349 {
16350 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
16351 ImGuiContext& g = *GImGui;
16352 ImGuiWindow* window = FindWindowByName(name);
16353 if (window != NULL)
16354 {
16355 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
16356 InitOrLoadWindowSettings(window, NULL);
16357 if (window->DockId != 0)
16358 DockContextProcessUndockWindow(&g, window, true);
16359 }
16360 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
16361 settings->WantDelete = true;
16362 }
16363
16364 static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
16365 {
16366 ImGuiContext& g = *ctx;
16367 for (ImGuiWindow* window : g.Windows)
16368 window->SettingsOffset = -1;
16369 g.SettingsWindows.clear();
16370 }
16371
16372 static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
16373 {
16374 ImGuiID id = ImHashStr(name);
16375 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
16376 if (settings)
16377 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
16378 else
16379 settings = ImGui::CreateNewWindowSettings(name);
16380 settings->ID = id;
16381 settings->WantApply = true;
16382 return (void*)settings;
16383 }
16384
16385 static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
16386 {
16387 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
16388 int x, y;
16389 int i;
16390 ImU32 u1;
16391 if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
16392 else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
16393 else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
16394 else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
16395 else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
16396 else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
16397 else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
16398 else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
16399 else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
16400 }
16401
16402 // Apply to existing windows (if any)
16403 static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
16404 {
16405 ImGuiContext& g = *ctx;
16406 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16407 if (settings->WantApply)
16408 {
16409 if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
16410 ApplyWindowSettings(window, settings);
16411 settings->WantApply = false;
16412 }
16413 }
16414
16415 static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
16416 {
16417 // Gather data from windows that were active during this session
16418 // (if a window wasn't opened in this session we preserve its settings)
16419 ImGuiContext& g = *ctx;
16420 for (ImGuiWindow* window : g.Windows)
16421 {
16422 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
16423 continue;
16424
16425 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
16426 if (!settings)
16427 {
16428 settings = ImGui::CreateNewWindowSettings(window->Name);
16429 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
16430 }
16431 IM_ASSERT(settings->ID == window->ID);
16432 settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
16433 settings->Size = ImVec2ih(window->SizeFull);
16434 settings->ViewportId = window->ViewportId;
16435 settings->ViewportPos = ImVec2ih(window->ViewportPos);
16436 IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
16437 settings->DockId = window->DockId;
16438 settings->ClassId = window->WindowClass.ClassId;
16439 settings->DockOrder = window->DockOrder;
16440 settings->Collapsed = window->Collapsed;
16441 settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
16442 settings->WantDelete = false;
16443 }
16444
16445 // Write to text buffer
16446 buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
16447 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16448 {
16449 if (settings->WantDelete)
16450 continue;
16451 const char* settings_name = settings->GetName();
16452 buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
16453 if (settings->IsChild)
16454 {
16455 buf->appendf("IsChild=1\n");
16456 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
16457 }
16458 else
16459 {
16460 if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
16461 {
16462 buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
16463 buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
16464 }
16465 if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
16466 buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
16467 if (settings->Size.x != 0 || settings->Size.y != 0)
16468 buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
16469 buf->appendf("Collapsed=%d\n", settings->Collapsed);
16470 if (settings->DockId != 0)
16471 {
16472 //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.
16473 if (settings->DockOrder == -1)
16474 buf->appendf("DockId=0x%08X\n", settings->DockId);
16475 else
16476 buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
16477 if (settings->ClassId != 0)
16478 buf->appendf("ClassId=0x%08X\n", settings->ClassId);
16479 }
16480 }
16481 buf->append("\n");
16482 }
16483 }
16484
16485 //-----------------------------------------------------------------------------
16486 // [SECTION] LOCALIZATION
16487 //-----------------------------------------------------------------------------
16488
16489 void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
16490 {
16491 ImGuiContext& g = *GImGui;
16492
16493 if (GImGui != NULL)
16494 {
16495 for (int n = 0; n < count; n++)
16496 {
16497 g.LocalizationTable[entries[n].Key] = entries[n].Text;
16498 }
16499 }
16500 }
16501
16502 //-----------------------------------------------------------------------------
16503 // [SECTION] VIEWPORTS, PLATFORM WINDOWS
16504 //-----------------------------------------------------------------------------
16505 // - GetMainViewport()
16506 // - FindViewportByID()
16507 // - FindViewportByPlatformHandle()
16508 // - SetCurrentViewport() [Internal]
16509 // - SetWindowViewport() [Internal]
16510 // - GetWindowAlwaysWantOwnViewport() [Internal]
16511 // - UpdateTryMergeWindowIntoHostViewport() [Internal]
16512 // - UpdateTryMergeWindowIntoHostViewports() [Internal]
16513 // - TranslateWindowsInViewport() [Internal]
16514 // - ScaleWindowsInViewport() [Internal]
16515 // - FindHoveredViewportFromPlatformWindowStack() [Internal]
16516 // - UpdateViewportsNewFrame() [Internal]
16517 // - UpdateViewportsEndFrame() [Internal]
16518 // - AddUpdateViewport() [Internal]
16519 // - WindowSelectViewport() [Internal]
16520 // - WindowSyncOwnedViewport() [Internal]
16521 // - UpdatePlatformWindows()
16522 // - RenderPlatformWindowsDefault()
16523 // - FindPlatformMonitorForPos() [Internal]
16524 // - FindPlatformMonitorForRect() [Internal]
16525 // - UpdateViewportPlatformMonitor() [Internal]
16526 // - DestroyPlatformWindow() [Internal]
16527 // - DestroyPlatformWindows()
16528 //-----------------------------------------------------------------------------
16529
16530 ImGuiViewport* ImGui::GetMainViewport()
16531 {
16532 ImGuiContext& g = *GImGui;
16533 return g.Viewports[0];
16534 }
16535
16536 // FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
16537 ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
16538 {
16539 ImGuiContext& g = *GImGui;
16540 for (ImGuiViewportP* viewport : g.Viewports)
16541 if (viewport->ID == id)
16542 return viewport;
16543 return NULL;
16544 }
16545
16546 ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
16547 {
16548 ImGuiContext& g = *GImGui;
16549 for (ImGuiViewportP* viewport : g.Viewports)
16550 if (viewport->PlatformHandle == platform_handle)
16551 return viewport;
16552 return NULL;
16553 }
16554
16555 void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
16556 {
16557 ImGuiContext& g = *GImGui;
16558 (void)current_window;
16559
16560 if (viewport)
16561 viewport->LastFrameActive = g.FrameCount;
16562 if (g.CurrentViewport == viewport)
16563 return;
16564 g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
16565 g.CurrentViewport = viewport;
16566 IM_ASSERT(g.CurrentDpiScale > 0.0f && g.CurrentDpiScale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
16567 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
16568
16569 // Notify platform layer of viewport changes
16570 // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
16571 if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
16572 g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
16573 }
16574
16575 void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16576 {
16577 // Abandon viewport
16578 if (window->ViewportOwned && window->Viewport->Window == window)
16579 window->Viewport->Size = ImVec2(0.0f, 0.0f);
16580
16581 window->Viewport = viewport;
16582 window->ViewportId = viewport->ID;
16583 window->ViewportOwned = (viewport->Window == window);
16584 }
16585
16586 static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
16587 {
16588 // 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.
16589 ImGuiContext& g = *GImGui;
16590 if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
16591 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16592 if (!window->DockIsActive)
16593 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
16594 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
16595 return true;
16596 return false;
16597 }
16598
16599 static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
16600 {
16601 ImGuiContext& g = *GImGui;
16602 if (window->Viewport == viewport)
16603 return false;
16604 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
16605 return false;
16606 if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
16607 return false;
16608 if (!viewport->GetMainRect().Contains(window->Rect()))
16609 return false;
16610 if (GetWindowAlwaysWantOwnViewport(window))
16611 return false;
16612
16613 // 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..
16614 for (ImGuiWindow* window_behind : g.Windows)
16615 {
16616 if (window_behind == window)
16617 break;
16618 if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
16619 if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
16620 return false;
16621 }
16622
16623 // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
16624 ImGuiViewportP* old_viewport = window->Viewport;
16625 if (window->ViewportOwned)
16626 for (int n = 0; n < g.Windows.Size; n++)
16627 if (g.Windows[n]->Viewport == old_viewport)
16628 SetWindowViewport(g.Windows[n], viewport);
16629 SetWindowViewport(window, viewport);
16630 BringWindowToDisplayFront(window);
16631
16632 return true;
16633 }
16634
16635 // FIXME: handle 0 to N host viewports
16636 static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
16637 {
16638 ImGuiContext& g = *GImGui;
16639 return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
16640 }
16641
16642 // Translate Dear ImGui windows when a Host Viewport has been moved
16643 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
16644 void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size)
16645 {
16646 ImGuiContext& g = *GImGui;
16647 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X\n", viewport->ID);
16648 IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
16649
16650 // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
16651 // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
16652 // 2) If it's not going to fit into the new size, keep it at same absolute position.
16653 // One problem with this is that most Win32 applications doesn't update their render while dragging,
16654 // and so the window will appear to teleport when releasing the mouse.
16655 const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
16656 ImRect test_still_fit_rect(old_pos, old_pos + old_size);
16657 ImVec2 delta_pos = new_pos - old_pos;
16658 for (ImGuiWindow* window : g.Windows) // FIXME-OPT
16659 if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(window->Rect()))))
16660 TranslateWindow(window, delta_pos);
16661 }
16662
16663 // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
16664 void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
16665 {
16666 ImGuiContext& g = *GImGui;
16667 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport->ID);
16668 if (viewport->Window)
16669 {
16670 ScaleWindow(viewport->Window, scale);
16671 }
16672 else
16673 {
16674 for (ImGuiWindow* window : g.Windows)
16675 if (window->Viewport == viewport)
16676 ScaleWindow(window, scale);
16677 }
16678 }
16679
16680 // If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
16681 // A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
16682 // B) It requires Platform_GetWindowFocus to be implemented by backend.
16683 ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
16684 {
16685 ImGuiContext& g = *GImGui;
16686 ImGuiViewportP* best_candidate = NULL;
16687 for (ImGuiViewportP* viewport : g.Viewports)
16688 if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
16689 if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
16690 best_candidate = viewport;
16691 return best_candidate;
16692 }
16693
16694 // Update viewports and monitor infos
16695 // Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
16696 static void ImGui::UpdateViewportsNewFrame()
16697 {
16698 ImGuiContext& g = *GImGui;
16699 IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
16700
16701 // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
16702 // Update Focused status
16703 const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
16704 if (viewports_enabled)
16705 {
16706 ImGuiViewportP* focused_viewport = NULL;
16707 for (ImGuiViewportP* viewport : g.Viewports)
16708 {
16709 const bool platform_funcs_available = viewport->PlatformWindowCreated;
16710 if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
16711 {
16712 bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
16713 if (is_minimized)
16714 viewport->Flags |= ImGuiViewportFlags_IsMinimized;
16715 else
16716 viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
16717 }
16718
16719 // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
16720 // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
16721 if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
16722 {
16723 bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
16724 if (is_focused)
16725 viewport->Flags |= ImGuiViewportFlags_IsFocused;
16726 else
16727 viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
16728 if (is_focused)
16729 focused_viewport = viewport;
16730 }
16731 }
16732
16733 // Focused viewport has changed?
16734 if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
16735 {
16736 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");
16737 const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
16738 const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
16739
16740 // Store a tag so we can infer z-order easily from all our windows
16741 // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
16742 // will keep the front most stamp instead of losing it back to their parent viewport.
16743 if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
16744 focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
16745 g.PlatformLastFocusedViewportId = focused_viewport->ID;
16746
16747 // Focus associated dear imgui window
16748 // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
16749 // - if focus didn't happen because we destroyed another window (#6462)
16750 // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
16751 const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
16752 if (apply_imgui_focus_on_focused_viewport && g.IO.ConfigViewportPlatformFocusSetsImGuiFocus)
16753 {
16754 focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
16755 ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
16756 if (focused_viewport->Window != NULL)
16757 FocusWindow(focused_viewport->Window, focus_request_flags);
16758 else if (focused_viewport->LastFocusedHadNavWindow)
16759 FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
16760 else
16761 FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
16762 }
16763 }
16764 if (focused_viewport)
16765 focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
16766 }
16767
16768 // Create/update main viewport with current platform position.
16769 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
16770 ImGuiViewportP* main_viewport = g.Viewports[0];
16771 IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
16772 IM_ASSERT(main_viewport->Window == NULL);
16773 ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
16774 ImVec2 main_viewport_size = g.IO.DisplaySize;
16775 ImVec2 main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale;
16776 if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
16777 {
16778 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)
16779 main_viewport_size = main_viewport->Size;
16780 main_viewport_framebuffer_scale = main_viewport->FramebufferScale;
16781 }
16782 AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
16783
16784 g.CurrentDpiScale = 0.0f;
16785 g.CurrentViewport = NULL;
16786 g.MouseViewport = NULL;
16787 for (int n = 0; n < g.Viewports.Size; n++)
16788 {
16789 ImGuiViewportP* viewport = g.Viewports[n];
16790 viewport->Idx = n;
16791
16792 // Erase unused viewports
16793 if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
16794 {
16795 DestroyViewport(viewport);
16796 n--;
16797 continue;
16798 }
16799
16800 const bool platform_funcs_available = viewport->PlatformWindowCreated;
16801 if (viewports_enabled)
16802 {
16803 // Update Position and Size (from Platform Window to ImGui) if requested.
16804 // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
16805 if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
16806 {
16807 // Viewport->WorkPos and WorkSize will be updated below
16808 if (viewport->PlatformRequestMove)
16809 viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
16810 if (viewport->PlatformRequestResize)
16811 viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
16812 if (g.PlatformIO.Platform_GetWindowFramebufferScale != NULL)
16813 viewport->FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport);
16814 }
16815 }
16816
16817 // Update/copy monitor info
16818 UpdateViewportPlatformMonitor(viewport);
16819
16820 // Lock down space taken by menu bars and status bars + query initial insets from backend
16821 // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
16822 viewport->WorkInsetMin = viewport->BuildWorkInsetMin;
16823 viewport->WorkInsetMax = viewport->BuildWorkInsetMax;
16824 viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f);
16825 if (g.PlatformIO.Platform_GetWindowWorkAreaInsets != NULL && platform_funcs_available)
16826 {
16827 ImVec4 insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport);
16828 IM_ASSERT(insets.x >= 0.0f && insets.y >= 0.0f && insets.z >= 0.0f && insets.w >= 0.0f);
16829 viewport->BuildWorkInsetMin = ImVec2(insets.x, insets.y);
16830 viewport->BuildWorkInsetMax = ImVec2(insets.z, insets.w);
16831 }
16832 viewport->UpdateWorkRect();
16833
16834 // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
16835 viewport->Alpha = 1.0f;
16836
16837 // Translate Dear ImGui windows when a Host Viewport has been moved
16838 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
16839 const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
16840 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
16841 TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos, viewport->LastSize, viewport->Size);
16842
16843 // Update DPI scale
16844 float new_dpi_scale;
16845 if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
16846 new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
16847 else if (viewport->PlatformMonitor != -1)
16848 new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
16849 else
16850 new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
16851 IM_ASSERT(new_dpi_scale > 0.0f && new_dpi_scale < 99.0f); // Typical correct values would be between 1.0f and 4.0f
16852 if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
16853 {
16854 float scale_factor = new_dpi_scale / viewport->DpiScale;
16855 if (g.IO.ConfigDpiScaleViewports)
16856 ScaleWindowsInViewport(viewport, scale_factor);
16857 //if (viewport == GetMainViewport())
16858 // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
16859
16860 // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
16861 // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
16862 // (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.)
16863 //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
16864 // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
16865 }
16866 viewport->DpiScale = new_dpi_scale;
16867 }
16868
16869 // Update fallback monitor
16870 g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
16871 if (g.PlatformIO.Monitors.Size == 0)
16872 {
16873 ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
16874 monitor->MainPos = main_viewport->Pos;
16875 monitor->MainSize = main_viewport->Size;
16876 monitor->WorkPos = main_viewport->WorkPos;
16877 monitor->WorkSize = main_viewport->WorkSize;
16878 monitor->DpiScale = main_viewport->DpiScale;
16879 g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
16880 g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
16881 }
16882 else
16883 {
16884 g.FallbackMonitor = g.PlatformIO.Monitors[0];
16885 }
16886 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
16887 {
16888 g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
16889 g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
16890 }
16891
16892 if (!viewports_enabled)
16893 {
16894 g.MouseViewport = main_viewport;
16895 return;
16896 }
16897
16898 // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
16899 // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
16900 ImGuiViewportP* viewport_hovered = NULL;
16901 if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
16902 {
16903 viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
16904 if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
16905 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
16906 }
16907 else
16908 {
16909 // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
16910 // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
16911 // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
16912 // 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)
16913 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
16914 }
16915 if (viewport_hovered != NULL)
16916 g.MouseLastHoveredViewport = viewport_hovered;
16917 else if (g.MouseLastHoveredViewport == NULL)
16918 g.MouseLastHoveredViewport = g.Viewports[0];
16919
16920 // Update mouse reference viewport
16921 // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
16922 // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
16923 if (g.MovingWindow && g.MovingWindow->Viewport)
16924 g.MouseViewport = g.MovingWindow->Viewport;
16925 else
16926 g.MouseViewport = g.MouseLastHoveredViewport;
16927
16928 // When dragging something, always refer to the last hovered viewport.
16929 // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
16930 // - 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)
16931 // - 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.
16932 // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
16933 const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
16934 if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
16935 viewport_hovered = g.MouseLastHoveredViewport;
16936 if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
16937 if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
16938 g.MouseViewport = viewport_hovered;
16939
16940 IM_ASSERT(g.MouseViewport != NULL);
16941 }
16942
16943 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
16944 static void ImGui::UpdateViewportsEndFrame()
16945 {
16946 ImGuiContext& g = *GImGui;
16947 g.PlatformIO.Viewports.resize(0);
16948 for (int i = 0; i < g.Viewports.Size; i++)
16949 {
16950 ImGuiViewportP* viewport = g.Viewports[i];
16951 viewport->LastPos = viewport->Pos;
16952 viewport->LastSize = viewport->Size;
16953 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
16954 if (i > 0) // Always include main viewport in the list
16955 continue;
16956 if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
16957 continue;
16958 if (i > 0)
16959 IM_ASSERT(viewport->Window != NULL);
16960 g.PlatformIO.Viewports.push_back(viewport);
16961 }
16962 g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
16963 }
16964
16965 // FIXME: We should ideally refactor the system to call this every frame (we currently don't)
16966 ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
16967 {
16968 ImGuiContext& g = *GImGui;
16969 IM_ASSERT(id != 0);
16970
16971 flags |= ImGuiViewportFlags_IsPlatformWindow;
16972 if (window != NULL)
16973 {
16974 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
16975 if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
16976 flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
16977 if (!window_can_use_inputs)
16978 flags |= ImGuiViewportFlags_NoInputs;
16979 if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
16980 flags |= ImGuiViewportFlags_NoFocusOnAppearing;
16981 }
16982
16983 ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
16984 if (viewport)
16985 {
16986 // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
16987 ImVec2 prev_pos = viewport->Pos;
16988 ImVec2 prev_size = viewport->Size;
16989 if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
16990 viewport->Pos = pos;
16991 if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
16992 viewport->Size = size;
16993 viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
16994 if (prev_pos != viewport->Pos || prev_size != viewport->Size)
16995 UpdateViewportPlatformMonitor(viewport);
16996 }
16997 else
16998 {
16999 // New viewport
17000 viewport = IM_NEW(ImGuiViewportP)();
17001 viewport->ID = id;
17002 viewport->Idx = g.Viewports.Size;
17003 viewport->Pos = viewport->LastPos = pos;
17004 viewport->Size = viewport->LastSize = size;
17005 viewport->Flags = flags;
17006 UpdateViewportPlatformMonitor(viewport);
17007 g.Viewports.push_back(viewport);
17008 g.ViewportCreatedCount++;
17009 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
17010
17011 // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
17012 // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
17013 g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
17014 g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
17015 g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
17016 g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
17017
17018 // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
17019 // This is so we can select an appropriate font size on the first frame of our window lifetime
17020 viewport->DpiScale = GetViewportPlatformMonitor(viewport)->DpiScale;
17021 }
17022
17023 viewport->Window = window;
17024 viewport->LastFrameActive = g.FrameCount;
17025 viewport->UpdateWorkRect();
17026 IM_ASSERT(window == NULL || viewport->ID == window->ID);
17027
17028 if (window != NULL)
17029 window->ViewportOwned = true;
17030
17031 return viewport;
17032 }
17033
17034 static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
17035 {
17036 // Clear references to this viewport in windows (window->ViewportId becomes the master data)
17037 ImGuiContext& g = *GImGui;
17038 for (ImGuiWindow* window : g.Windows)
17039 {
17040 if (window->Viewport != viewport)
17041 continue;
17042 window->Viewport = NULL;
17043 window->ViewportOwned = false;
17044 }
17045 if (viewport == g.MouseLastHoveredViewport)
17046 g.MouseLastHoveredViewport = NULL;
17047
17048 // Destroy
17049 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
17050 DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
17051 IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
17052 IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
17053 g.Viewports.erase(g.Viewports.Data + viewport->Idx);
17054 IM_DELETE(viewport);
17055 }
17056
17057 // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
17058 static void ImGui::WindowSelectViewport(ImGuiWindow* window)
17059 {
17060 ImGuiContext& g = *GImGui;
17061 ImGuiWindowFlags flags = window->Flags;
17062 window->ViewportAllowPlatformMonitorExtend = -1;
17063
17064 // Restore main viewport if multi-viewport is not supported by the backend
17065 ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
17066 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
17067 {
17068 SetWindowViewport(window, main_viewport);
17069 return;
17070 }
17071 window->ViewportOwned = false;
17072
17073 // Appearing popups reset their viewport so they can inherit again
17074 if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
17075 {
17076 window->Viewport = NULL;
17077 window->ViewportId = 0;
17078 }
17079
17080 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport) == 0)
17081 {
17082 // By default inherit from parent window
17083 if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
17084 window->Viewport = window->ParentWindow->Viewport;
17085
17086 // 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
17087 if (window->Viewport == NULL && window->ViewportId != 0)
17088 {
17089 window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
17090 if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
17091 window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
17092 }
17093 }
17094
17095 bool lock_viewport = false;
17096 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasViewport)
17097 {
17098 // Code explicitly request a viewport
17099 window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
17100 window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
17101 if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
17102 {
17103 window->Viewport->Window = window;
17104 window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
17105 }
17106 lock_viewport = true;
17107 }
17108 else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
17109 {
17110 // Always inherit viewport from parent window
17111 if (window->DockNode && window->DockNode->HostWindow)
17112 IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
17113 window->Viewport = window->ParentWindow->Viewport;
17114 }
17115 else if (window->DockNode && window->DockNode->HostWindow)
17116 {
17117 // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
17118 window->Viewport = window->DockNode->HostWindow->Viewport;
17119 }
17120 else if (flags & ImGuiWindowFlags_Tooltip)
17121 {
17122 window->Viewport = g.MouseViewport;
17123 }
17124 else if (GetWindowAlwaysWantOwnViewport(window))
17125 {
17126 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
17127 }
17128 else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
17129 {
17130 if (window->Viewport != NULL && window->Viewport->Window == window)
17131 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
17132 }
17133 else
17134 {
17135 // Merge into host viewport?
17136 // We cannot test window->ViewportOwned as it set lower in the function.
17137 // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
17138 bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
17139 if (try_to_merge_into_host_viewport)
17140 UpdateTryMergeWindowIntoHostViewports(window);
17141 }
17142
17143 // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
17144 if (window->Viewport == NULL)
17145 if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
17146 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
17147
17148 // Mark window as allowed to protrude outside of its viewport and into the current monitor
17149 if (!lock_viewport)
17150 {
17151 if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
17152 {
17153 // We need to take account of the possibility that mouse may become invalid.
17154 // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
17155 ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
17156 bool use_mouse_ref = (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !g.NavWindow);
17157 bool mouse_valid = IsMousePosValid(&mouse_ref);
17158 if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
17159 window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
17160 else
17161 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
17162 }
17163 else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
17164 {
17165 // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
17166 const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
17167 if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
17168 {
17169 // Steal/transfer ownership
17170 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
17171 window->Viewport->Window = window;
17172 window->Viewport->ID = window->ID;
17173 window->Viewport->LastNameHash = 0;
17174 }
17175 else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
17176 {
17177 // New viewport
17178 window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
17179 }
17180 }
17181 else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
17182 {
17183 // Regular (non-child, non-popup) windows by default are also allowed to protrude
17184 // Child windows are kept contained within their parent.
17185 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
17186 }
17187 }
17188
17189 // Update flags
17190 window->ViewportOwned = (window == window->Viewport->Window);
17191 window->ViewportId = window->Viewport->ID;
17192
17193 // If the OS window has a title bar, hide our imgui title bar
17194 //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
17195 // window->Flags |= ImGuiWindowFlags_NoTitleBar;
17196 }
17197
17198 void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
17199 {
17200 ImGuiContext& g = *GImGui;
17201
17202 bool viewport_rect_changed = false;
17203
17204 // Synchronize window --> viewport in most situations
17205 // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
17206 if (window->Viewport->PlatformRequestMove)
17207 {
17208 window->Pos = window->Viewport->Pos;
17209 MarkIniSettingsDirty(window);
17210 }
17211 else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
17212 {
17213 viewport_rect_changed = true;
17214 window->Viewport->Pos = window->Pos;
17215 }
17216
17217 if (window->Viewport->PlatformRequestResize)
17218 {
17219 window->Size = window->SizeFull = window->Viewport->Size;
17220 MarkIniSettingsDirty(window);
17221 }
17222 else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
17223 {
17224 viewport_rect_changed = true;
17225 window->Viewport->Size = window->Size;
17226 }
17227 window->Viewport->UpdateWorkRect();
17228
17229 // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
17230 // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
17231 if (viewport_rect_changed)
17232 UpdateViewportPlatformMonitor(window->Viewport);
17233
17234 // Update common viewport flags
17235 const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
17236 ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
17237 ImGuiWindowFlags window_flags = window->Flags;
17238 const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
17239 const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
17240 if (window_flags & ImGuiWindowFlags_Tooltip)
17241 viewport_flags |= ImGuiViewportFlags_TopMost;
17242 if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
17243 viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
17244 if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
17245 viewport_flags |= ImGuiViewportFlags_NoDecoration;
17246
17247 // Not correct to set modal as topmost because:
17248 // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
17249 // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
17250 //if (flags & ImGuiWindowFlags_Modal)
17251 // viewport_flags |= ImGuiViewportFlags_TopMost;
17252
17253 // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
17254 // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
17255 // 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,
17256 // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
17257 if (is_short_lived_floating_window && !is_modal)
17258 viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
17259
17260 // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
17261 if (window->WindowClass.ViewportFlagsOverrideSet)
17262 viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
17263 if (window->WindowClass.ViewportFlagsOverrideClear)
17264 viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
17265
17266 // We can also tell the backend that clearing the platform window won't be necessary,
17267 // as our window background is filling the viewport and we have disabled BgAlpha.
17268 // FIXME: Work on support for per-viewport transparency (#2766)
17269 if (!(window_flags & ImGuiWindowFlags_NoBackground))
17270 viewport_flags |= ImGuiViewportFlags_NoRendererClear;
17271
17272 window->Viewport->Flags = viewport_flags;
17273
17274 // Update parent viewport ID
17275 // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
17276 if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
17277 window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
17278 else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
17279 window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
17280 else
17281 window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
17282 }
17283
17284 // Called by user at the end of the main loop, after EndFrame()
17285 // This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
17286 void ImGui::UpdatePlatformWindows()
17287 {
17288 ImGuiContext& g = *GImGui;
17289 IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
17290 IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
17291 g.FrameCountPlatformEnded = g.FrameCount;
17292 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
17293 return;
17294
17295 // Create/resize/destroy platform windows to match each active viewport.
17296 // Skip the main viewport (index 0), which is always fully handled by the application!
17297 for (int i = 1; i < g.Viewports.Size; i++)
17298 {
17299 ImGuiViewportP* viewport = g.Viewports[i];
17300
17301 // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
17302 // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
17303 bool destroy_platform_window = false;
17304 destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
17305 destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
17306 if (destroy_platform_window)
17307 {
17308 DestroyPlatformWindow(viewport);
17309 continue;
17310 }
17311
17312 // New windows that appears directly in a new viewport won't always have a size on their first frame
17313 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
17314 continue;
17315
17316 // Create window
17317 const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
17318 if (is_new_platform_window)
17319 {
17320 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
17321 g.PlatformIO.Platform_CreateWindow(viewport);
17322 if (g.PlatformIO.Renderer_CreateWindow != NULL)
17323 g.PlatformIO.Renderer_CreateWindow(viewport);
17324 g.PlatformWindowsCreatedCount++;
17325 viewport->LastNameHash = 0;
17326 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?)
17327 viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
17328 viewport->PlatformWindowCreated = true;
17329 }
17330
17331 // Apply Position and Size (from ImGui to Platform/Renderer backends)
17332 if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
17333 g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
17334 if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
17335 g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
17336 if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
17337 g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
17338 viewport->LastPlatformPos = viewport->Pos;
17339 viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
17340
17341 // Update title bar (if it changed)
17342 if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
17343 {
17344 const char* title_begin = window_for_title->Name;
17345 char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
17346 const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
17347 if (viewport->LastNameHash != title_hash)
17348 {
17349 char title_end_backup_c = *title_end;
17350 *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
17351 g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
17352 *title_end = title_end_backup_c;
17353 viewport->LastNameHash = title_hash;
17354 }
17355 }
17356
17357 // Update alpha (if it changed)
17358 if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
17359 g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
17360 viewport->LastAlpha = viewport->Alpha;
17361
17362 // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
17363 if (g.PlatformIO.Platform_UpdateWindow)
17364 g.PlatformIO.Platform_UpdateWindow(viewport);
17365
17366 if (is_new_platform_window)
17367 {
17368 // 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)
17369 if (g.FrameCount < 3)
17370 viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
17371
17372 // Show window
17373 g.PlatformIO.Platform_ShowWindow(viewport);
17374
17375 // Even without focus, we assume the window becomes front-most.
17376 // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
17377 if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
17378 viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
17379 }
17380
17381 // Clear request flags
17382 viewport->ClearRequestFlags();
17383 }
17384 }
17385
17386 // This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
17387 // Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
17388 // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
17389 //
17390 // ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
17391 // for (int i = 1; i < platform_io.Viewports.Size; i++)
17392 // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
17393 // MyRenderFunction(platform_io.Viewports[i], my_args);
17394 // for (int i = 1; i < platform_io.Viewports.Size; i++)
17395 // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
17396 // MySwapBufferFunction(platform_io.Viewports[i], my_args);
17397 //
17398 void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
17399 {
17400 // Skip the main viewport (index 0), which is always fully handled by the application!
17401 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
17402 for (int i = 1; i < platform_io.Viewports.Size; i++)
17403 {
17404 ImGuiViewport* viewport = platform_io.Viewports[i];
17405 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
17406 continue;
17407 if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
17408 if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
17409 }
17410 for (int i = 1; i < platform_io.Viewports.Size; i++)
17411 {
17412 ImGuiViewport* viewport = platform_io.Viewports[i];
17413 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
17414 continue;
17415 if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
17416 if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
17417 }
17418 }
17419
17420 static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
17421 {
17422 ImGuiContext& g = *GImGui;
17423 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
17424 {
17425 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
17426 if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
17427 return monitor_n;
17428 }
17429 return -1;
17430 }
17431
17432 // Search for the monitor with the largest intersection area with the given rectangle
17433 // We generally try to avoid searching loops but the monitor count should be very small here
17434 // FIXME-OPT: We could test the last monitor used for that viewport first, and early
17435 static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
17436 {
17437 ImGuiContext& g = *GImGui;
17438
17439 const int monitor_count = g.PlatformIO.Monitors.Size;
17440 if (monitor_count <= 1)
17441 return monitor_count - 1;
17442
17443 // 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.
17444 // This is necessary for tooltips which always resize down to zero at first.
17445 const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
17446 int best_monitor_n = 0; // Default to the first monitor as fallback
17447 float best_monitor_surface = 0.001f;
17448
17449 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
17450 {
17451 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
17452 const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
17453 if (monitor_rect.Contains(rect))
17454 return monitor_n;
17455 ImRect overlapping_rect = rect;
17456 overlapping_rect.ClipWithFull(monitor_rect);
17457 float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
17458 if (overlapping_surface < best_monitor_surface)
17459 continue;
17460 best_monitor_surface = overlapping_surface;
17461 best_monitor_n = monitor_n;
17462 }
17463 return best_monitor_n;
17464 }
17465
17466 // Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
17467 static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
17468 {
17469 viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
17470 }
17471
17472 // Return value is always != NULL, but don't hold on it across frames.
17473 const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
17474 {
17475 ImGuiContext& g = *GImGui;
17476 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
17477 int monitor_idx = viewport->PlatformMonitor;
17478 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
17479 return &g.PlatformIO.Monitors[monitor_idx];
17480 return &g.FallbackMonitor;
17481 }
17482
17483 void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
17484 {
17485 ImGuiContext& g = *GImGui;
17486 if (viewport->PlatformWindowCreated)
17487 {
17488 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
17489 if (g.PlatformIO.Renderer_DestroyWindow)
17490 g.PlatformIO.Renderer_DestroyWindow(viewport);
17491 if (g.PlatformIO.Platform_DestroyWindow)
17492 g.PlatformIO.Platform_DestroyWindow(viewport);
17493 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
17494
17495 // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
17496 // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
17497 if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
17498 viewport->PlatformWindowCreated = false;
17499 }
17500 else
17501 {
17502 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
17503 }
17504 viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
17505 viewport->ClearRequestFlags();
17506 }
17507
17508 void ImGui::DestroyPlatformWindows()
17509 {
17510 // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
17511 // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
17512 // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
17513 // code to operator a consistent manner.
17514 // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
17515 // crashing if it doesn't have data stored.
17516 ImGuiContext& g = *GImGui;
17517 for (ImGuiViewportP* viewport : g.Viewports)
17518 DestroyPlatformWindow(viewport);
17519 }
17520
17521
17522 //-----------------------------------------------------------------------------
17523 // [SECTION] DOCKING
17524 //-----------------------------------------------------------------------------
17525 // Docking: Internal Types
17526 // Docking: Forward Declarations
17527 // Docking: ImGuiDockContext
17528 // Docking: ImGuiDockContext Docking/Undocking functions
17529 // Docking: ImGuiDockNode
17530 // Docking: ImGuiDockNode Tree manipulation functions
17531 // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17532 // Docking: Builder Functions
17533 // Docking: Begin/End Support Functions (called from Begin/End)
17534 // Docking: Settings
17535 //-----------------------------------------------------------------------------
17536
17537 //-----------------------------------------------------------------------------
17538 // Typical Docking call flow: (root level is generally public API):
17539 //-----------------------------------------------------------------------------
17540 // - NewFrame() new dear imgui frame
17541 // | DockContextNewFrameUpdateUndocking() - process queued undocking requests
17542 // | - DockContextProcessUndockWindow() - process one window undocking request
17543 // | - DockContextProcessUndockNode() - process one whole node undocking request
17544 // | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes
17545 // | - update g.HoveredDockNode - [debug] update node hovered by mouse
17546 // | - DockContextProcessDock() - process one docking request
17547 // | - DockNodeUpdate()
17548 // | - DockNodeUpdateForRootNode()
17549 // | - DockNodeUpdateFlagsAndCollapse()
17550 // | - DockNodeFindInfo()
17551 // | - destroy unused node or tab bar
17552 // | - create dock node host window
17553 // | - Begin() etc.
17554 // | - DockNodeStartMouseMovingWindow()
17555 // | - DockNodeTreeUpdatePosSize()
17556 // | - DockNodeTreeUpdateSplitter()
17557 // | - draw node background
17558 // | - DockNodeUpdateTabBar() - create/update tab bar for a docking node
17559 // | - DockNodeAddTabBar()
17560 // | - DockNodeWindowMenuUpdate()
17561 // | - DockNodeCalcTabBarLayout()
17562 // | - BeginTabBarEx()
17563 // | - TabItemEx() calls
17564 // | - EndTabBar()
17565 // | - BeginDockableDragDropTarget()
17566 // | - DockNodeUpdate() - recurse into child nodes...
17567 //-----------------------------------------------------------------------------
17568 // - DockSpace() user submit a dockspace into a window
17569 // | Begin(Child) - create a child window
17570 // | DockNodeUpdate() - call main dock node update function
17571 // | End(Child)
17572 // | ItemSize()
17573 //-----------------------------------------------------------------------------
17574 // - Begin()
17575 // | BeginDocked()
17576 // | BeginDockableDragDropSource()
17577 // | BeginDockableDragDropTarget()
17578 // | - DockNodePreviewDockRender()
17579 //-----------------------------------------------------------------------------
17580 // - EndFrame()
17581 // | DockContextEndFrame()
17582 //-----------------------------------------------------------------------------
17583
17584 //-----------------------------------------------------------------------------
17585 // Docking: Internal Types
17586 //-----------------------------------------------------------------------------
17587 // - ImGuiDockRequestType
17588 // - ImGuiDockRequest
17589 // - ImGuiDockPreviewData
17590 // - ImGuiDockNodeSettings
17591 // - ImGuiDockContext
17592 //-----------------------------------------------------------------------------
17593
17594 enum ImGuiDockRequestType
17595 {
17596 ImGuiDockRequestType_None = 0,
17597 ImGuiDockRequestType_Dock,
17598 ImGuiDockRequestType_Undock,
17599 ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
17600 };
17601
17602 struct ImGuiDockRequest
17603 {
17604 ImGuiDockRequestType Type;
17605 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)
17606 ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
17607 ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
17608 ImGuiDir DockSplitDir;
17609 float DockSplitRatio;
17610 bool DockSplitOuter;
17611 ImGuiWindow* UndockTargetWindow;
17612 ImGuiDockNode* UndockTargetNode;
17613
17614 ImGuiDockRequest()
17615 {
17616 Type = ImGuiDockRequestType_None;
17617 DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
17618 DockTargetNode = UndockTargetNode = NULL;
17619 DockSplitDir = ImGuiDir_None;
17620 DockSplitRatio = 0.5f;
17621 DockSplitOuter = false;
17622 }
17623 };
17624
17625 struct ImGuiDockPreviewData
17626 {
17627 ImGuiDockNode FutureNode;
17628 bool IsDropAllowed;
17629 bool IsCenterAvailable;
17630 bool IsSidesAvailable; // Hold your breath, grammar freaks..
17631 bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
17632 ImGuiDockNode* SplitNode;
17633 ImGuiDir SplitDir;
17634 float SplitRatio;
17635 ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
17636
17637 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); }
17638 };
17639
17640 // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
17641 struct ImGuiDockNodeSettings
17642 {
17643 ImGuiID ID;
17644 ImGuiID ParentNodeId;
17645 ImGuiID ParentWindowId;
17646 ImGuiID SelectedTabId;
17647 signed char SplitAxis;
17648 char Depth;
17649 ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
17650 ImVec2ih Pos;
17651 ImVec2ih Size;
17652 ImVec2ih SizeRef;
17653 ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
17654 };
17655
17656 //-----------------------------------------------------------------------------
17657 // Docking: Forward Declarations
17658 //-----------------------------------------------------------------------------
17659
17660 namespace ImGui
17661 {
17662 // ImGuiDockContext
17663 static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
17664 static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
17665 static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
17666 static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
17667 static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
17668 static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
17669 static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
17670 static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
17671
17672 // ImGuiDockNode
17673 static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
17674 static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
17675 static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
17676 static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
17677 static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
17678 static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
17679 static void DockNodeHideHostWindow(ImGuiDockNode* node);
17680 static void DockNodeUpdate(ImGuiDockNode* node);
17681 static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
17682 static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
17683 static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
17684 static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
17685 static void DockNodeAddTabBar(ImGuiDockNode* node);
17686 static void DockNodeRemoveTabBar(ImGuiDockNode* node);
17687 static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
17688 static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
17689 static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
17690 static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
17691 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);
17692 static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
17693 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);
17694 static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
17695 static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
17696 static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
17697 static int DockNodeGetTabOrder(ImGuiWindow* window);
17698
17699 // ImGuiDockNode tree manipulations
17700 static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
17701 static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
17702 static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
17703 static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
17704 static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
17705 static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
17706
17707 // Settings
17708 static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
17709 static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
17710 static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
17711 static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
17712 static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
17713 static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
17714 static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
17715 static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
17716 }
17717
17718 //-----------------------------------------------------------------------------
17719 // Docking: ImGuiDockContext
17720 //-----------------------------------------------------------------------------
17721 // The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
17722 // 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.
17723 // At boot time only, we run a simple GC to remove nodes that have no references.
17724 // Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
17725 // we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
17726 // This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
17727 //-----------------------------------------------------------------------------
17728 // - DockContextInitialize()
17729 // - DockContextShutdown()
17730 // - DockContextClearNodes()
17731 // - DockContextRebuildNodes()
17732 // - DockContextNewFrameUpdateUndocking()
17733 // - DockContextNewFrameUpdateDocking()
17734 // - DockContextEndFrame()
17735 // - DockContextFindNodeByID()
17736 // - DockContextBindNodeToWindow()
17737 // - DockContextGenNodeID()
17738 // - DockContextAddNode()
17739 // - DockContextRemoveNode()
17740 // - ImGuiDockContextPruneNodeData
17741 // - DockContextPruneUnusedSettingsNodes()
17742 // - DockContextBuildNodesFromSettings()
17743 // - DockContextBuildAddWindowsToNodes()
17744 //-----------------------------------------------------------------------------
17745
17746 void ImGui::DockContextInitialize(ImGuiContext* ctx)
17747 {
17748 ImGuiContext& g = *ctx;
17749
17750 // Add .ini handle for persistent docking data
17751 ImGuiSettingsHandler ini_handler;
17752 ini_handler.TypeName = "Docking";
17753 ini_handler.TypeHash = ImHashStr("Docking");
17754 ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
17755 ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
17756 ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
17757 ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
17758 ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
17759 ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
17760 g.SettingsHandlers.push_back(ini_handler);
17761
17762 g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
17763 }
17764
17765 void ImGui::DockContextShutdown(ImGuiContext* ctx)
17766 {
17767 ImGuiDockContext* dc = &ctx->DockContext;
17768 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17769 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17770 IM_DELETE(node);
17771 }
17772
17773 void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
17774 {
17775 IM_UNUSED(ctx);
17776 IM_ASSERT(ctx == GImGui);
17777 DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
17778 DockBuilderRemoveNodeChildNodes(root_id);
17779 }
17780
17781 // [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
17782 // (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
17783 void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
17784 {
17785 ImGuiContext& g = *ctx;
17786 ImGuiDockContext* dc = &ctx->DockContext;
17787 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
17788 SaveIniSettingsToMemory();
17789 ImGuiID root_id = 0; // Rebuild all
17790 DockContextClearNodes(ctx, root_id, false);
17791 DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
17792 DockContextBuildAddWindowsToNodes(ctx, root_id);
17793 }
17794
17795 // Docking context update function, called by NewFrame()
17796 void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
17797 {
17798 ImGuiContext& g = *ctx;
17799 ImGuiDockContext* dc = &ctx->DockContext;
17800 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17801 {
17802 if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
17803 DockContextClearNodes(ctx, 0, true);
17804 return;
17805 }
17806
17807 // Setting NoSplit at runtime merges all nodes
17808 if (g.IO.ConfigDockingNoSplit)
17809 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17810 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17811 if (node->IsRootNode() && node->IsSplitNode())
17812 {
17813 DockBuilderRemoveNodeChildNodes(node->ID);
17814 //dc->WantFullRebuild = true;
17815 }
17816
17817 // Process full rebuild
17818 #if 0
17819 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
17820 dc->WantFullRebuild = true;
17821 #endif
17822 if (dc->WantFullRebuild)
17823 {
17824 DockContextRebuildNodes(ctx);
17825 dc->WantFullRebuild = false;
17826 }
17827
17828 // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
17829 for (ImGuiDockRequest& req : dc->Requests)
17830 {
17831 if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
17832 DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
17833 else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
17834 DockContextProcessUndockNode(ctx, req.UndockTargetNode);
17835 }
17836 }
17837
17838 // Docking context update function, called by NewFrame()
17839 void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
17840 {
17841 ImGuiContext& g = *ctx;
17842 ImGuiDockContext* dc = &ctx->DockContext;
17843 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17844 return;
17845
17846 // [DEBUG] Store hovered dock node.
17847 // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
17848 // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
17849 g.DebugHoveredDockNode = NULL;
17850 if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
17851 {
17852 if (hovered_window->DockNodeAsHost)
17853 g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
17854 else if (hovered_window->RootWindow->DockNode)
17855 g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
17856 }
17857
17858 // Process Docking requests
17859 for (ImGuiDockRequest& req : dc->Requests)
17860 if (req.Type == ImGuiDockRequestType_Dock)
17861 DockContextProcessDock(ctx, &req);
17862 dc->Requests.resize(0);
17863
17864 // Create windows for each automatic docking nodes
17865 // 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)
17866 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17867 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17868 if (node->IsFloatingNode())
17869 DockNodeUpdate(node);
17870 }
17871
17872 void ImGui::DockContextEndFrame(ImGuiContext* ctx)
17873 {
17874 // Draw backgrounds of node missing their window
17875 ImGuiContext& g = *ctx;
17876 ImGuiDockContext* dc = &g.DockContext;
17877 for (int n = 0; n < dc->Nodes.Data.Size; n++)
17878 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17879 if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
17880 {
17881 ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
17882 ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
17883 node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17884 node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
17885 }
17886 }
17887
17888 ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
17889 {
17890 return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
17891 }
17892
17893 ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
17894 {
17895 // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
17896 // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
17897 // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
17898 ImGuiID id = 0x0001;
17899 while (DockContextFindNodeByID(ctx, id) != NULL)
17900 id++;
17901 return id;
17902 }
17903
17904 static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
17905 {
17906 // 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.
17907 ImGuiContext& g = *ctx;
17908 if (id == 0)
17909 id = DockContextGenNodeID(ctx);
17910 else
17911 IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
17912
17913 // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
17914 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
17915 ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
17916 ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
17917 return node;
17918 }
17919
17920 static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
17921 {
17922 ImGuiContext& g = *ctx;
17923 ImGuiDockContext* dc = &ctx->DockContext;
17924
17925 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
17926 IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
17927 IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
17928 IM_ASSERT(node->Windows.Size == 0);
17929
17930 if (node->HostWindow)
17931 node->HostWindow->DockNodeAsHost = NULL;
17932
17933 ImGuiDockNode* parent_node = node->ParentNode;
17934 const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
17935 if (merge)
17936 {
17937 IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
17938 ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
17939 DockNodeTreeMerge(&g, parent_node, sibling_node);
17940 }
17941 else
17942 {
17943 for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
17944 if (parent_node->ChildNodes[n] == node)
17945 node->ParentNode->ChildNodes[n] = NULL;
17946 dc->Nodes.SetVoidPtr(node->ID, NULL);
17947 IM_DELETE(node);
17948 }
17949 }
17950
17951 static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
17952 {
17953 const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
17954 const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
17955 return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
17956 }
17957
17958 // Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
17959 struct ImGuiDockContextPruneNodeData
17960 {
17961 int CountWindows, CountChildWindows, CountChildNodes;
17962 ImGuiID RootId;
17963 ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
17964 };
17965
17966 // Garbage collect unused nodes (run once at init time)
17967 static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
17968 {
17969 ImGuiContext& g = *ctx;
17970 ImGuiDockContext* dc = &ctx->DockContext;
17971 IM_ASSERT(g.Windows.Size == 0);
17972
17973 ImPool<ImGuiDockContextPruneNodeData> pool;
17974 pool.Reserve(dc->NodesSettings.Size);
17975
17976 // Count child nodes and compute RootID
17977 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17978 {
17979 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17980 ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
17981 pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
17982 if (settings->ParentNodeId)
17983 pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
17984 }
17985
17986 // Count reference to dock ids from dockspaces
17987 // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
17988 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
17989 {
17990 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
17991 if (settings->ParentWindowId != 0)
17992 if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
17993 if (window_settings->DockId)
17994 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
17995 data->CountChildNodes++;
17996 }
17997
17998 // Count reference to dock ids from window settings
17999 // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
18000 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18001 if (ImGuiID dock_id = settings->DockId)
18002 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
18003 {
18004 data->CountWindows++;
18005 if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
18006 data_root->CountChildWindows++;
18007 }
18008
18009 // Prune
18010 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
18011 {
18012 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
18013 ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
18014 if (data == NULL || data->CountWindows > 1)
18015 continue;
18016 ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
18017
18018 bool remove = false;
18019 remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
18020 remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
18021 remove |= (data_root->CountChildWindows == 0);
18022 if (remove)
18023 {
18024 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
18025 DockSettingsRemoveNodeReferences(&settings->ID, 1);
18026 settings->ID = 0;
18027 }
18028 }
18029 }
18030
18031 static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
18032 {
18033 // Build nodes
18034 for (int node_n = 0; node_n < node_settings_count; node_n++)
18035 {
18036 ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
18037 if (settings->ID == 0)
18038 continue;
18039 ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
18040 node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
18041 node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
18042 node->Size = ImVec2(settings->Size.x, settings->Size.y);
18043 node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
18044 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
18045 if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
18046 node->ParentNode->ChildNodes[0] = node;
18047 else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
18048 node->ParentNode->ChildNodes[1] = node;
18049 node->SelectedTabId = settings->SelectedTabId;
18050 node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
18051 node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
18052
18053 // Bind host window immediately if it already exist (in case of a rebuild)
18054 // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
18055 char host_window_title[20];
18056 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18057 node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
18058 }
18059 }
18060
18061 void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
18062 {
18063 // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
18064 ImGuiContext& g = *ctx;
18065 for (ImGuiWindow* window : g.Windows)
18066 {
18067 if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
18068 continue;
18069 if (window->DockNode != NULL)
18070 continue;
18071
18072 ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18073 IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
18074 if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
18075 DockNodeAddWindow(node, window, true);
18076 }
18077 }
18078
18079 //-----------------------------------------------------------------------------
18080 // Docking: ImGuiDockContext Docking/Undocking functions
18081 //-----------------------------------------------------------------------------
18082 // - DockContextQueueDock()
18083 // - DockContextQueueUndockWindow()
18084 // - DockContextQueueUndockNode()
18085 // - DockContextQueueNotifyRemovedNode()
18086 // - DockContextProcessDock()
18087 // - DockContextProcessUndockWindow()
18088 // - DockContextProcessUndockNode()
18089 // - DockContextCalcDropPosForDocking()
18090 //-----------------------------------------------------------------------------
18091
18092 void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
18093 {
18094 IM_ASSERT(target != payload);
18095 ImGuiDockRequest req;
18096 req.Type = ImGuiDockRequestType_Dock;
18097 req.DockTargetWindow = target;
18098 req.DockTargetNode = target_node;
18099 req.DockPayload = payload;
18100 req.DockSplitDir = split_dir;
18101 req.DockSplitRatio = split_ratio;
18102 req.DockSplitOuter = split_outer;
18103 ctx->DockContext.Requests.push_back(req);
18104 }
18105
18106 void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
18107 {
18108 ImGuiDockRequest req;
18109 req.Type = ImGuiDockRequestType_Undock;
18110 req.UndockTargetWindow = window;
18111 ctx->DockContext.Requests.push_back(req);
18112 }
18113
18114 void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
18115 {
18116 ImGuiDockRequest req;
18117 req.Type = ImGuiDockRequestType_Undock;
18118 req.UndockTargetNode = node;
18119 ctx->DockContext.Requests.push_back(req);
18120 }
18121
18122 void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
18123 {
18124 ImGuiDockContext* dc = &ctx->DockContext;
18125 for (ImGuiDockRequest& req : dc->Requests)
18126 if (req.DockTargetNode == node)
18127 req.Type = ImGuiDockRequestType_None;
18128 }
18129
18130 void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
18131 {
18132 IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
18133 IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
18134
18135 ImGuiContext& g = *ctx;
18136 IM_UNUSED(g);
18137
18138 ImGuiWindow* payload_window = req->DockPayload; // Optional
18139 ImGuiWindow* target_window = req->DockTargetWindow;
18140 ImGuiDockNode* node = req->DockTargetNode;
18141 if (payload_window)
18142 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);
18143 else
18144 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
18145
18146 // Decide which Tab will be selected at the end of the operation
18147 ImGuiID next_selected_id = 0;
18148 ImGuiDockNode* payload_node = NULL;
18149 if (payload_window)
18150 {
18151 payload_node = payload_window->DockNodeAsHost;
18152 payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
18153 if (payload_node && payload_node->IsLeafNode())
18154 next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
18155 if (payload_node == NULL)
18156 next_selected_id = payload_window->TabId;
18157 }
18158
18159 // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
18160 // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
18161 if (node)
18162 IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
18163 if (node && target_window && node == target_window->DockNodeAsHost)
18164 IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
18165
18166 // Create new node and add existing window to it
18167 if (node == NULL)
18168 {
18169 node = DockContextAddNode(ctx, 0);
18170 node->Pos = target_window->Pos;
18171 node->Size = target_window->Size;
18172 if (target_window->DockNodeAsHost == NULL)
18173 {
18174 DockNodeAddWindow(node, target_window, true);
18175 node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
18176 target_window->DockIsActive = true;
18177 }
18178 }
18179
18180 ImGuiDir split_dir = req->DockSplitDir;
18181 if (split_dir != ImGuiDir_None)
18182 {
18183 // Split into two, one side will be our payload node unless we are dropping a loose window
18184 const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18185 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
18186 const float split_ratio = req->DockSplitRatio;
18187 DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
18188 ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
18189 new_node->HostWindow = node->HostWindow;
18190 node = new_node;
18191 }
18192 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
18193
18194 if (node != payload_node)
18195 {
18196 // 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!)
18197 if (node->Windows.Size > 0 && node->TabBar == NULL)
18198 {
18199 DockNodeAddTabBar(node);
18200 for (int n = 0; n < node->Windows.Size; n++)
18201 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
18202 }
18203
18204 if (payload_node != NULL)
18205 {
18206 // Transfer full payload node (with 1+ child windows or child nodes)
18207 if (payload_node->IsSplitNode())
18208 {
18209 if (node->Windows.Size > 0)
18210 {
18211 // 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.
18212 // In this situation, we move the windows of the target node into the currently visible node of the payload.
18213 // This allows us to preserve some of the underlying dock tree settings nicely.
18214 IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
18215 ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
18216 if (visible_node->TabBar)
18217 IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
18218 DockNodeMoveWindows(node, visible_node);
18219 DockNodeMoveWindows(visible_node, node);
18220 DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
18221 }
18222 if (node->IsCentralNode())
18223 {
18224 // Central node property needs to be moved to a leaf node, pick the last focused one.
18225 // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
18226 ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
18227 IM_ASSERT(last_focused_node != NULL);
18228 ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
18229 IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
18230 last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18231 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
18232 last_focused_root_node->CentralNode = last_focused_node;
18233 }
18234
18235 IM_ASSERT(node->Windows.Size == 0);
18236 DockNodeMoveChildNodes(node, payload_node);
18237 }
18238 else
18239 {
18240 const ImGuiID payload_dock_id = payload_node->ID;
18241 DockNodeMoveWindows(node, payload_node);
18242 DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
18243 }
18244 DockContextRemoveNode(ctx, payload_node, true);
18245 }
18246 else if (payload_window)
18247 {
18248 // Transfer single window
18249 const ImGuiID payload_dock_id = payload_window->DockId;
18250 node->VisibleWindow = payload_window;
18251 DockNodeAddWindow(node, payload_window, true);
18252 if (payload_dock_id != 0)
18253 DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
18254 }
18255 }
18256 else
18257 {
18258 // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
18259 node->WantHiddenTabBarUpdate = true;
18260 }
18261
18262 // Update selection immediately
18263 if (ImGuiTabBar* tab_bar = node->TabBar)
18264 tab_bar->NextSelectedTabId = next_selected_id;
18265 MarkIniSettingsDirty();
18266 }
18267
18268 // Problem:
18269 // Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
18270 // than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
18271 // with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
18272 // due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
18273 // Solution:
18274 // When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
18275 // Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
18276 static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
18277 {
18278 if (ref_viewport == NULL)
18279 return size;
18280
18281 ImGuiContext& g = *GImGui;
18282 ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
18283 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
18284 {
18285 const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
18286 max_size = ImTrunc(monitor->WorkSize * 0.90f);
18287 }
18288 return ImMin(size, max_size);
18289 }
18290
18291 void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
18292 {
18293 ImGuiContext& g = *ctx;
18294 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
18295 if (window->DockNode)
18296 DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
18297 else
18298 window->DockId = 0;
18299 window->Collapsed = false;
18300 window->DockIsActive = false;
18301 window->DockNodeIsVisible = window->DockTabIsVisible = false;
18302 window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
18303
18304 MarkIniSettingsDirty();
18305 }
18306
18307 void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
18308 {
18309 ImGuiContext& g = *ctx;
18310 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
18311 IM_ASSERT(node->IsLeafNode());
18312 IM_ASSERT(node->Windows.Size >= 1);
18313
18314 if (node->IsRootNode() || node->IsCentralNode())
18315 {
18316 // 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.
18317 ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
18318 new_node->Pos = node->Pos;
18319 new_node->Size = node->Size;
18320 new_node->SizeRef = node->SizeRef;
18321 DockNodeMoveWindows(new_node, node);
18322 DockSettingsRenameNodeReferences(node->ID, new_node->ID);
18323 node = new_node;
18324 }
18325 else
18326 {
18327 // Otherwise extract our node and merge our sibling back into the parent node.
18328 IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
18329 int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
18330 node->ParentNode->ChildNodes[index_in_parent] = NULL;
18331 DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
18332 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
18333 node->ParentNode = NULL;
18334 }
18335 for (ImGuiWindow* window : node->Windows)
18336 {
18337 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
18338 if (window->ParentWindow)
18339 window->ParentWindow->DC.ChildWindows.find_erase(window);
18340 UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
18341 }
18342 node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18343 node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
18344 node->WantMouseMove = true;
18345 MarkIniSettingsDirty();
18346 }
18347
18348 // This is mostly used for automation.
18349 bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
18350 {
18351 if (target != NULL && target_node == NULL)
18352 target_node = target->DockNode;
18353
18354 // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
18355 // (which would be functionally identical) we only show the outer one. Reflect this here.
18356 if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
18357 split_outer = true;
18358 ImGuiDockPreviewData split_data;
18359 DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
18360 if (split_data.DropRectsDraw[split_dir+1].IsInverted())
18361 return false;
18362 *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
18363 return true;
18364 }
18365
18366 //-----------------------------------------------------------------------------
18367 // Docking: ImGuiDockNode
18368 //-----------------------------------------------------------------------------
18369 // - DockNodeGetTabOrder()
18370 // - DockNodeAddWindow()
18371 // - DockNodeRemoveWindow()
18372 // - DockNodeMoveChildNodes()
18373 // - DockNodeMoveWindows()
18374 // - DockNodeApplyPosSizeToWindows()
18375 // - DockNodeHideHostWindow()
18376 // - ImGuiDockNodeFindInfoResults
18377 // - DockNodeFindInfo()
18378 // - DockNodeFindWindowByID()
18379 // - DockNodeUpdateFlagsAndCollapse()
18380 // - DockNodeUpdateHasCentralNodeFlag()
18381 // - DockNodeUpdateVisibleFlag()
18382 // - DockNodeStartMouseMovingWindow()
18383 // - DockNodeUpdate()
18384 // - DockNodeUpdateWindowMenu()
18385 // - DockNodeBeginAmendTabBar()
18386 // - DockNodeEndAmendTabBar()
18387 // - DockNodeUpdateTabBar()
18388 // - DockNodeAddTabBar()
18389 // - DockNodeRemoveTabBar()
18390 // - DockNodeIsDropAllowedOne()
18391 // - DockNodeIsDropAllowed()
18392 // - DockNodeCalcTabBarLayout()
18393 // - DockNodeCalcSplitRects()
18394 // - DockNodeCalcDropRectsAndTestMousePos()
18395 // - DockNodePreviewDockSetup()
18396 // - DockNodePreviewDockRender()
18397 //-----------------------------------------------------------------------------
18398
18399 ImGuiDockNode::ImGuiDockNode(ImGuiID id)
18400 {
18401 ID = id;
18402 SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
18403 ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
18404 TabBar = NULL;
18405 SplitAxis = ImGuiAxis_None;
18406
18407 State = ImGuiDockNodeState_Unknown;
18408 LastBgColor = IM_COL32_WHITE;
18409 HostWindow = VisibleWindow = NULL;
18410 CentralNode = OnlyNodeWithWindows = NULL;
18411 CountNodeWithWindows = 0;
18412 LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
18413 LastFocusedNodeId = 0;
18414 SelectedTabId = 0;
18415 WantCloseTabId = 0;
18416 RefViewportId = 0;
18417 AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
18418 AuthorityForViewport = ImGuiDataAuthority_Auto;
18419 IsVisible = true;
18420 IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
18421 IsBgDrawnThisFrame = false;
18422 WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
18423 }
18424
18425 ImGuiDockNode::~ImGuiDockNode()
18426 {
18427 IM_DELETE(TabBar);
18428 TabBar = NULL;
18429 ChildNodes[0] = ChildNodes[1] = NULL;
18430 }
18431
18432 int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
18433 {
18434 ImGuiTabBar* tab_bar = window->DockNode->TabBar;
18435 if (tab_bar == NULL)
18436 return -1;
18437 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
18438 return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
18439 }
18440
18441 static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
18442 {
18443 window->Hidden = true;
18444 window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
18445 }
18446
18447 static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
18448 {
18449 ImGuiContext& g = *GImGui; (void)g;
18450 if (window->DockNode)
18451 {
18452 // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
18453 IM_ASSERT(window->DockNode->ID != node->ID);
18454 DockNodeRemoveWindow(window->DockNode, window, 0);
18455 }
18456 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
18457 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
18458
18459 // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
18460 // 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).
18461 // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
18462 if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
18463 DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
18464
18465 node->Windows.push_back(window);
18466 node->WantHiddenTabBarUpdate = true;
18467 window->DockNode = node;
18468 window->DockId = node->ID;
18469 window->DockIsActive = (node->Windows.Size > 1);
18470 window->DockTabWantClose = false;
18471
18472 // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
18473 // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
18474 if (node->HostWindow == NULL && node->IsFloatingNode())
18475 {
18476 if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
18477 node->AuthorityForPos = ImGuiDataAuthority_Window;
18478 if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
18479 node->AuthorityForSize = ImGuiDataAuthority_Window;
18480 if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
18481 node->AuthorityForViewport = ImGuiDataAuthority_Window;
18482 }
18483
18484 // Add to tab bar if requested
18485 if (add_to_tab_bar)
18486 {
18487 if (node->TabBar == NULL)
18488 {
18489 DockNodeAddTabBar(node);
18490 node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
18491
18492 // Add existing windows
18493 for (int n = 0; n < node->Windows.Size - 1; n++)
18494 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
18495 }
18496 TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
18497 }
18498
18499 DockNodeUpdateVisibleFlag(node);
18500
18501 // 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.
18502 if (node->HostWindow)
18503 UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
18504 }
18505
18506 static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
18507 {
18508 ImGuiContext& g = *GImGui;
18509 IM_ASSERT(window->DockNode == node);
18510 //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
18511 //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
18512 IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
18513 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
18514
18515 window->DockNode = NULL;
18516 window->DockIsActive = window->DockTabWantClose = false;
18517 window->DockId = save_dock_id;
18518 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
18519 if (window->ParentWindow)
18520 window->ParentWindow->DC.ChildWindows.find_erase(window);
18521 UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
18522
18523 if (node->HostWindow && node->HostWindow->ViewportOwned)
18524 {
18525 // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
18526 // But mid-frame, if we clear viewport we need to mark window as hidden as well.
18527 window->Viewport = NULL;
18528 window->ViewportId = 0;
18529 window->ViewportOwned = false;
18530 window->Hidden = true;
18531 }
18532
18533 // Remove window
18534 bool erased = false;
18535 for (int n = 0; n < node->Windows.Size; n++)
18536 if (node->Windows[n] == window)
18537 {
18538 node->Windows.erase(node->Windows.Data + n);
18539 erased = true;
18540 break;
18541 }
18542 if (!erased)
18543 IM_ASSERT(erased);
18544 if (node->VisibleWindow == window)
18545 node->VisibleWindow = NULL;
18546
18547 // Remove tab and possibly tab bar
18548 node->WantHiddenTabBarUpdate = true;
18549 if (node->TabBar)
18550 {
18551 TabBarRemoveTab(node->TabBar, window->TabId);
18552 const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
18553 if (node->Windows.Size < tab_count_threshold_for_tab_bar)
18554 DockNodeRemoveTabBar(node);
18555 }
18556
18557 if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
18558 {
18559 // Automatic dock node delete themselves if they are not holding at least one tab
18560 DockContextRemoveNode(&g, node, true);
18561 return;
18562 }
18563
18564 if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
18565 {
18566 ImGuiWindow* remaining_window = node->Windows[0];
18567 // Note: we used to transport viewport ownership here.
18568 remaining_window->Collapsed = node->HostWindow->Collapsed;
18569 }
18570
18571 // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
18572 DockNodeUpdateVisibleFlag(node);
18573 }
18574
18575 static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
18576 {
18577 IM_ASSERT(dst_node->Windows.Size == 0);
18578 dst_node->ChildNodes[0] = src_node->ChildNodes[0];
18579 dst_node->ChildNodes[1] = src_node->ChildNodes[1];
18580 if (dst_node->ChildNodes[0])
18581 dst_node->ChildNodes[0]->ParentNode = dst_node;
18582 if (dst_node->ChildNodes[1])
18583 dst_node->ChildNodes[1]->ParentNode = dst_node;
18584 dst_node->SplitAxis = src_node->SplitAxis;
18585 dst_node->SizeRef = src_node->SizeRef;
18586 src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
18587 }
18588
18589 static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
18590 {
18591 // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
18592 IM_ASSERT(src_node && dst_node && dst_node != src_node);
18593 ImGuiTabBar* src_tab_bar = src_node->TabBar;
18594 if (src_tab_bar != NULL)
18595 IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
18596
18597 // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
18598 bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
18599 if (move_tab_bar)
18600 {
18601 dst_node->TabBar = src_node->TabBar;
18602 src_node->TabBar = NULL;
18603 }
18604
18605 // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
18606 for (ImGuiWindow* window : src_node->Windows)
18607 {
18608 window->DockNode = NULL;
18609 window->DockIsActive = false;
18610 DockNodeAddWindow(dst_node, window, !move_tab_bar);
18611 }
18612 src_node->Windows.clear();
18613
18614 if (!move_tab_bar && src_node->TabBar)
18615 {
18616 if (dst_node->TabBar)
18617 dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
18618 DockNodeRemoveTabBar(src_node);
18619 }
18620 }
18621
18622 static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
18623 {
18624 for (ImGuiWindow* window : node->Windows)
18625 {
18626 SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
18627 SetWindowSize(window, node->Size, ImGuiCond_Always);
18628 }
18629 }
18630
18631 static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
18632 {
18633 if (node->HostWindow)
18634 {
18635 if (node->HostWindow->DockNodeAsHost == node)
18636 node->HostWindow->DockNodeAsHost = NULL;
18637 node->HostWindow = NULL;
18638 }
18639
18640 if (node->Windows.Size == 1)
18641 {
18642 node->VisibleWindow = node->Windows[0];
18643 node->Windows[0]->DockIsActive = false;
18644 }
18645
18646 if (node->TabBar)
18647 DockNodeRemoveTabBar(node);
18648 }
18649
18650 // Search function called once by root node in DockNodeUpdate()
18651 struct ImGuiDockNodeTreeInfo
18652 {
18653 ImGuiDockNode* CentralNode;
18654 ImGuiDockNode* FirstNodeWithWindows;
18655 int CountNodesWithWindows;
18656 //ImGuiWindowClass WindowClassForMerges;
18657
18658 ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
18659 };
18660
18661 static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
18662 {
18663 if (node->Windows.Size > 0)
18664 {
18665 if (info->FirstNodeWithWindows == NULL)
18666 info->FirstNodeWithWindows = node;
18667 info->CountNodesWithWindows++;
18668 }
18669 if (node->IsCentralNode())
18670 {
18671 IM_ASSERT(info->CentralNode == NULL); // Should be only one
18672 IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
18673 info->CentralNode = node;
18674 }
18675 if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
18676 return;
18677 if (node->ChildNodes[0])
18678 DockNodeFindInfo(node->ChildNodes[0], info);
18679 if (node->ChildNodes[1])
18680 DockNodeFindInfo(node->ChildNodes[1], info);
18681 }
18682
18683 static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
18684 {
18685 IM_ASSERT(id != 0);
18686 for (ImGuiWindow* window : node->Windows)
18687 if (window->ID == id)
18688 return window;
18689 return NULL;
18690 }
18691
18692 // - Remove inactive windows/nodes.
18693 // - Update visibility flag.
18694 static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
18695 {
18696 ImGuiContext& g = *GImGui;
18697 IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
18698
18699 // Inherit most flags
18700 if (node->ParentNode)
18701 node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18702
18703 // Recurse into children
18704 // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
18705 // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
18706 // 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)
18707 node->HasCentralNodeChild = false;
18708 if (node->ChildNodes[0])
18709 DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
18710 if (node->ChildNodes[1])
18711 DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
18712
18713 // Remove inactive windows, collapse nodes
18714 // Merge node flags overrides stored in windows
18715 node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18716 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18717 {
18718 ImGuiWindow* window = node->Windows[window_n];
18719 IM_ASSERT(window->DockNode == node);
18720
18721 bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
18722 bool remove = false;
18723 remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
18724 remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
18725 remove |= (window->DockTabWantClose);
18726 if (remove)
18727 {
18728 window->DockTabWantClose = false;
18729 if (node->Windows.Size == 1 && !node->IsCentralNode())
18730 {
18731 DockNodeHideHostWindow(node);
18732 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
18733 DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
18734 return;
18735 }
18736 DockNodeRemoveWindow(node, window, node->ID);
18737 window_n--;
18738 continue;
18739 }
18740
18741 // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
18742 //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
18743 node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
18744 }
18745 node->UpdateMergedFlags();
18746
18747 // Auto-hide tab bar option
18748 ImGuiDockNodeFlags node_flags = node->MergedFlags;
18749 if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
18750 node->WantHiddenTabBarToggle = true;
18751 node->WantHiddenTabBarUpdate = false;
18752
18753 // Cancel toggling if we know our tab bar is enforced to be hidden at all times
18754 if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
18755 node->WantHiddenTabBarToggle = false;
18756
18757 // Apply toggles at a single point of the frame (here!)
18758 if (node->Windows.Size > 1)
18759 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
18760 else if (node->WantHiddenTabBarToggle)
18761 node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
18762 node->WantHiddenTabBarToggle = false;
18763
18764 DockNodeUpdateVisibleFlag(node);
18765 }
18766
18767 // This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
18768 static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
18769 {
18770 node->HasCentralNodeChild = false;
18771 if (node->ChildNodes[0])
18772 DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
18773 if (node->ChildNodes[1])
18774 DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
18775 if (node->IsRootNode())
18776 {
18777 ImGuiDockNode* mark_node = node->CentralNode;
18778 while (mark_node)
18779 {
18780 mark_node->HasCentralNodeChild = true;
18781 mark_node = mark_node->ParentNode;
18782 }
18783 }
18784 }
18785
18786 static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
18787 {
18788 // Update visibility flag
18789 bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
18790 is_visible |= (node->Windows.Size > 0);
18791 is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
18792 is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
18793 node->IsVisible = is_visible;
18794 }
18795
18796 static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
18797 {
18798 ImGuiContext& g = *GImGui;
18799 IM_ASSERT(node->WantMouseMove == true);
18800 StartMouseMovingWindow(window);
18801 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
18802 g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
18803 node->WantMouseMove = false;
18804 }
18805
18806 // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
18807 static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
18808 {
18809 DockNodeUpdateFlagsAndCollapse(node);
18810
18811 // - Setup central node pointers
18812 // - 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!)
18813 // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
18814 ImGuiDockNodeTreeInfo info;
18815 DockNodeFindInfo(node, &info);
18816 node->CentralNode = info.CentralNode;
18817 node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
18818 node->CountNodeWithWindows = info.CountNodesWithWindows;
18819 if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
18820 node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
18821
18822 // Copy the window class from of our first window so it can be used for proper dock filtering.
18823 // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
18824 // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
18825 if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
18826 {
18827 node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
18828 for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
18829 if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
18830 {
18831 node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
18832 break;
18833 }
18834 }
18835
18836 ImGuiDockNode* mark_node = node->CentralNode;
18837 while (mark_node)
18838 {
18839 mark_node->HasCentralNodeChild = true;
18840 mark_node = mark_node->ParentNode;
18841 }
18842 }
18843
18844 static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
18845 {
18846 // Remove ourselves from any previous different host window
18847 // This can happen if a user mistakenly does (see #4295 for details):
18848 // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace
18849 // - N+1: NewFrame() // will create floating host window for that node
18850 // - N+1: DockSpace(id) // requalify node as dockspace, moving host window
18851 if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
18852 node->HostWindow->DockNodeAsHost = NULL;
18853
18854 host_window->DockNodeAsHost = node;
18855 node->HostWindow = host_window;
18856 }
18857
18858 static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
18859 {
18860 ImGuiContext& g = *GImGui;
18861 IM_ASSERT(node->LastFrameActive != g.FrameCount);
18862 node->LastFrameAlive = g.FrameCount;
18863 node->IsBgDrawnThisFrame = false;
18864
18865 node->CentralNode = node->OnlyNodeWithWindows = NULL;
18866 if (node->IsRootNode())
18867 DockNodeUpdateForRootNode(node);
18868
18869 // Remove tab bar if not needed
18870 if (node->TabBar && node->IsNoTabBar())
18871 DockNodeRemoveTabBar(node);
18872
18873 // 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)
18874 bool want_to_hide_host_window = false;
18875 if (node->IsFloatingNode())
18876 {
18877 if (node->Windows.Size <= 1 && node->IsLeafNode())
18878 if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
18879 want_to_hide_host_window = true;
18880 if (node->CountNodeWithWindows == 0)
18881 want_to_hide_host_window = true;
18882 }
18883 if (want_to_hide_host_window)
18884 {
18885 if (node->Windows.Size == 1)
18886 {
18887 // Floating window pos/size is authoritative
18888 ImGuiWindow* single_window = node->Windows[0];
18889 node->Pos = single_window->Pos;
18890 node->Size = single_window->SizeFull;
18891 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18892
18893 // Transfer focus immediately so when we revert to a regular window it is immediately selected
18894 if (node->HostWindow && g.NavWindow == node->HostWindow)
18895 FocusWindow(single_window);
18896 if (node->HostWindow)
18897 {
18898 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);
18899 single_window->Viewport = node->HostWindow->Viewport;
18900 single_window->ViewportId = node->HostWindow->ViewportId;
18901 if (node->HostWindow->ViewportOwned)
18902 {
18903 single_window->Viewport->ID = single_window->ID;
18904 single_window->Viewport->Window = single_window;
18905 single_window->ViewportOwned = true;
18906 }
18907 }
18908 node->RefViewportId = single_window->ViewportId;
18909 }
18910
18911 DockNodeHideHostWindow(node);
18912 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
18913 node->WantCloseAll = false;
18914 node->WantCloseTabId = 0;
18915 node->HasCloseButton = node->HasWindowMenuButton = false;
18916 node->LastFrameActive = g.FrameCount;
18917
18918 if (node->WantMouseMove && node->Windows.Size == 1)
18919 DockNodeStartMouseMovingWindow(node, node->Windows[0]);
18920 return;
18921 }
18922
18923 // In some circumstance we will defer creating the host window (so everything will be kept hidden),
18924 // while the expected visible window is resizing itself.
18925 // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
18926 // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
18927 // N+0: Begin(): window created (with no known size), node is created
18928 // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
18929 // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
18930 // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
18931 // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
18932 // In reality it isn't very important as user quickly ends up with size data in .ini file.
18933 if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
18934 {
18935 IM_ASSERT(node->Windows.Size > 0);
18936 ImGuiWindow* ref_window = NULL;
18937 if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
18938 ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
18939 if (ref_window == NULL)
18940 ref_window = node->Windows[0];
18941 if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
18942 {
18943 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
18944 return;
18945 }
18946 }
18947
18948 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
18949
18950 // Decide if the node will have a close button and a window menu button
18951 node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
18952 node->HasCloseButton = false;
18953 for (ImGuiWindow* window : node->Windows)
18954 {
18955 // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
18956 node->HasCloseButton |= window->HasCloseButton;
18957 window->DockIsActive = (node->Windows.Size > 1);
18958 }
18959 if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
18960 node->HasCloseButton = false;
18961
18962 // Bind or create host window
18963 ImGuiWindow* host_window = NULL;
18964 bool beginned_into_host_window = false;
18965 if (node->IsDockSpace())
18966 {
18967 // [Explicit root dockspace node]
18968 IM_ASSERT(node->HostWindow);
18969 host_window = node->HostWindow;
18970 }
18971 else
18972 {
18973 // [Automatic root or child nodes]
18974 if (node->IsRootNode() && node->IsVisible)
18975 {
18976 ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
18977
18978 // Sync Pos
18979 if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
18980 SetNextWindowPos(ref_window->Pos);
18981 else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
18982 SetNextWindowPos(node->Pos);
18983
18984 // Sync Size
18985 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
18986 SetNextWindowSize(ref_window->SizeFull);
18987 else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
18988 SetNextWindowSize(node->Size);
18989
18990 // Sync Collapsed
18991 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
18992 SetNextWindowCollapsed(ref_window->Collapsed);
18993
18994 // Sync Viewport
18995 if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
18996 SetNextWindowViewport(ref_window->ViewportId);
18997 else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
18998 SetNextWindowViewport(node->RefViewportId);
18999
19000 SetNextWindowClass(&node->WindowClass);
19001
19002 // Begin into the host window
19003 char window_label[20];
19004 DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
19005 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
19006 window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
19007 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
19008 window_flags |= ImGuiWindowFlags_NoTitleBar;
19009
19010 SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
19011 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
19012 Begin(window_label, NULL, window_flags);
19013 PopStyleVar();
19014 beginned_into_host_window = true;
19015
19016 host_window = g.CurrentWindow;
19017 DockNodeSetupHostWindow(node, host_window);
19018 host_window->DC.CursorPos = host_window->Pos;
19019 node->Pos = host_window->Pos;
19020 node->Size = host_window->Size;
19021
19022 // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
19023 // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
19024 // 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.
19025 // 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
19026 // 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
19027 // after the dock host window, losing their top-most status.
19028 if (node->HostWindow->Appearing)
19029 BringWindowToDisplayFront(node->HostWindow);
19030
19031 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
19032 }
19033 else if (node->ParentNode)
19034 {
19035 node->HostWindow = host_window = node->ParentNode->HostWindow;
19036 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
19037 }
19038 if (node->WantMouseMove && node->HostWindow)
19039 DockNodeStartMouseMovingWindow(node, node->HostWindow);
19040 }
19041 node->RefViewportId = 0; // Clear when we have a host window
19042
19043 // Update focused node (the one whose title bar is highlight) within a node tree
19044 if (node->IsSplitNode())
19045 IM_ASSERT(node->TabBar == NULL);
19046 if (node->IsRootNode())
19047 if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
19048 while (p_window != NULL && p_window->DockNode != NULL)
19049 {
19050 ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
19051 if (p_node == node)
19052 {
19053 node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
19054 break;
19055 }
19056 p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
19057 }
19058
19059 // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
19060 ImGuiDockNode* central_node = node->CentralNode;
19061 const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
19062 bool central_node_hole_register_hit_test_hole = central_node_hole;
19063 if (central_node_hole)
19064 if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
19065 if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
19066 central_node_hole_register_hit_test_hole = false;
19067 if (central_node_hole_register_hit_test_hole)
19068 {
19069 // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
19070 // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
19071 // covering passthru node we'd have a gap on the edge not covered by the hole)
19072 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
19073 ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
19074 ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
19075 ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
19076 if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += g.WindowsBorderHoverPadding; }
19077 if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= g.WindowsBorderHoverPadding; }
19078 if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += g.WindowsBorderHoverPadding; }
19079 if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= g.WindowsBorderHoverPadding; }
19080 //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
19081 if (central_node_hole && !hole_rect.IsInverted())
19082 {
19083 SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
19084 if (host_window->ParentWindow)
19085 SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
19086 }
19087 }
19088
19089 // Update position/size, process and draw resizing splitters
19090 if (node->IsRootNode() && host_window)
19091 {
19092 DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
19093 PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
19094 PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
19095 PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
19096 DockNodeTreeUpdateSplitter(node);
19097 PopStyleColor(3);
19098 }
19099
19100 // Draw empty node background (currently can only be the Central Node)
19101 if (host_window && node->IsEmpty() && node->IsVisible)
19102 {
19103 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
19104 /*node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
19105 if (node->LastBgColor != 0)
19106 host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);*/
19107 node->IsBgDrawnThisFrame = true;
19108 }
19109
19110 // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
19111 // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
19112 // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
19113 const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
19114 if (render_dockspace_bg && node->IsVisible)
19115 {
19116 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
19117 /*
19118 if (central_node_hole)
19119 RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
19120 else
19121 host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);*/
19122 }
19123
19124 // Draw and populate Tab Bar
19125 if (host_window)
19126 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
19127 if (host_window && node->Windows.Size > 0)
19128 {
19129 DockNodeUpdateTabBar(node, host_window);
19130 }
19131 else
19132 {
19133 node->WantCloseAll = false;
19134 node->WantCloseTabId = 0;
19135 node->IsFocused = false;
19136 }
19137 if (node->TabBar && node->TabBar->SelectedTabId)
19138 node->SelectedTabId = node->TabBar->SelectedTabId;
19139 else if (node->Windows.Size > 0)
19140 node->SelectedTabId = node->Windows[0]->TabId;
19141
19142 // Draw payload drop target
19143 if (host_window && node->IsVisible)
19144 if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
19145 BeginDockableDragDropTarget(host_window);
19146
19147 // We update this after DockNodeUpdateTabBar()
19148 node->LastFrameActive = g.FrameCount;
19149
19150 // Recurse into children
19151 // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
19152 if (host_window)
19153 {
19154 if (node->ChildNodes[0])
19155 DockNodeUpdate(node->ChildNodes[0]);
19156 if (node->ChildNodes[1])
19157 DockNodeUpdate(node->ChildNodes[1]);
19158
19159 // Render outer borders last (after the tab bar)
19160 if (node->IsRootNode())
19161 RenderWindowOuterBorders(host_window);
19162 }
19163
19164 // End host window
19165 if (beginned_into_host_window) //-V1020
19166 End();
19167 }
19168
19169 // 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.
19170 static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
19171 {
19172 ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
19173 ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
19174 if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
19175 return d;
19176 return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
19177 }
19178
19179 // Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
19180 // This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
19181 // Custom overrides may want to decorate, group, sort entries.
19182 // Please note those are internal structures: if you copy this expect occasional breakage.
19183 // (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
19184 void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
19185 {
19186 IM_UNUSED(ctx);
19187 if (tab_bar->Tabs.Size == 1)
19188 {
19189 // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
19190 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
19191 node->WantHiddenTabBarToggle = true;
19192 }
19193 else
19194 {
19195 // Display a selectable list of windows in this docking node
19196 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19197 {
19198 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19199 if (tab->Flags & ImGuiTabItemFlags_Button)
19200 continue;
19201 if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
19202 TabBarQueueFocus(tab_bar, tab);
19203 SameLine();
19204 Text(" ");
19205 }
19206 }
19207 }
19208
19209 static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
19210 {
19211 // Try to position the menu so it is more likely to stays within the same viewport
19212 ImGuiContext& g = *GImGui;
19213 if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
19214 SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
19215 else
19216 SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
19217 if (BeginPopup("#WindowMenu"))
19218 {
19219 node->IsFocused = true;
19220 g.DockNodeWindowMenuHandler(&g, node, tab_bar);
19221 EndPopup();
19222 }
19223 }
19224
19225 // User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
19226 bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
19227 {
19228 if (node->TabBar == NULL || node->HostWindow == NULL)
19229 return false;
19230 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19231 return false;
19232 if (node->TabBar->ID == 0)
19233 return false;
19234 Begin(node->HostWindow->Name);
19235 PushOverrideID(node->ID);
19236 bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
19237 IM_UNUSED(ret);
19238 IM_ASSERT(ret);
19239 return true;
19240 }
19241
19242 void ImGui::DockNodeEndAmendTabBar()
19243 {
19244 EndTabBar();
19245 PopID();
19246 End();
19247 }
19248
19249 static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
19250 {
19251 // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
19252 ImGuiContext& g = *GImGui;
19253 if (g.NavWindowingTarget)
19254 return (g.NavWindowingTarget->DockNode == node);
19255
19256 // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
19257 if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
19258 {
19259 // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
19260 ImGuiWindow* parent_window = g.NavWindow->RootWindow;
19261 while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
19262 parent_window = parent_window->ParentWindow->RootWindow;
19263 ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
19264 for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
19265 if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
19266 return true;
19267 }
19268 return false;
19269 }
19270
19271 // Submit the tab bar corresponding to a dock node and various housekeeping details.
19272 static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
19273 {
19274 ImGuiContext& g = *GImGui;
19275 ImGuiStyle& style = g.Style;
19276
19277 const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
19278 node->WantCloseAll = false;
19279 node->WantCloseTabId = 0;
19280
19281 // Decide if we should use a focused title bar color
19282 bool is_focused = false;
19283 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19284 if (IsDockNodeTitleBarHighlighted(node, root_node))
19285 is_focused = true;
19286
19287 // Hidden tab bar will show a triangle on the upper-left (in Begin)
19288 if (node->IsHiddenTabBar() || node->IsNoTabBar())
19289 {
19290 node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
19291 node->IsFocused = is_focused;
19292 if (is_focused)
19293 node->LastFrameFocused = g.FrameCount;
19294 if (node->VisibleWindow)
19295 {
19296 // Notify root of visible window (used to display title in OS task bar)
19297 if (is_focused || root_node->VisibleWindow == NULL)
19298 root_node->VisibleWindow = node->VisibleWindow;
19299 if (node->TabBar)
19300 node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
19301 }
19302 return;
19303 }
19304
19305 // 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
19306 bool backup_skip_item = host_window->SkipItems;
19307 if (!node->IsDockSpace())
19308 {
19309 host_window->SkipItems = false;
19310 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
19311 }
19312
19313 // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
19314 // 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,
19315 // as docked windows themselves will override the stack with their own root ID.
19316 PushOverrideID(node->ID);
19317 ImGuiTabBar* tab_bar = node->TabBar;
19318 bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
19319 if (tab_bar == NULL)
19320 {
19321 DockNodeAddTabBar(node);
19322 tab_bar = node->TabBar;
19323 }
19324
19325 ImGuiID focus_tab_id = 0;
19326 node->IsFocused = is_focused;
19327
19328 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
19329 const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
19330
19331 // In a dock node, the Collapse Button turns into the Window Menu button.
19332 // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
19333 if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
19334 {
19335 ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
19336 DockNodeWindowMenuUpdate(node, tab_bar);
19337 if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
19338 focus_tab_id = tab_bar->NextSelectedTabId;
19339 is_focused |= node->IsFocused;
19340 }
19341
19342 // Layout
19343 ImRect title_bar_rect, tab_bar_rect;
19344 ImVec2 window_menu_button_pos;
19345 ImVec2 close_button_pos;
19346 DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
19347
19348 // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
19349 const int tabs_count_old = tab_bar->Tabs.Size;
19350 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19351 {
19352 ImGuiWindow* window = node->Windows[window_n];
19353 if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
19354 TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
19355 }
19356
19357 // Title bar
19358 if (is_focused)
19359 node->LastFrameFocused = g.FrameCount;
19360 ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
19361 ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
19362 host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
19363
19364 // Docking/Collapse button
19365 if (has_window_menu_button)
19366 {
19367 if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
19368 OpenPopup("#WindowMenu");
19369 if (IsItemActive())
19370 focus_tab_id = tab_bar->SelectedTabId;
19371 if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
19372 SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
19373 }
19374
19375 // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
19376 int tabs_unsorted_start = tab_bar->Tabs.Size;
19377 for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
19378 {
19379 // 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?
19380 tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
19381 tabs_unsorted_start = tab_n;
19382 }
19383 if (tab_bar->Tabs.Size > tabs_unsorted_start)
19384 {
19385 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)" : "");
19386 for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
19387 {
19388 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19389 IM_UNUSED(tab);
19390 IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
19391 }
19392 IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
19393 if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
19394 ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
19395 }
19396
19397 // Apply NavWindow focus back to the tab bar
19398 if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
19399 tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
19400
19401 // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
19402 if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
19403 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
19404 else if (tab_bar->Tabs.Size > tabs_count_old)
19405 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
19406
19407 // Begin tab bar
19408 ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
19409 tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
19410 tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyMixed; // Enforce default policy. Since 1.92.2 this is now reasonable. May expose later if needed. (#8800, #3421)
19411 tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
19412 if (!host_window->Collapsed && is_focused)
19413 tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
19414 tab_bar->ID = GetID("#TabBar");
19415 tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
19416 tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
19417 BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
19418 //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
19419
19420 // Backup style colors
19421 ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
19422 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19423 backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
19424
19425 // Submit actual tabs
19426 node->VisibleWindow = NULL;
19427 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19428 {
19429 ImGuiWindow* window = node->Windows[window_n];
19430 if (window->LastFrameActive + 1 < g.FrameCount && node_was_active)
19431 continue; // FIXME: Not sure if that's still taken/useful.
19432
19433 ImGuiTabItemFlags tab_item_flags = 0;
19434 tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
19435 if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
19436 tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
19437 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
19438 tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
19439
19440 // Apply stored style overrides for the window
19441 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19442 g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
19443
19444 // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
19445 bool tab_open = true;
19446 TabItemEx(tab_bar, window->DisplayedName == NULL ? window->Name : window->DisplayedName, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
19447 if (!tab_open)
19448 node->WantCloseTabId = window->TabId;
19449 if (tab_bar->VisibleTabId == window->TabId)
19450 node->VisibleWindow = window;
19451
19452 // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
19453 window->DC.DockTabItemStatusFlags = g.LastItemData.StatusFlags;
19454 window->DC.DockTabItemRect = g.LastItemData.Rect;
19455
19456 // Update navigation ID on menu layer
19457 if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
19458 host_window->NavLastIds[1] = window->TabId;
19459 }
19460
19461 // Restore style colors
19462 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19463 g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
19464
19465 // Notify root of visible window (used to display title in OS task bar)
19466 if (node->VisibleWindow)
19467 if (is_focused || root_node->VisibleWindow == NULL)
19468 root_node->VisibleWindow = node->VisibleWindow;
19469
19470 // Close button (after VisibleWindow was updated)
19471 // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
19472 const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
19473 const bool close_button_is_visible = node->HasCloseButton;
19474 //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)
19475 if (close_button_is_visible)
19476 {
19477 if (!close_button_is_enabled)
19478 {
19479 PushItemFlag(ImGuiItemFlags_Disabled, true);
19480 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
19481 }
19482 if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
19483 {
19484 node->WantCloseAll = true;
19485 for (int n = 0; n < tab_bar->Tabs.Size; n++)
19486 TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
19487 }
19488 //if (IsItemActive())
19489 // focus_tab_id = tab_bar->SelectedTabId;
19490 if (!close_button_is_enabled)
19491 {
19492 PopStyleColor();
19493 PopItemFlag();
19494 }
19495 }
19496
19497 // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
19498 // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
19499 ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
19500 if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
19501 {
19502 // AllowOverlap mode required for appending into dock node tab bar,
19503 // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
19504 bool held;
19505 KeepAliveID(title_bar_id);
19506 ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
19507 if (g.HoveredId == title_bar_id)
19508 {
19509 g.LastItemData.ID = title_bar_id;
19510 }
19511 if (held)
19512 {
19513 if (IsMouseClicked(0))
19514 focus_tab_id = tab_bar->SelectedTabId;
19515
19516 // Forward moving request to selected window
19517 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
19518 StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
19519 }
19520 }
19521
19522 // Forward focus from host node to selected window
19523 //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
19524 // focus_tab_id = tab_bar->SelectedTabId;
19525
19526 // When clicked on a tab we requested focus to the docked child
19527 // This overrides the value set by "forward focus from host node to selected window".
19528 if (tab_bar->NextSelectedTabId)
19529 focus_tab_id = tab_bar->NextSelectedTabId;
19530
19531 // Apply navigation focus
19532 if (focus_tab_id != 0)
19533 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
19534 if (tab->Window)
19535 {
19536 FocusWindow(tab->Window);
19537 NavInitWindow(tab->Window, false);
19538 }
19539
19540 EndTabBar();
19541 PopID();
19542
19543 // Restore SkipItems flag
19544 if (!node->IsDockSpace())
19545 {
19546 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
19547 host_window->SkipItems = backup_skip_item;
19548 }
19549 }
19550
19551 static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
19552 {
19553 IM_ASSERT(node->TabBar == NULL);
19554 node->TabBar = IM_NEW(ImGuiTabBar);
19555 }
19556
19557 static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
19558 {
19559 if (node->TabBar == NULL)
19560 return;
19561 IM_DELETE(node->TabBar);
19562 node->TabBar = NULL;
19563 }
19564
19565 static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
19566 {
19567 if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
19568 return false;
19569
19570 ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
19571 ImGuiWindowClass* payload_class = &payload->WindowClass;
19572 if (host_class->ClassId != payload_class->ClassId)
19573 {
19574 bool pass = false;
19575 if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
19576 pass = true;
19577 if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
19578 pass = true;
19579 if (!pass)
19580 return false;
19581 }
19582
19583 // Prevent docking any window created above a popup
19584 // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
19585 // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
19586 // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
19587 // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
19588 ImGuiContext& g = *GImGui;
19589 for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
19590 if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
19591 if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window)) // Payload is created from within a popup begin stack.
19592 return false;
19593
19594 return true;
19595 }
19596
19597 static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
19598 {
19599 if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
19600 return true;
19601
19602 const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
19603 for (int payload_n = 0; payload_n < payload_count; payload_n++)
19604 {
19605 ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
19606 if (DockNodeIsDropAllowedOne(payload, host_window))
19607 return true;
19608 }
19609 return false;
19610 }
19611
19612 // window menu button == collapse button when not in a dock node.
19613 // FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
19614 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)
19615 {
19616 ImGuiContext& g = *GImGui;
19617 ImGuiStyle& style = g.Style;
19618
19619 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);
19620 if (out_title_rect) { *out_title_rect = r; }
19621
19622 r.Min.x += style.WindowBorderSize;
19623 r.Max.x -= style.WindowBorderSize;
19624
19625 float button_sz = g.FontSize;
19626 r.Min.x += style.FramePadding.x;
19627 r.Max.x -= style.FramePadding.x;
19628 ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
19629 if (node->HasCloseButton)
19630 {
19631 if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
19632 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
19633 }
19634 if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
19635 {
19636 r.Min.x += button_sz + style.ItemInnerSpacing.x;
19637 }
19638 else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
19639 {
19640 window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
19641 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
19642 }
19643 if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
19644 if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
19645 }
19646
19647 void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
19648 {
19649 ImGuiContext& g = *GImGui;
19650 const float dock_spacing = g.Style.ItemInnerSpacing.x;
19651 const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
19652 pos_new[axis ^ 1] = pos_old[axis ^ 1];
19653 size_new[axis ^ 1] = size_old[axis ^ 1];
19654
19655 // Distribute size on given axis (with a desired size or equally)
19656 const float w_avail = size_old[axis] - dock_spacing;
19657 if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
19658 {
19659 size_new[axis] = size_new_desired[axis];
19660 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
19661 }
19662 else
19663 {
19664 size_new[axis] = IM_TRUNC(w_avail * 0.5f);
19665 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
19666 }
19667
19668 // Position each node
19669 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
19670 {
19671 pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
19672 }
19673 else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
19674 {
19675 pos_new[axis] = pos_old[axis];
19676 pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
19677 }
19678 }
19679
19680 // Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
19681 bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
19682 {
19683 ImGuiContext& g = *GImGui;
19684
19685 const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
19686 const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
19687 float hs_w; // Half-size, longer axis
19688 float hs_h; // Half-size, smaller axis
19689 ImVec2 off; // Distance from edge or center
19690 if (outer_docking)
19691 {
19692 //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
19693 //hs_h = ImTrunc(hs_w * 0.15f);
19694 //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
19695 hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
19696 hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
19697 off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
19698 }
19699 else
19700 {
19701 hs_w = ImTrunc(hs_for_central_nodes);
19702 hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
19703 off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
19704 }
19705
19706 ImVec2 c = ImTrunc(parent.GetCenter());
19707 if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
19708 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); }
19709 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); }
19710 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); }
19711 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); }
19712
19713 if (test_mouse_pos == NULL)
19714 return false;
19715
19716 ImRect hit_r = out_r;
19717 if (!outer_docking)
19718 {
19719 // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
19720 hit_r.Expand(ImTrunc(hs_w * 0.30f));
19721 ImVec2 mouse_delta = (*test_mouse_pos - c);
19722 float mouse_delta_len2 = ImLengthSqr(mouse_delta);
19723 float r_threshold_center = hs_w * 1.4f;
19724 float r_threshold_sides = hs_w * (1.4f + 1.2f);
19725 if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
19726 return (dir == ImGuiDir_None);
19727 if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
19728 return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
19729 }
19730 return hit_r.Contains(*test_mouse_pos);
19731 }
19732
19733 // host_node may be NULL if the window doesn't have a DockNode already.
19734 // FIXME-DOCK: This is misnamed since it's also doing the filtering.
19735 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)
19736 {
19737 ImGuiContext& g = *GImGui;
19738
19739 // There is an edge case when docking into a dockspace which only has inactive nodes.
19740 // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
19741 // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
19742 if (payload_node == NULL)
19743 payload_node = payload_window->DockNodeAsHost;
19744 ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
19745 if (ref_node_for_rect)
19746 IM_ASSERT(ref_node_for_rect->IsVisible == true);
19747
19748 // Filter, figure out where we are allowed to dock
19749 ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
19750 ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
19751 data->IsCenterAvailable = true;
19752 if (is_outer_docking)
19753 data->IsCenterAvailable = false;
19754 else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
19755 data->IsCenterAvailable = false;
19756 else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
19757 data->IsCenterAvailable = false;
19758 else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
19759 data->IsCenterAvailable = false;
19760 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
19761 data->IsCenterAvailable = false;
19762 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
19763 data->IsCenterAvailable = false;
19764
19765 data->IsSidesAvailable = true;
19766 if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
19767 data->IsSidesAvailable = false;
19768 else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
19769 data->IsSidesAvailable = false;
19770 else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
19771 data->IsSidesAvailable = false;
19772
19773 // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
19774 data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
19775 data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
19776 data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
19777 data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
19778
19779 // Calculate drop shapes geometry for allowed splitting directions
19780 IM_ASSERT(ImGuiDir_None == -1);
19781 data->SplitNode = host_node;
19782 data->SplitDir = ImGuiDir_None;
19783 data->IsSplitDirExplicit = false;
19784 if (!host_window->Collapsed)
19785 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
19786 {
19787 if (dir == ImGuiDir_None && !data->IsCenterAvailable)
19788 continue;
19789 if (dir != ImGuiDir_None && !data->IsSidesAvailable)
19790 continue;
19791 if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
19792 {
19793 data->SplitDir = (ImGuiDir)dir;
19794 data->IsSplitDirExplicit = true;
19795 }
19796 }
19797
19798 // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
19799 data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
19800 if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
19801 data->IsDropAllowed = false;
19802
19803 // Calculate split area
19804 data->SplitRatio = 0.0f;
19805 if (data->SplitDir != ImGuiDir_None)
19806 {
19807 ImGuiDir split_dir = data->SplitDir;
19808 ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
19809 ImVec2 pos_new, pos_old = data->FutureNode.Pos;
19810 ImVec2 size_new, size_old = data->FutureNode.Size;
19811 DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
19812
19813 // Calculate split ratio so we can pass it down the docking request
19814 float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
19815 data->FutureNode.Pos = pos_new;
19816 data->FutureNode.Size = size_new;
19817 data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
19818 }
19819 }
19820
19821 static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
19822 {
19823 ImGuiContext& g = *GImGui;
19824 IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
19825
19826 // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
19827 // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
19828 const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
19829
19830 // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
19831 int overlay_draw_lists_count = 0;
19832 ImDrawList* overlay_draw_lists[2];
19833 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
19834 if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
19835 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
19836
19837 // Draw main preview rectangle
19838 const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
19839 const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
19840 const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
19841 const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
19842
19843 // Display area preview
19844 const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
19845 if (data->IsDropAllowed)
19846 {
19847 ImRect overlay_rect = data->FutureNode.Rect();
19848 if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
19849 overlay_rect.Min.y += GetFrameHeight();
19850 if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
19851 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19852 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));
19853 }
19854
19855 // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
19856 if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
19857 {
19858 // Compute target tab bar geometry so we can locate our preview tabs
19859 ImRect tab_bar_rect;
19860 DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
19861 ImVec2 tab_pos = tab_bar_rect.Min;
19862 if (host_node && host_node->TabBar)
19863 {
19864 if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
19865 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.
19866 else
19867 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
19868 }
19869 else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
19870 {
19871 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
19872 }
19873
19874 // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
19875 if (root_payload->DockNodeAsHost)
19876 IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
19877 ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
19878 const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
19879 for (int payload_n = 0; payload_n < payload_count; payload_n++)
19880 {
19881 // DockNode's TabBar may have non-window Tabs manually appended by user
19882 ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
19883 if (tab_bar_with_payload && payload_window == NULL)
19884 continue;
19885 if (!DockNodeIsDropAllowedOne(payload_window, host_window))
19886 continue;
19887
19888 // Calculate the tab bounding box for each payload window
19889 ImVec2 tab_size = TabItemCalcSize(payload_window);
19890 ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
19891 tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
19892 const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
19893 const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
19894 PushStyleColor(ImGuiCol_Text, overlay_col_text);
19895 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19896 {
19897 ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
19898 if (!tab_bar_rect.Contains(tab_bb))
19899 overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
19900 TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
19901 TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->DisplayedName == NULL ? payload_window->Name : payload_window->DisplayedName, 0, 0, false, NULL, NULL);
19902 if (!tab_bar_rect.Contains(tab_bb))
19903 overlay_draw_lists[overlay_n]->PopClipRect();
19904 }
19905 PopStyleColor();
19906 }
19907 }
19908
19909 // Display drop boxes
19910 const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
19911 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
19912 {
19913 if (!data->DropRectsDraw[dir + 1].IsInverted())
19914 {
19915 ImRect draw_r = data->DropRectsDraw[dir + 1];
19916 ImRect draw_r_in = draw_r;
19917 draw_r_in.Expand(-2.0f);
19918 ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
19919 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
19920 {
19921 ImVec2 center = ImFloor(draw_r_in.GetCenter());
19922 overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
19923 overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
19924 if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
19925 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);
19926 if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
19927 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);
19928 }
19929 }
19930
19931 // Stop after ImGuiDir_None
19932 if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
19933 return;
19934 }
19935 }
19936
19937 //-----------------------------------------------------------------------------
19938 // Docking: ImGuiDockNode Tree manipulation functions
19939 //-----------------------------------------------------------------------------
19940 // - DockNodeTreeSplit()
19941 // - DockNodeTreeMerge()
19942 // - DockNodeTreeUpdatePosSize()
19943 // - DockNodeTreeUpdateSplitterFindTouchingNode()
19944 // - DockNodeTreeUpdateSplitter()
19945 // - DockNodeTreeFindFallbackLeafNode()
19946 // - DockNodeTreeFindNodeByPos()
19947 //-----------------------------------------------------------------------------
19948
19949 void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
19950 {
19951 ImGuiContext& g = *GImGui;
19952 IM_ASSERT(split_axis != ImGuiAxis_None);
19953
19954 ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
19955 child_0->ParentNode = parent_node;
19956
19957 ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
19958 child_1->ParentNode = parent_node;
19959
19960 ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
19961 DockNodeMoveChildNodes(child_inheritor, parent_node);
19962 parent_node->ChildNodes[0] = child_0;
19963 parent_node->ChildNodes[1] = child_1;
19964 parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
19965 parent_node->SplitAxis = split_axis;
19966 parent_node->VisibleWindow = NULL;
19967 parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
19968
19969 float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
19970 size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
19971 IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
19972 child_0->SizeRef = child_1->SizeRef = parent_node->Size;
19973 child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
19974 child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
19975
19976 DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
19977 DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
19978 DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
19979 DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
19980
19981 // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
19982 child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
19983 child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
19984 child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19985 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
19986 child_0->UpdateMergedFlags();
19987 child_1->UpdateMergedFlags();
19988 parent_node->UpdateMergedFlags();
19989 if (child_inheritor->IsCentralNode())
19990 DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
19991 }
19992
19993 void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
19994 {
19995 // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
19996 ImGuiContext& g = *GImGui;
19997 ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
19998 ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
19999 IM_ASSERT(child_0 || child_1);
20000 IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
20001 if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
20002 {
20003 IM_ASSERT(parent_node->TabBar == NULL);
20004 IM_ASSERT(parent_node->Windows.Size == 0);
20005 }
20006 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);
20007
20008 ImVec2 backup_last_explicit_size = parent_node->SizeRef;
20009 DockNodeMoveChildNodes(parent_node, merge_lead_child);
20010 if (child_0)
20011 {
20012 DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
20013 DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
20014 }
20015 if (child_1)
20016 {
20017 DockNodeMoveWindows(parent_node, child_1);
20018 DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
20019 }
20020 DockNodeApplyPosSizeToWindows(parent_node);
20021 parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
20022 parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
20023 parent_node->SizeRef = backup_last_explicit_size;
20024
20025 // Flags transfer
20026 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
20027 parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
20028 parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
20029 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
20030 parent_node->UpdateMergedFlags();
20031
20032 if (child_0)
20033 {
20034 ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
20035 IM_DELETE(child_0);
20036 }
20037 if (child_1)
20038 {
20039 ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
20040 IM_DELETE(child_1);
20041 }
20042 }
20043
20044 // Update Pos/Size for a node hierarchy (don't affect child Windows yet)
20045 // (Depth-first, Pre-Order)
20046 void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
20047 {
20048 // During the regular dock node update we write to all nodes.
20049 // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
20050 ImGuiContext& g = *GImGui;
20051 const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
20052 if (write_to_node)
20053 {
20054 node->Pos = pos;
20055 node->Size = size;
20056 }
20057
20058 if (node->IsLeafNode())
20059 return;
20060
20061 ImGuiDockNode* child_0 = node->ChildNodes[0];
20062 ImGuiDockNode* child_1 = node->ChildNodes[1];
20063 ImVec2 child_0_pos = pos, child_1_pos = pos;
20064 ImVec2 child_0_size = size, child_1_size = size;
20065
20066 const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
20067 const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
20068 const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
20069 const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
20070
20071 if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
20072 {
20073 const float spacing = g.Style.DockingSeparatorSize;
20074 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
20075 const float size_avail = ImMax(size[axis] - spacing, 0.0f);
20076
20077 // Size allocation policy
20078 // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
20079 const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
20080
20081 // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
20082 // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
20083 // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
20084
20085 // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
20086 if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
20087 {
20088 child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
20089 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
20090 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
20091 }
20092 else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
20093 {
20094 child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
20095 child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
20096 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
20097 }
20098 else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
20099 {
20100 // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
20101 // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
20102 float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
20103 child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
20104 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
20105 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
20106 }
20107
20108 // 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
20109 else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
20110 {
20111 child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
20112 child_1_size[axis] = (size_avail - child_0_size[axis]);
20113 }
20114 else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
20115 {
20116 child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
20117 child_0_size[axis] = (size_avail - child_1_size[axis]);
20118 }
20119 else
20120 {
20121 // 4) Otherwise distribute according to the relative ratio of each SizeRef value
20122 float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
20123 child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
20124 child_1_size[axis] = (size_avail - child_0_size[axis]);
20125 }
20126
20127 child_1_pos[axis] += spacing + child_0_size[axis];
20128 }
20129
20130 if (only_write_to_single_node == NULL)
20131 child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
20132
20133 const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
20134 const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
20135 if (child_0_recurse)
20136 DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
20137 if (child_1_recurse)
20138 DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
20139 }
20140
20141 static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
20142 {
20143 if (node->IsLeafNode())
20144 {
20145 touching_nodes->push_back(node);
20146 return;
20147 }
20148 if (node->ChildNodes[0]->IsVisible)
20149 if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
20150 DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
20151 if (node->ChildNodes[1]->IsVisible)
20152 if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
20153 DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
20154 }
20155
20156 // (Depth-First, Pre-Order)
20157 void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
20158 {
20159 if (node->IsLeafNode())
20160 return;
20161
20162 ImGuiContext& g = *GImGui;
20163
20164 ImGuiDockNode* child_0 = node->ChildNodes[0];
20165 ImGuiDockNode* child_1 = node->ChildNodes[1];
20166 if (child_0->IsVisible && child_1->IsVisible)
20167 {
20168 // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
20169 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
20170 IM_ASSERT(axis != ImGuiAxis_None);
20171 ImRect bb;
20172 bb.Min = child_0->Pos;
20173 bb.Max = child_1->Pos;
20174 bb.Min[axis] += child_0->Size[axis];
20175 bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
20176 //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
20177
20178 const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
20179 const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
20180 if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
20181 {
20182 ImGuiWindow* window = g.CurrentWindow;
20183 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
20184 }
20185 else
20186 {
20187 //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
20188 //bb.Max[axis] -= 1;
20189 PushID(node->ID);
20190
20191 // Find resizing limits by gathering list of nodes that are touching the splitter line.
20192 ImVector<ImGuiDockNode*> touching_nodes[2];
20193 float min_size = g.Style.WindowMinSize[axis];
20194 float resize_limits[2];
20195 resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
20196 resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
20197
20198 ImGuiID splitter_id = GetID("##Splitter");
20199 if (g.ActiveId == splitter_id) // Only process when splitter is active
20200 {
20201 DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
20202 DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
20203 for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
20204 resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
20205 for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
20206 resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
20207
20208 // [DEBUG] Render touching nodes & limits
20209 /*
20210 ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20211 for (int n = 0; n < 2; n++)
20212 {
20213 for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
20214 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));
20215 if (axis == ImGuiAxis_X)
20216 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);
20217 else
20218 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);
20219 }
20220 */
20221 }
20222
20223 // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
20224 float cur_size_0 = child_0->Size[axis];
20225 float cur_size_1 = child_1->Size[axis];
20226 float min_size_0 = resize_limits[0] - child_0->Pos[axis];
20227 float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
20228 ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
20229 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))
20230 {
20231 if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
20232 {
20233 child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
20234 child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
20235 child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
20236
20237 // Lock the size of every node that is a sibling of the node we are touching
20238 // This might be less desirable if we can merge sibling of a same axis into the same parental level.
20239 for (int side_n = 0; side_n < 2; side_n++)
20240 for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
20241 {
20242 ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
20243 //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20244 //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
20245 while (touching_node->ParentNode != node)
20246 {
20247 if (touching_node->ParentNode->SplitAxis == axis)
20248 {
20249 // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
20250 ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
20251 node_to_preserve->WantLockSizeOnce = true;
20252 //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
20253 //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
20254 }
20255 touching_node = touching_node->ParentNode;
20256 }
20257 }
20258
20259 DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
20260 DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
20261 MarkIniSettingsDirty();
20262 }
20263 }
20264 PopID();
20265 }
20266 }
20267
20268 if (child_0->IsVisible)
20269 DockNodeTreeUpdateSplitter(child_0);
20270 if (child_1->IsVisible)
20271 DockNodeTreeUpdateSplitter(child_1);
20272 }
20273
20274 ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
20275 {
20276 if (node->IsLeafNode())
20277 return node;
20278 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
20279 return leaf_node;
20280 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
20281 return leaf_node;
20282 return NULL;
20283 }
20284
20285 ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
20286 {
20287 if (!node->IsVisible)
20288 return NULL;
20289
20290 const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
20291 ImRect r(node->Pos, node->Pos + node->Size);
20292 r.Expand(dock_spacing * 0.5f);
20293 bool inside = r.Contains(pos);
20294 if (!inside)
20295 return NULL;
20296
20297 if (node->IsLeafNode())
20298 return node;
20299 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
20300 return hovered_node;
20301 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
20302 return hovered_node;
20303
20304 // This means we are hovering over the splitter/spacing of a parent node
20305 return node;
20306 }
20307
20308 //-----------------------------------------------------------------------------
20309 // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
20310 //-----------------------------------------------------------------------------
20311 // - SetWindowDock() [Internal]
20312 // - DockSpace()
20313 // - DockSpaceOverViewport()
20314 //-----------------------------------------------------------------------------
20315
20316 // [Internal] Called via SetNextWindowDockID()
20317 void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
20318 {
20319 // Test condition (NB: bit 0 is always true) and clear flags for next time
20320 if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
20321 return;
20322 window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
20323
20324 if (window->DockId == dock_id)
20325 return;
20326
20327 // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
20328 ImGuiContext& g = *GImGui;
20329 if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
20330 if (new_node->IsSplitNode())
20331 {
20332 // Policy: Find central node or latest focused node. We first move back to our root node.
20333 new_node = DockNodeGetRootNode(new_node);
20334 if (new_node->CentralNode)
20335 {
20336 IM_ASSERT(new_node->CentralNode->IsCentralNode());
20337 dock_id = new_node->CentralNode->ID;
20338 }
20339 else
20340 {
20341 dock_id = new_node->LastFocusedNodeId;
20342 }
20343 }
20344
20345 if (window->DockId == dock_id)
20346 return;
20347
20348 if (window->DockNode)
20349 DockNodeRemoveWindow(window->DockNode, window, 0);
20350 window->DockId = dock_id;
20351 }
20352
20353 // Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
20354 // The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
20355 // DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
20356 // When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
20357 ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
20358 {
20359 ImGuiContext& g = *GImGui;
20360 ImGuiWindow* window = GetCurrentWindowRead();
20361 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
20362 return 0;
20363
20364 // Early out if parent window is hidden/collapsed
20365 // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
20366 // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
20367 if (window->SkipItems)
20368 flags |= ImGuiDockNodeFlags_KeepAliveOnly;
20369 if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
20370 window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
20371
20372 IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags!
20373 IM_ASSERT((flags & ImGuiDockNodeFlags_CentralNode) == 0); // Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145)
20374
20375 IM_ASSERT(dockspace_id != 0);
20376 ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
20377 if (node == NULL)
20378 {
20379 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
20380 node = DockContextAddNode(&g, dockspace_id);
20381 node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
20382 }
20383 if (window_class && window_class->ClassId != node->WindowClass.ClassId)
20384 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);
20385 node->SharedFlags = flags;
20386 node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
20387
20388 // When a DockSpace transitioned form implicit to explicit this may be called a second time
20389 // 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.
20390 if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
20391 {
20392 IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
20393 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
20394 return dockspace_id;
20395 }
20396 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
20397
20398 // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
20399 if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
20400 {
20401 node->LastFrameAlive = g.FrameCount;
20402 return dockspace_id;
20403 }
20404
20405 const ImVec2 content_avail = GetContentRegionAvail();
20406 ImVec2 size = ImTrunc(size_arg);
20407 if (size.x <= 0.0f)
20408 size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
20409 if (size.y <= 0.0f)
20410 size.y = ImMax(content_avail.y + size.y, 4.0f);
20411 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
20412
20413 node->Pos = window->DC.CursorPos;
20414 node->Size = node->SizeRef = size;
20415 SetNextWindowPos(node->Pos);
20416 SetNextWindowSize(node->Size);
20417 g.NextWindowData.PosUndock = false;
20418
20419 // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
20420 // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
20421 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
20422 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
20423 window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
20424 window_flags |= ImGuiWindowFlags_NoBackground;
20425
20426 char title[256];
20427 ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
20428
20429 PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
20430 Begin(title, NULL, window_flags);
20431 PopStyleVar();
20432
20433 ImGuiWindow* host_window = g.CurrentWindow;
20434 DockNodeSetupHostWindow(node, host_window);
20435 host_window->ChildId = window->GetID(title);
20436 node->OnlyNodeWithWindows = NULL;
20437
20438 IM_ASSERT(node->IsRootNode());
20439
20440 // We need to handle the rare case were a central node is missing.
20441 // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
20442 // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
20443 // 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.
20444 // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
20445 // as it doesn't make sense for an empty dockspace to not have this property.
20446 if (node->IsLeafNode() && !node->IsCentralNode())
20447 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20448
20449 // Update the node
20450 DockNodeUpdate(node);
20451
20452 End();
20453
20454 ImRect bb(node->Pos, node->Pos + size);
20455 ItemSize(size);
20456 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?)
20457 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
20458 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
20459
20460 return dockspace_id;
20461 }
20462
20463 // Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
20464 // The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
20465 // 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.
20466 // 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.
20467 ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
20468 {
20469 if (viewport == NULL)
20470 viewport = GetMainViewport();
20471
20472 // Submit a window filling the entire viewport
20473 SetNextWindowPos(viewport->WorkPos);
20474 SetNextWindowSize(viewport->WorkSize);
20475 SetNextWindowViewport(viewport->ID);
20476
20477 ImGuiWindowFlags host_window_flags = 0;
20478 host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
20479 host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
20480 //if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
20481 host_window_flags |= ImGuiWindowFlags_NoBackground;
20482
20483 // FIXME-OPT: When using ImGuiDockNodeFlags_KeepAliveOnly with DockSpaceOverViewport() we might be able to spare submitting the window,
20484 // since DockSpace() with that flag doesn't need a window. We'd only need to compute the default ID accordingly.
20485 if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly)
20486 host_window_flags |= ImGuiWindowFlags_NoMouseInputs;
20487
20488 char label[32];
20489 ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
20490
20491 PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
20492 PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
20493 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
20494 Begin(label, NULL, host_window_flags);
20495 PopStyleVar(3);
20496
20497 // Submit the dockspace
20498 if (dockspace_id == 0)
20499 dockspace_id = GetID("DockSpace");
20500 DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
20501
20502 End();
20503
20504 return dockspace_id;
20505 }
20506
20507 //-----------------------------------------------------------------------------
20508 // Docking: Builder Functions
20509 //-----------------------------------------------------------------------------
20510 // Very early end-user API to manipulate dock nodes.
20511 // Only available in imgui_internal.h. Expect this API to change/break!
20512 // It is expected that those functions are all called _before_ the dockspace node submission.
20513 //-----------------------------------------------------------------------------
20514 // - DockBuilderDockWindow()
20515 // - DockBuilderGetNode()
20516 // - DockBuilderSetNodePos()
20517 // - DockBuilderSetNodeSize()
20518 // - DockBuilderAddNode()
20519 // - DockBuilderRemoveNode()
20520 // - DockBuilderRemoveNodeChildNodes()
20521 // - DockBuilderRemoveNodeDockedWindows()
20522 // - DockBuilderSplitNode()
20523 // - DockBuilderCopyNodeRec()
20524 // - DockBuilderCopyNode()
20525 // - DockBuilderCopyWindowSettings()
20526 // - DockBuilderCopyDockSpace()
20527 // - DockBuilderFinish()
20528 //-----------------------------------------------------------------------------
20529
20530 void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
20531 {
20532 // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
20533 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20534 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
20535 ImGuiID window_id = ImHashStr(window_name);
20536 if (ImGuiWindow* window = FindWindowByID(window_id))
20537 {
20538 // Apply to created window
20539 ImGuiID prev_node_id = window->DockId;
20540 SetWindowDock(window, node_id, ImGuiCond_Always);
20541 if (window->DockId != prev_node_id)
20542 window->DockOrder = -1;
20543 }
20544 else
20545 {
20546 // Apply to settings
20547 ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
20548 if (settings == NULL)
20549 settings = CreateNewWindowSettings(window_name);
20550 if (settings->DockId != node_id)
20551 settings->DockOrder = -1;
20552 settings->DockId = node_id;
20553 }
20554 }
20555
20556 ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
20557 {
20558 ImGuiContext& g = *GImGui;
20559 return DockContextFindNodeByID(&g, node_id);
20560 }
20561
20562 void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
20563 {
20564 ImGuiContext& g = *GImGui;
20565 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
20566 if (node == NULL)
20567 return;
20568 node->Pos = pos;
20569 node->AuthorityForPos = ImGuiDataAuthority_DockNode;
20570 }
20571
20572 void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
20573 {
20574 ImGuiContext& g = *GImGui;
20575 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
20576 if (node == NULL)
20577 return;
20578 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
20579 node->Size = node->SizeRef = size;
20580 node->AuthorityForSize = ImGuiDataAuthority_DockNode;
20581 }
20582
20583 // Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
20584 // - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
20585 // - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
20586 // - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
20587 // For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
20588 // - Use (id == 0) to let the system allocate a node identifier.
20589 // - Existing node with a same id will be removed.
20590 ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
20591 {
20592 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20593 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
20594
20595 if (node_id != 0)
20596 DockBuilderRemoveNode(node_id);
20597
20598 ImGuiDockNode* node = NULL;
20599 if (flags & ImGuiDockNodeFlags_DockSpace)
20600 {
20601 DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
20602 node = DockContextFindNodeByID(&g, node_id);
20603 }
20604 else
20605 {
20606 node = DockContextAddNode(&g, node_id);
20607 node->SetLocalFlags(flags);
20608 }
20609 node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
20610 return node->ID;
20611 }
20612
20613 void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
20614 {
20615 ImGuiContext& g = *GImGui; IM_UNUSED(g);
20616 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
20617
20618 ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
20619 if (node == NULL)
20620 return;
20621 DockBuilderRemoveNodeDockedWindows(node_id, true);
20622 DockBuilderRemoveNodeChildNodes(node_id);
20623 // Node may have moved or deleted if e.g. any merge happened
20624 node = DockContextFindNodeByID(&g, node_id);
20625 if (node == NULL)
20626 return;
20627 if (node->IsCentralNode() && node->ParentNode)
20628 node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20629 DockContextRemoveNode(&g, node, true);
20630 }
20631
20632 // root_id = 0 to remove all, root_id != 0 to remove child of given node.
20633 void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
20634 {
20635 ImGuiContext& g = *GImGui;
20636 ImGuiDockContext* dc = &g.DockContext;
20637
20638 ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
20639 if (root_id && root_node == NULL)
20640 return;
20641 bool has_central_node = false;
20642
20643 ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
20644 ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
20645
20646 // Process active windows
20647 ImVector<ImGuiDockNode*> nodes_to_remove;
20648 for (int n = 0; n < dc->Nodes.Data.Size; n++)
20649 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20650 {
20651 bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
20652 if (want_removal)
20653 {
20654 if (node->IsCentralNode())
20655 has_central_node = true;
20656 if (root_id != 0)
20657 DockContextQueueNotifyRemovedNode(&g, node);
20658 if (root_node)
20659 {
20660 DockNodeMoveWindows(root_node, node);
20661 DockSettingsRenameNodeReferences(node->ID, root_node->ID);
20662 }
20663 nodes_to_remove.push_back(node);
20664 }
20665 }
20666
20667 // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
20668 // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
20669 if (root_node)
20670 {
20671 root_node->AuthorityForPos = backup_root_node_authority_for_pos;
20672 root_node->AuthorityForSize = backup_root_node_authority_for_size;
20673 }
20674
20675 // Apply to settings
20676 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20677 if (ImGuiID window_settings_dock_id = settings->DockId)
20678 for (int n = 0; n < nodes_to_remove.Size; n++)
20679 if (nodes_to_remove[n]->ID == window_settings_dock_id)
20680 {
20681 settings->DockId = root_id;
20682 break;
20683 }
20684
20685 // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
20686 if (nodes_to_remove.Size > 1)
20687 ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
20688 for (int n = 0; n < nodes_to_remove.Size; n++)
20689 DockContextRemoveNode(&g, nodes_to_remove[n], false);
20690
20691 if (root_id == 0)
20692 {
20693 dc->Nodes.Clear();
20694 dc->Requests.clear();
20695 }
20696 else if (has_central_node)
20697 {
20698 root_node->CentralNode = root_node;
20699 root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
20700 }
20701 }
20702
20703 void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
20704 {
20705 // Clear references in settings
20706 ImGuiContext& g = *GImGui;
20707 if (clear_settings_refs)
20708 {
20709 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20710 {
20711 bool want_removal = (root_id == 0) || (settings->DockId == root_id);
20712 if (!want_removal && settings->DockId != 0)
20713 if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
20714 if (DockNodeGetRootNode(node)->ID == root_id)
20715 want_removal = true;
20716 if (want_removal)
20717 settings->DockId = 0;
20718 }
20719 }
20720
20721 // Clear references in windows
20722 for (int n = 0; n < g.Windows.Size; n++)
20723 {
20724 ImGuiWindow* window = g.Windows[n];
20725 bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
20726 if (want_removal)
20727 {
20728 const ImGuiID backup_dock_id = window->DockId;
20729 IM_UNUSED(backup_dock_id);
20730 DockContextProcessUndockWindow(&g, window, clear_settings_refs);
20731 if (!clear_settings_refs)
20732 IM_ASSERT(window->DockId == backup_dock_id);
20733 }
20734 }
20735 }
20736
20737 // 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.
20738 // Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
20739 // FIXME-DOCK: We are not exposing nor using split_outer.
20740 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)
20741 {
20742 ImGuiContext& g = *GImGui;
20743 IM_ASSERT(split_dir != ImGuiDir_None);
20744 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
20745
20746 ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
20747 if (node == NULL)
20748 {
20749 IM_ASSERT(node != NULL);
20750 return 0;
20751 }
20752
20753 ImGuiDockRequest req;
20754 req.Type = ImGuiDockRequestType_Split;
20755 req.DockTargetWindow = NULL;
20756 req.DockTargetNode = node;
20757 req.DockPayload = NULL;
20758 req.DockSplitDir = split_dir;
20759 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);
20760 req.DockSplitOuter = false;
20761 DockContextProcessDock(&g, &req);
20762
20763 ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
20764 ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
20765 if (out_id_at_dir)
20766 *out_id_at_dir = id_at_dir;
20767 if (out_id_at_opposite_dir)
20768 *out_id_at_opposite_dir = id_at_opposite_dir;
20769 return id_at_dir;
20770 }
20771
20772 static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
20773 {
20774 ImGuiContext& g = *GImGui;
20775 ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
20776 dst_node->SharedFlags = src_node->SharedFlags;
20777 dst_node->LocalFlags = src_node->LocalFlags;
20778 dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
20779 dst_node->Pos = src_node->Pos;
20780 dst_node->Size = src_node->Size;
20781 dst_node->SizeRef = src_node->SizeRef;
20782 dst_node->SplitAxis = src_node->SplitAxis;
20783 dst_node->UpdateMergedFlags();
20784
20785 out_node_remap_pairs->push_back(src_node->ID);
20786 out_node_remap_pairs->push_back(dst_node->ID);
20787
20788 for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
20789 if (src_node->ChildNodes[child_n])
20790 {
20791 dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
20792 dst_node->ChildNodes[child_n]->ParentNode = dst_node;
20793 }
20794
20795 IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
20796 return dst_node;
20797 }
20798
20799 void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
20800 {
20801 ImGuiContext& g = *GImGui;
20802 IM_ASSERT(src_node_id != 0);
20803 IM_ASSERT(dst_node_id != 0);
20804 IM_ASSERT(out_node_remap_pairs != NULL);
20805
20806 DockBuilderRemoveNode(dst_node_id);
20807
20808 ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
20809 IM_ASSERT(src_node != NULL);
20810
20811 out_node_remap_pairs->clear();
20812 DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
20813
20814 IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
20815 }
20816
20817 void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
20818 {
20819 ImGuiWindow* src_window = FindWindowByName(src_name);
20820 if (src_window == NULL)
20821 return;
20822 if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
20823 {
20824 dst_window->Pos = src_window->Pos;
20825 dst_window->Size = src_window->Size;
20826 dst_window->SizeFull = src_window->SizeFull;
20827 dst_window->Collapsed = src_window->Collapsed;
20828 }
20829 else
20830 {
20831 ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
20832 if (!dst_settings)
20833 dst_settings = CreateNewWindowSettings(dst_name);
20834 ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
20835 if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
20836 {
20837 dst_settings->ViewportPos = window_pos_2ih;
20838 dst_settings->ViewportId = src_window->ViewportId;
20839 dst_settings->Pos = ImVec2ih(0, 0);
20840 }
20841 else
20842 {
20843 dst_settings->Pos = window_pos_2ih;
20844 }
20845 dst_settings->Size = ImVec2ih(src_window->SizeFull);
20846 dst_settings->Collapsed = src_window->Collapsed;
20847 }
20848 }
20849
20850 // FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
20851 void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
20852 {
20853 ImGuiContext& g = *GImGui;
20854 IM_ASSERT(src_dockspace_id != 0);
20855 IM_ASSERT(dst_dockspace_id != 0);
20856 IM_ASSERT(in_window_remap_pairs != NULL);
20857 IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
20858
20859 // Duplicate entire dock
20860 // 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,
20861 // whereas we could attempt to at least keep them together in a new, same floating node.
20862 ImVector<ImGuiID> node_remap_pairs;
20863 DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
20864
20865 // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
20866 // (The windows associated to src_dockspace_id are staying in place)
20867 ImVector<ImGuiID> src_windows;
20868 for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
20869 {
20870 const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
20871 const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
20872 ImGuiID src_window_id = ImHashStr(src_window_name);
20873 src_windows.push_back(src_window_id);
20874
20875 // Search in the remapping tables
20876 ImGuiID src_dock_id = 0;
20877 if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
20878 src_dock_id = src_window->DockId;
20879 else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
20880 src_dock_id = src_window_settings->DockId;
20881 ImGuiID dst_dock_id = 0;
20882 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
20883 if (node_remap_pairs[dock_remap_n] == src_dock_id)
20884 {
20885 dst_dock_id = node_remap_pairs[dock_remap_n + 1];
20886 //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
20887 break;
20888 }
20889
20890 if (dst_dock_id != 0)
20891 {
20892 // Docked windows gets redocked into the new node hierarchy.
20893 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);
20894 DockBuilderDockWindow(dst_window_name, dst_dock_id);
20895 }
20896 else
20897 {
20898 // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
20899 // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
20900 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
20901 DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
20902 }
20903 }
20904
20905 // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
20906 // Find those windows and move to them to the cloned dock node. This may be optional?
20907 // Dock those are a second step as undocking would invalidate source dock nodes.
20908 struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
20909 ImVector<DockRemainingWindowTask> dock_remaining_windows;
20910 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
20911 if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
20912 {
20913 ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
20914 ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
20915 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
20916 {
20917 ImGuiWindow* window = node->Windows[window_n];
20918 if (src_windows.contains(window->ID))
20919 continue;
20920
20921 // Docked windows gets redocked into the new node hierarchy.
20922 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
20923 dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
20924 }
20925 }
20926 for (const DockRemainingWindowTask& task : dock_remaining_windows)
20927 DockBuilderDockWindow(task.Window->Name, task.DockId);
20928 }
20929
20930 // FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
20931 void ImGui::DockBuilderFinish(ImGuiID root_id)
20932 {
20933 ImGuiContext& g = *GImGui;
20934 //DockContextRebuild(&g);
20935 DockContextBuildAddWindowsToNodes(&g, root_id);
20936 }
20937
20938 //-----------------------------------------------------------------------------
20939 // Docking: Begin/End Support Functions (called from Begin/End)
20940 //-----------------------------------------------------------------------------
20941 // - GetWindowAlwaysWantOwnTabBar()
20942 // - DockContextBindNodeToWindow()
20943 // - BeginDocked()
20944 // - BeginDockableDragDropSource()
20945 // - BeginDockableDragDropTarget()
20946 //-----------------------------------------------------------------------------
20947
20948 bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
20949 {
20950 ImGuiContext& g = *GImGui;
20951 if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
20952 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
20953 if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
20954 return true;
20955 return false;
20956 }
20957
20958 static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
20959 {
20960 ImGuiContext& g = *ctx;
20961 ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
20962 IM_ASSERT(window->DockNode == NULL);
20963
20964 // We should not be docking into a split node (SetWindowDock should avoid this)
20965 if (node && node->IsSplitNode())
20966 {
20967 DockContextProcessUndockWindow(ctx, window);
20968 return NULL;
20969 }
20970
20971 // Create node
20972 if (node == NULL)
20973 {
20974 node = DockContextAddNode(ctx, window->DockId);
20975 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
20976 node->LastFrameAlive = g.FrameCount;
20977 }
20978
20979 // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
20980 // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
20981 // 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.
20982 // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
20983 if (!node->IsVisible)
20984 {
20985 ImGuiDockNode* ancestor_node = node;
20986 while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
20987 ancestor_node = ancestor_node->ParentNode;
20988 IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
20989 DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
20990 DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
20991 }
20992
20993 // Add window to node
20994 bool node_was_visible = node->IsVisible;
20995 DockNodeAddWindow(node, window, true);
20996 node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
20997 IM_ASSERT(node == window->DockNode);
20998 return node;
20999 }
21000
21001 static void StoreDockStyleForWindow(ImGuiWindow* window)
21002 {
21003 ImGuiContext& g = *GImGui;
21004 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
21005 window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
21006 }
21007
21008 void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
21009 {
21010 ImGuiContext& g = *GImGui;
21011
21012 // Clear fields ahead so most early-out paths don't have to do it
21013 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
21014
21015 const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
21016 if (auto_dock_node)
21017 {
21018 if (window->DockId == 0)
21019 {
21020 IM_ASSERT(window->DockNode == NULL);
21021 window->DockId = DockContextGenNodeID(&g);
21022 }
21023 }
21024 else
21025 {
21026 // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
21027 bool want_undock = false;
21028 want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
21029 want_undock |= (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
21030 if (want_undock)
21031 {
21032 DockContextProcessUndockWindow(&g, window);
21033 return;
21034 }
21035 }
21036
21037 // Bind to our dock node
21038 ImGuiDockNode* node = window->DockNode;
21039 if (node != NULL)
21040 IM_ASSERT(window->DockId == node->ID);
21041 if (window->DockId != 0 && node == NULL)
21042 {
21043 node = DockContextBindNodeToWindow(&g, window);
21044 if (node == NULL)
21045 return;
21046 }
21047
21048 #if 0
21049 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
21050 if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
21051 {
21052 DockContextProcessUndockWindow(ctx, window);
21053 return;
21054 }
21055 #endif
21056
21057 // Undock if our dockspace node disappeared
21058 // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
21059 if (node->LastFrameAlive < g.FrameCount)
21060 {
21061 // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
21062 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
21063 if (root_node->LastFrameAlive < g.FrameCount)
21064 DockContextProcessUndockWindow(&g, window);
21065 else
21066 window->DockIsActive = true;
21067 return;
21068 }
21069
21070 // Store style overrides
21071 StoreDockStyleForWindow(window);
21072
21073 // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
21074 // and never create neither a host window neither a tab bar.
21075 // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
21076 if (node->HostWindow == NULL)
21077 {
21078 if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
21079 window->DockIsActive = true;
21080 if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
21081 DockNodeHideWindowDuringHostWindowCreation(window);
21082 return;
21083 }
21084
21085 // We can have zero-sized nodes (e.g. children of a small-size dockspace)
21086 IM_ASSERT(node->HostWindow);
21087 IM_ASSERT(node->IsLeafNode());
21088 IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
21089 node->State = ImGuiDockNodeState_HostWindowVisible;
21090
21091 // Undock if we are submitted earlier than the host window
21092 if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
21093 {
21094 DockContextProcessUndockWindow(&g, window);
21095 return;
21096 }
21097
21098 // Position/Size window
21099 SetNextWindowPos(node->Pos);
21100 SetNextWindowSize(node->Size);
21101 g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
21102 window->DockIsActive = true;
21103 window->DockNodeIsVisible = true;
21104 window->DockTabIsVisible = false;
21105 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
21106 return;
21107
21108 // When the window is selected we mark it as visible.
21109 if (node->VisibleWindow == window)
21110 window->DockTabIsVisible = true;
21111
21112 // Update window flag
21113 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
21114 window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
21115 window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
21116 if (node->IsHiddenTabBar() || node->IsNoTabBar())
21117 window->Flags |= ImGuiWindowFlags_NoTitleBar;
21118 else
21119 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!
21120
21121 // Save new dock order only if the window has been visible once already
21122 // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
21123 if (node->TabBar && window->WasActive)
21124 window->DockOrder = (short)DockNodeGetTabOrder(window);
21125
21126 if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
21127 *p_open = false;
21128
21129 // Update ChildId to allow returning from Child to Parent with Escape
21130 ImGuiWindow* parent_window = window->DockNode->HostWindow;
21131 window->ChildId = parent_window->GetID(window->Name);
21132 }
21133
21134 void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
21135 {
21136 ImGuiContext& g = *GImGui;
21137 IM_ASSERT(g.ActiveId == window->MoveId);
21138 IM_ASSERT(g.MovingWindow == window);
21139 IM_ASSERT(g.CurrentWindow == window);
21140
21141 // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
21142 if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
21143 {
21144 // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
21145 // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
21146 // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
21147 IM_ASSERT(g.NextWindowData.HasFlags == 0);
21148 if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
21149 SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
21150 return;
21151 }
21152
21153 g.LastItemData.ID = window->MoveId;
21154 window = window->RootWindowDockTree;
21155 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
21156 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
21157 ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
21158 if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
21159 {
21160 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
21161 EndDragDropSource();
21162 StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
21163 }
21164 }
21165
21166 void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
21167 {
21168 ImGuiContext& g = *GImGui;
21169
21170 //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
21171 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
21172 if (!g.DragDropActive)
21173 return;
21174 //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21175 if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
21176 return;
21177
21178 // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
21179 // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
21180 const ImGuiPayload* payload = &g.DragDropPayload;
21181 if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
21182 {
21183 EndDragDropTarget();
21184 return;
21185 }
21186
21187 ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
21188 if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
21189 {
21190 // Select target node
21191 // (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)
21192 bool dock_into_floating_window = false;
21193 ImGuiDockNode* node = NULL;
21194 if (window->DockNodeAsHost)
21195 {
21196 // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
21197 node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
21198
21199 // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
21200 // In this case we need to fallback into any leaf mode, possibly the central node.
21201 // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
21202 if (node && node->IsDockSpace() && node->IsRootNode())
21203 node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
21204 }
21205 else
21206 {
21207 if (window->DockNode)
21208 node = window->DockNode;
21209 else
21210 dock_into_floating_window = true; // Dock into a regular window
21211 }
21212
21213 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()));
21214 const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
21215
21216 // Preview docking request and find out split direction/ratio
21217 //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.
21218 const bool do_preview = payload->IsPreview() || payload->IsDelivery();
21219 if (do_preview && (node != NULL || dock_into_floating_window))
21220 {
21221 // 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.
21222 ImGuiDockPreviewData split_inner;
21223 ImGuiDockPreviewData split_outer;
21224 ImGuiDockPreviewData* split_data = &split_inner;
21225 if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
21226 if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
21227 {
21228 DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
21229 if (split_outer.IsSplitDirExplicit)
21230 split_data = &split_outer;
21231 }
21232 if (!node || node->IsLeafNode())
21233 DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
21234 if (split_data == &split_outer)
21235 split_inner.IsDropAllowed = false;
21236
21237 // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
21238 DockNodePreviewDockRender(window, node, payload_window, &split_inner);
21239 DockNodePreviewDockRender(window, node, payload_window, &split_outer);
21240
21241 // Queue docking request
21242 if (split_data->IsDropAllowed && payload->IsDelivery())
21243 DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
21244 }
21245 }
21246 EndDragDropTarget();
21247 }
21248
21249 //-----------------------------------------------------------------------------
21250 // Docking: Settings
21251 //-----------------------------------------------------------------------------
21252 // - DockSettingsRenameNodeReferences()
21253 // - DockSettingsRemoveNodeReferences()
21254 // - DockSettingsFindNodeSettings()
21255 // - DockSettingsHandler_ApplyAll()
21256 // - DockSettingsHandler_ReadOpen()
21257 // - DockSettingsHandler_ReadLine()
21258 // - DockSettingsHandler_DockNodeToSettings()
21259 // - DockSettingsHandler_WriteAll()
21260 //-----------------------------------------------------------------------------
21261
21262 static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
21263 {
21264 ImGuiContext& g = *GImGui;
21265 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
21266 for (int window_n = 0; window_n < g.Windows.Size; window_n++)
21267 {
21268 ImGuiWindow* window = g.Windows[window_n];
21269 if (window->DockId == old_node_id && window->DockNode == NULL)
21270 window->DockId = new_node_id;
21271 }
21272 //// FIXME-OPT: We could remove this loop by storing the index in the map
21273 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
21274 if (settings->DockId == old_node_id)
21275 settings->DockId = new_node_id;
21276 }
21277
21278 // Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
21279 static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
21280 {
21281 ImGuiContext& g = *GImGui;
21282 int found = 0;
21283 //// FIXME-OPT: We could remove this loop by storing the index in the map
21284 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
21285 for (int node_n = 0; node_n < node_ids_count; node_n++)
21286 if (settings->DockId == node_ids[node_n])
21287 {
21288 settings->DockId = 0;
21289 settings->DockOrder = -1;
21290 if (++found < node_ids_count)
21291 break;
21292 return;
21293 }
21294 }
21295
21296 static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
21297 {
21298 // FIXME-OPT
21299 ImGuiDockContext* dc = &ctx->DockContext;
21300 for (int n = 0; n < dc->NodesSettings.Size; n++)
21301 if (dc->NodesSettings[n].ID == id)
21302 return &dc->NodesSettings[n];
21303 return NULL;
21304 }
21305
21306 // Clear settings data
21307 static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
21308 {
21309 ImGuiDockContext* dc = &ctx->DockContext;
21310 dc->NodesSettings.clear();
21311 DockContextClearNodes(ctx, 0, true);
21312 }
21313
21314 // Recreate nodes based on settings data
21315 static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
21316 {
21317 // Prune settings at boot time only
21318 ImGuiDockContext* dc = &ctx->DockContext;
21319 if (ctx->Windows.Size == 0)
21320 DockContextPruneUnusedSettingsNodes(ctx);
21321 DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
21322 DockContextBuildAddWindowsToNodes(ctx, 0);
21323 }
21324
21325 static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
21326 {
21327 if (strcmp(name, "Data") != 0)
21328 return NULL;
21329 return (void*)1;
21330 }
21331
21332 static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
21333 {
21334 char c = 0;
21335 int x = 0, y = 0;
21336 int r = 0;
21337
21338 // Parsing, e.g.
21339 // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
21340 // " DockNode ID=0x00000002 Parent=0x00000001 "
21341 // Important: this code expect currently fields in a fixed order.
21342 ImGuiDockNodeSettings node;
21343 line = ImStrSkipBlank(line);
21344 if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
21345 else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
21346 else return;
21347 if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
21348 if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
21349 if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
21350 if (node.ParentNodeId == 0)
21351 {
21352 if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
21353 if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
21354 }
21355 else
21356 {
21357 if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
21358 }
21359 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; }
21360 if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
21361 if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
21362 if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
21363 if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
21364 if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
21365 if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
21366 if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
21367 if (node.ParentNodeId != 0)
21368 if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
21369 node.Depth = parent_settings->Depth + 1;
21370 ctx->DockContext.NodesSettings.push_back(node);
21371 }
21372
21373 static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
21374 {
21375 ImGuiDockNodeSettings node_settings;
21376 IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
21377 node_settings.ID = node->ID;
21378 node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
21379 node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
21380 node_settings.SelectedTabId = node->SelectedTabId;
21381 node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
21382 node_settings.Depth = (char)depth;
21383 node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
21384 node_settings.Pos = ImVec2ih(node->Pos);
21385 node_settings.Size = ImVec2ih(node->Size);
21386 node_settings.SizeRef = ImVec2ih(node->SizeRef);
21387 dc->NodesSettings.push_back(node_settings);
21388 if (node->ChildNodes[0])
21389 DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
21390 if (node->ChildNodes[1])
21391 DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
21392 }
21393
21394 static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
21395 {
21396 ImGuiContext& g = *ctx;
21397 ImGuiDockContext* dc = &ctx->DockContext;
21398 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
21399 return;
21400
21401 // Gather settings data
21402 // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
21403 dc->NodesSettings.resize(0);
21404 dc->NodesSettings.reserve(dc->Nodes.Data.Size);
21405 for (int n = 0; n < dc->Nodes.Data.Size; n++)
21406 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
21407 if (node->IsRootNode())
21408 DockSettingsHandler_DockNodeToSettings(dc, node, 0);
21409
21410 int max_depth = 0;
21411 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
21412 max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
21413
21414 // Write to text buffer
21415 buf->appendf("[%s][Data]\n", handler->TypeName);
21416 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
21417 {
21418 const int line_start_pos = buf->size(); (void)line_start_pos;
21419 const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
21420 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
21421 buf->appendf(" ID=0x%08X", node_settings->ID);
21422 if (node_settings->ParentNodeId)
21423 {
21424 buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
21425 }
21426 else
21427 {
21428 if (node_settings->ParentWindowId)
21429 buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
21430 buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
21431 }
21432 if (node_settings->SplitAxis != ImGuiAxis_None)
21433 buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
21434 if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
21435 buf->appendf(" NoResize=1");
21436 if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
21437 buf->appendf(" CentralNode=1");
21438 if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
21439 buf->appendf(" NoTabBar=1");
21440 if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
21441 buf->appendf(" HiddenTabBar=1");
21442 if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
21443 buf->appendf(" NoWindowMenuButton=1");
21444 if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
21445 buf->appendf(" NoCloseButton=1");
21446 if (node_settings->SelectedTabId)
21447 buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
21448
21449 // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
21450 if (g.IO.ConfigDebugIniSettings)
21451 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
21452 {
21453 buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
21454 if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
21455 buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
21456 // Iterate settings so we can give info about windows that didn't exist during the session.
21457 int contains_window = 0;
21458 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
21459 if (settings->DockId == node_settings->ID)
21460 {
21461 if (contains_window++ == 0)
21462 buf->appendf(" ; contains ");
21463 buf->appendf("'%s' ", settings->GetName());
21464 }
21465 }
21466
21467 buf->appendf("\n");
21468 }
21469 buf->appendf("\n");
21470 }
21471
21472
21473 //-----------------------------------------------------------------------------
21474 // [SECTION] PLATFORM DEPENDENT HELPERS
21475 //-----------------------------------------------------------------------------
21476 // - Default clipboard handlers
21477 // - Default shell function handlers
21478 // - Default IME handlers
21479 //-----------------------------------------------------------------------------
21480
21481 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
21482
21483 #ifdef _MSC_VER
21484 #pragma comment(lib, "user32")
21485 #pragma comment(lib, "kernel32")
21486 #endif
21487
21488 // Win32 clipboard implementation
21489 // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
21490 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21491 {
21492 ImGuiContext& g = *ctx;
21493 g.ClipboardHandlerData.clear();
21494 if (!::OpenClipboard(NULL))
21495 return NULL;
21496 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
21497 if (wbuf_handle == NULL)
21498 {
21499 ::CloseClipboard();
21500 return NULL;
21501 }
21502 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
21503 {
21504 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
21505 g.ClipboardHandlerData.resize(buf_len);
21506 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
21507 }
21508 ::GlobalUnlock(wbuf_handle);
21509 ::CloseClipboard();
21510 return g.ClipboardHandlerData.Data;
21511 }
21512
21513 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
21514 {
21515 if (!::OpenClipboard(NULL))
21516 return;
21517 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
21518 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
21519 if (wbuf_handle == NULL)
21520 {
21521 ::CloseClipboard();
21522 return;
21523 }
21524 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
21525 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
21526 ::GlobalUnlock(wbuf_handle);
21527 ::EmptyClipboard();
21528 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
21529 ::GlobalFree(wbuf_handle);
21530 ::CloseClipboard();
21531 }
21532
21533 #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
21534
21535 #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
21536 static PasteboardRef main_clipboard = 0;
21537
21538 // OSX clipboard implementation
21539 // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
21540 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text)
21541 {
21542 if (!main_clipboard)
21543 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
21544 PasteboardClear(main_clipboard);
21545 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text));
21546 if (cf_data)
21547 {
21548 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
21549 CFRelease(cf_data);
21550 }
21551 }
21552
21553 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21554 {
21555 ImGuiContext& g = *ctx;
21556 if (!main_clipboard)
21557 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
21558 PasteboardSynchronize(main_clipboard);
21559
21560 ItemCount item_count = 0;
21561 PasteboardGetItemCount(main_clipboard, &item_count);
21562 for (ItemCount i = 0; i < item_count; i++)
21563 {
21564 PasteboardItemID item_id = 0;
21565 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
21566 CFArrayRef flavor_type_array = 0;
21567 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
21568 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
21569 {
21570 CFDataRef cf_data;
21571 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
21572 {
21573 g.ClipboardHandlerData.clear();
21574 int length = (int)CFDataGetLength(cf_data);
21575 g.ClipboardHandlerData.resize(length + 1);
21576 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
21577 g.ClipboardHandlerData[length] = 0;
21578 CFRelease(cf_data);
21579 return g.ClipboardHandlerData.Data;
21580 }
21581 }
21582 }
21583 return NULL;
21584 }
21585
21586 #else
21587
21588 // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
21589 static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx)
21590 {
21591 ImGuiContext& g = *ctx;
21592 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
21593 }
21594
21595 static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text)
21596 {
21597 ImGuiContext& g = *ctx;
21598 g.ClipboardHandlerData.clear();
21599 const char* text_end = text + ImStrlen(text);
21600 g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
21601 memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
21602 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
21603 }
21604
21605 #endif // Default clipboard handlers
21606
21607 //-----------------------------------------------------------------------------
21608
21609 #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21610 #if defined(__APPLE__) && TARGET_OS_IPHONE
21611 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21612 #endif
21613 #if defined(__3DS__)
21614 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21615 #endif
21616 #if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
21617 #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21618 #endif
21619 #endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21620
21621 #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
21622 #ifdef _WIN32
21623 #include <shellapi.h> // ShellExecuteA()
21624 #ifdef _MSC_VER
21625 #pragma comment(lib, "shell32")
21626 #endif
21627 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
21628 {
21629 const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
21630 ImVector<wchar_t> path_wbuf;
21631 path_wbuf.resize(path_wsize);
21632 ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize);
21633 return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32;
21634 }
21635 #else
21636 #include <sys/wait.h>
21637 #include <unistd.h>
21638 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
21639 {
21640 #if defined(__APPLE__)
21641 const char* args[] { "open", "--", path, NULL };
21642 #else
21643 const char* args[] { "xdg-open", path, NULL };
21644 #endif
21645 pid_t pid = fork();
21646 if (pid < 0)
21647 return false;
21648 if (!pid)
21649 {
21650 execvp(args[0], const_cast<char **>(args));
21651 exit(-1);
21652 }
21653 else
21654 {
21655 int status;
21656 waitpid(pid, &status, 0);
21657 return WEXITSTATUS(status) == 0;
21658 }
21659 }
21660 #endif
21661 #else
21662 static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
21663 #endif // Default shell handlers
21664
21665 //-----------------------------------------------------------------------------
21666
21667 // Win32 API IME support (for Asian languages, etc.)
21668 #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
21669
21670 #include <imm.h>
21671 #ifdef _MSC_VER
21672 #pragma comment(lib, "imm32")
21673 #endif
21674
21675 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
21676 {
21677 // Notify OS Input Method Editor of text input position
21678 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
21679 if (hwnd == 0)
21680 return;
21681
21682 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
21683 if (HIMC himc = ::ImmGetContext(hwnd))
21684 {
21685 COMPOSITIONFORM composition_form = {};
21686 composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
21687 composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
21688 composition_form.dwStyle = CFS_FORCE_POSITION;
21689 ::ImmSetCompositionWindow(himc, &composition_form);
21690 CANDIDATEFORM candidate_form = {};
21691 candidate_form.dwStyle = CFS_CANDIDATEPOS;
21692 candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
21693 candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
21694 ::ImmSetCandidateWindow(himc, &candidate_form);
21695 ::ImmReleaseContext(hwnd, himc);
21696 }
21697 }
21698
21699 #else
21700
21701 static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
21702
21703 #endif // Default IME handlers
21704
21705 //-----------------------------------------------------------------------------
21706 // [SECTION] METRICS/DEBUGGER WINDOW
21707 //-----------------------------------------------------------------------------
21708 // - MetricsHelpMarker() [Internal]
21709 // - DebugRenderViewportThumbnail() [Internal]
21710 // - RenderViewportsThumbnails() [Internal]
21711 // - DebugRenderKeyboardPreview() [Internal]
21712 // - DebugTextEncoding()
21713 // - DebugFlashStyleColorStop() [Internal]
21714 // - DebugFlashStyleColor()
21715 // - UpdateDebugToolFlashStyleColor() [Internal]
21716 // - ShowFontAtlas() [Internal but called by Demo!]
21717 // - DebugNodeTexture() [Internal]
21718 // - ShowMetricsWindow()
21719 // - DebugNodeColumns() [Internal]
21720 // - DebugNodeDockNode() [Internal]
21721 // - DebugNodeDrawList() [Internal]
21722 // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
21723 // - DebugNodeFont() [Internal]
21724 // - DebugNodeFontGlyph() [Internal]
21725 // - DebugNodeStorage() [Internal]
21726 // - DebugNodeTabBar() [Internal]
21727 // - DebugNodeViewport() [Internal]
21728 // - DebugNodeWindow() [Internal]
21729 // - DebugNodeWindowSettings() [Internal]
21730 // - DebugNodeWindowsList() [Internal]
21731 // - DebugNodeWindowsListByBeginStackParent() [Internal]
21732 //-----------------------------------------------------------------------------
21733
21734 #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
21735 // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
21736 static void MetricsHelpMarker(const char* desc)
21737 {
21738 ImGui::TextDisabled("(?)");
21739 if (ImGui::BeginItemTooltip())
21740 {
21741 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
21742 ImGui::TextUnformatted(desc);
21743 ImGui::PopTextWrapPos();
21744 ImGui::EndTooltip();
21745 }
21746 }
21747 #endif
21748
21749 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21750
21751 void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
21752 {
21753 ImGuiContext& g = *GImGui;
21754 ImGuiWindow* window = g.CurrentWindow;
21755
21756 ImVec2 scale = bb.GetSize() / viewport->Size;
21757 ImVec2 off = bb.Min - viewport->Pos * scale;
21758 float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
21759 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
21760 for (ImGuiWindow* thumb_window : g.Windows)
21761 {
21762 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
21763 continue;
21764 if (thumb_window->Viewport != viewport)
21765 continue;
21766
21767 ImRect thumb_r = thumb_window->Rect();
21768 ImRect title_r = thumb_window->TitleBarRect();
21769 thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale));
21770 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
21771 thumb_r.ClipWithFull(bb);
21772 title_r.ClipWithFull(bb);
21773 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
21774 window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
21775 window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
21776 window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
21777 window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
21778 }
21779 draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
21780 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
21781 window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
21782 }
21783
21784 static void RenderViewportsThumbnails()
21785 {
21786 ImGuiContext& g = *GImGui;
21787 ImGuiWindow* window = g.CurrentWindow;
21788
21789 // Draw monitor and calculate their boundaries
21790 float SCALE = 1.0f / 8.0f;
21791 ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21792 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
21793 bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
21794 ImVec2 p = window->DC.CursorPos;
21795 ImVec2 off = p - bb_full.Min * SCALE;
21796 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
21797 {
21798 ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
21799 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);
21800 window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
21801 }
21802
21803 // Draw viewports
21804 for (ImGuiViewportP* viewport : g.Viewports)
21805 {
21806 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
21807 ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
21808 }
21809 ImGui::Dummy(bb_full.GetSize() * SCALE);
21810 }
21811
21812 static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
21813 {
21814 const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
21815 const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
21816 return b->LastFocusedStampCount - a->LastFocusedStampCount;
21817 }
21818
21819 // Draw an arbitrary US keyboard layout to visualize translated keys
21820 void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
21821 {
21822 const float scale = ImGui::GetFontSize() / 13.0f;
21823 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
21824 const float key_rounding = 3.0f * scale;
21825 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
21826 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
21827 const float key_face_rounding = 2.0f * scale;
21828 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
21829 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
21830 const float key_row_offset = 9.0f * scale;
21831
21832 ImVec2 board_min = GetCursorScreenPos();
21833 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);
21834 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
21835
21836 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
21837 const KeyLayoutData keys_to_display[] =
21838 {
21839 { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
21840 { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
21841 { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
21842 };
21843
21844 // Elements rendered manually via ImDrawList API are not clipped automatically.
21845 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
21846 Dummy(board_max - board_min);
21847 if (!IsItemVisible())
21848 return;
21849 draw_list->PushClipRect(board_min, board_max, true);
21850 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
21851 {
21852 const KeyLayoutData* key_data = &keys_to_display[n];
21853 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);
21854 ImVec2 key_max = key_min + key_size;
21855 draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
21856 draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
21857 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
21858 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
21859 draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
21860 draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
21861 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
21862 draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
21863 if (IsKeyDown(key_data->Key))
21864 draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
21865 }
21866 draw_list->PopClipRect();
21867 }
21868
21869 // Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
21870 void ImGui::DebugTextEncoding(const char* str)
21871 {
21872 Text("Text: \"%s\"", str);
21873 if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
21874 return;
21875 TableSetupColumn("Offset");
21876 TableSetupColumn("UTF-8");
21877 TableSetupColumn("Glyph");
21878 TableSetupColumn("Codepoint");
21879 TableHeadersRow();
21880 for (const char* p = str; *p != 0; )
21881 {
21882 unsigned int c;
21883 const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
21884 TableNextColumn();
21885 Text("%d", (int)(p - str));
21886 TableNextColumn();
21887 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
21888 {
21889 if (byte_index > 0)
21890 SameLine();
21891 Text("0x%02X", (int)(unsigned char)p[byte_index]);
21892 }
21893 TableNextColumn();
21894 TextUnformatted(p, p + c_utf8_len);
21895 if (!GetFont()->IsGlyphInFont((ImWchar)c))
21896 {
21897 SameLine();
21898 TextUnformatted("[missing]");
21899 }
21900 TableNextColumn();
21901 Text("U+%04X", (int)c);
21902 p += c_utf8_len;
21903 }
21904 EndTable();
21905 }
21906
21907 static void DebugFlashStyleColorStop()
21908 {
21909 ImGuiContext& g = *GImGui;
21910 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
21911 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
21912 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
21913 }
21914
21915 // Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
21916 void ImGui::DebugFlashStyleColor(ImGuiCol idx)
21917 {
21918 ImGuiContext& g = *GImGui;
21919 DebugFlashStyleColorStop();
21920 g.DebugFlashStyleColorTime = 0.5f;
21921 g.DebugFlashStyleColorIdx = idx;
21922 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
21923 }
21924
21925 void ImGui::UpdateDebugToolFlashStyleColor()
21926 {
21927 ImGuiContext& g = *GImGui;
21928 if (g.DebugFlashStyleColorTime <= 0.0f)
21929 return;
21930 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);
21931 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
21932 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
21933 DebugFlashStyleColorStop();
21934 }
21935
21936 static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21937 {
21938 union { void* ptr; int integer; } tex_id_opaque;
21939 memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21940 if (sizeof(tex_id) >= sizeof(void*))
21941 ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21942 else
21943 ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21944 return buf;
21945 }
21946
21947 static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const ImDrawCmd* cmd)
21948 {
21949 char* buf_end = buf + buf_size;
21950 if (cmd->TexRef._TexData != NULL)
21951 buf += ImFormatString(buf, buf_end - buf, "#%03d: ", cmd->TexRef._TexData->UniqueID);
21952 return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->TexRef.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID()
21953 }
21954
21955 #ifdef IMGUI_ENABLE_FREETYPE
21956 namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); }
21957 #endif
21958
21959 // [DEBUG] List fonts in a font atlas and display its texture
21960 void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
21961 {
21962 ImGuiContext& g = *GImGui;
21963 ImGuiIO& io = g.IO;
21964 ImGuiStyle& style = g.Style;
21965
21966 BeginDisabled();
21967 CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures);
21968 EndDisabled();
21969 ShowFontSelector("Font");
21970 //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0);
21971 if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f"))
21972 style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work.
21973 SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize());
21974 SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.");
21975 DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f);
21976 //BeginDisabled(io.ConfigDpiScaleFonts);
21977 DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f);
21978 //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.");
21979 //EndDisabled();
21980 if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
21981 {
21982 BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!");
21983 BulletText("For instructions, see:");
21984 SameLine();
21985 TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md");
21986 }
21987 BulletText("Load a nice font for better results!");
21988 BulletText("Please submit feedback:");
21989 SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465");
21990 BulletText("Read FAQ for more details:");
21991 SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/");
21992 //EndDisabled();
21993
21994 SeparatorText("Font List");
21995
21996 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21997 Checkbox("Show font preview", &cfg->ShowFontPreview);
21998
21999 // Font loaders
22000 if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL"))
22001 {
22002 const ImFontLoader* loader_current = atlas->FontLoader;
22003 BeginDisabled(!atlas->RendererHasTextures);
22004 #ifdef IMGUI_ENABLE_STB_TRUETYPE
22005 const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype();
22006 if (RadioButton("stb_truetype", loader_current == loader_stbtruetype))
22007 atlas->SetFontLoader(loader_stbtruetype);
22008 #else
22009 BeginDisabled();
22010 RadioButton("stb_truetype", false);
22011 SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE");
22012 EndDisabled();
22013 #endif
22014 SameLine();
22015 #ifdef IMGUI_ENABLE_FREETYPE
22016 const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader();
22017 if (RadioButton("FreeType", loader_current == loader_freetype))
22018 atlas->SetFontLoader(loader_freetype);
22019 if (loader_current == loader_freetype)
22020 {
22021 unsigned int loader_flags = atlas->FontLoaderFlags;
22022 Text("Shared FreeType Loader Flags: 0x%08X", loader_flags);
22023 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
22024 {
22025 for (ImFont* font : atlas->Fonts)
22026 ImFontAtlasFontDestroyOutput(atlas, font);
22027 atlas->FontLoaderFlags = loader_flags;
22028 for (ImFont* font : atlas->Fonts)
22029 ImFontAtlasFontInitOutput(atlas, font);
22030 }
22031 }
22032 #else
22033 BeginDisabled();
22034 RadioButton("FreeType", false);
22035 SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp.");
22036 EndDisabled();
22037 #endif
22038 EndDisabled();
22039 TreePop();
22040 }
22041
22042 // Font list
22043 for (ImFont* font : atlas->Fonts)
22044 {
22045 PushID(font);
22046 DebugNodeFont(font);
22047 PopID();
22048 }
22049
22050 SeparatorText("Font Atlas");
22051 if (Button("Compact"))
22052 atlas->CompactCache();
22053 SameLine();
22054 if (Button("Grow"))
22055 ImFontAtlasTextureGrow(atlas);
22056 SameLine();
22057 if (Button("Clear All"))
22058 ImFontAtlasBuildClear(atlas);
22059 SetItemTooltip("Destroy cache and custom rectangles.");
22060
22061 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
22062 {
22063 ImTextureData* tex = atlas->TexList[tex_n];
22064 if (tex_n > 0)
22065 SameLine();
22066 Text("Tex: %dx%d", tex->Width, tex->Height);
22067 }
22068 const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface);
22069 const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface);
22070 Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt);
22071 Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt);
22072
22073 ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid;
22074 if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles
22075 {
22076 PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f);
22077 if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12)))
22078 {
22079 for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex)
22080 if (entry.IsUsed)
22081 {
22082 ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation);
22083 ImFontAtlasRect r = {};
22084 atlas->GetCustomRect(id, &r);
22085 const char* buf;
22086 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);
22087 TableNextColumn();
22088 Selectable(buf);
22089 if (IsItemHovered())
22090 highlight_r_id = id;
22091 TableNextColumn();
22092 Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
22093 }
22094 EndTable();
22095 }
22096 PopStyleVar();
22097 TreePop();
22098 }
22099
22100 // Texture list
22101 // (ensure the last texture always use the same ID, so we can keep it open neatly)
22102 ImFontAtlasRect highlight_r;
22103 if (highlight_r_id != ImFontAtlasRectId_Invalid)
22104 atlas->GetCustomRect(highlight_r_id, &highlight_r);
22105 for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++)
22106 {
22107 if (tex_n == atlas->TexList.Size - 1)
22108 SetNextItemOpen(true, ImGuiCond_Once);
22109 DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL);
22110 }
22111 }
22112
22113 void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect)
22114 {
22115 ImGuiContext& g = *GImGui;
22116 PushID(int_id);
22117 if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height))
22118 {
22119 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22120 Checkbox("Show used rect", &cfg->ShowTextureUsedRect);
22121 PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize));
22122 ImVec2 p = GetCursorScreenPos();
22123 if (tex->WantDestroyNextFrame)
22124 Dummy(ImVec2((float)tex->Width, (float)tex->Height));
22125 else
22126 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));
22127 if (cfg->ShowTextureUsedRect)
22128 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));
22129 if (highlight_rect != NULL)
22130 {
22131 ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height);
22132 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);
22133 RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f);
22134 GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255));
22135 }
22136 PopStyleVar();
22137
22138 char texid_desc[30];
22139 Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors);
22140 Text("TexID = %s, BackendUserData = %p", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID), tex->BackendUserData);
22141 TreePop();
22142 }
22143 PopID();
22144 }
22145
22146 void ImGui::ShowMetricsWindow(bool* p_open)
22147 {
22148 ImGuiContext& g = *GImGui;
22149 ImGuiIO& io = g.IO;
22150 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22151 if (cfg->ShowDebugLog)
22152 ShowDebugLogWindow(&cfg->ShowDebugLog);
22153 if (cfg->ShowIDStackTool)
22154 ShowIDStackToolWindow(&cfg->ShowIDStackTool);
22155
22156 if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
22157 {
22158 End();
22159 return;
22160 }
22161
22162 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
22163 DebugBreakClearData();
22164
22165 // Basic info
22166 Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
22167 if (g.ContextName[0] != 0)
22168 {
22169 SameLine();
22170 Text("(Context Name: \"%s\")", g.ContextName);
22171 }
22172 Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
22173 Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
22174 Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
22175 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
22176
22177 Separator();
22178
22179 // Debugging enums
22180 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
22181 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
22182 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
22183 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
22184 if (cfg->ShowWindowsRectsType < 0)
22185 cfg->ShowWindowsRectsType = WRT_WorkRect;
22186 if (cfg->ShowTablesRectsType < 0)
22187 cfg->ShowTablesRectsType = TRT_WorkRect;
22188
22189 struct Funcs
22190 {
22191 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
22192 {
22193 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
22194 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
22195 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
22196 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
22197 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
22198 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
22199 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
22200 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); }
22201 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); }
22202 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
22203 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
22204 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); }
22205 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); }
22206 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); }
22207 IM_ASSERT(0);
22208 return ImRect();
22209 }
22210
22211 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
22212 {
22213 if (rect_type == WRT_OuterRect) { return window->Rect(); }
22214 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
22215 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
22216 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
22217 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
22218 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
22219 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
22220 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
22221 IM_ASSERT(0);
22222 return ImRect();
22223 }
22224 };
22225
22226 #ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
22227 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");
22228 #endif
22229
22230 // Tools
22231 if (TreeNode("Tools"))
22232 {
22233 // Debug Break features
22234 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
22235 SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
22236 SameLine();
22237 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.");
22238 if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
22239 DebugStartItemPicker();
22240 Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
22241
22242 SeparatorText("Visualize");
22243
22244 Checkbox("Show Debug Log", &cfg->ShowDebugLog);
22245 SameLine();
22246 MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
22247
22248 Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
22249 SameLine();
22250 MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
22251
22252 Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
22253 Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
22254 SameLine();
22255 SetNextItemWidth(GetFontSize() * 12);
22256 cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
22257 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
22258 {
22259 BulletText("'%s':", g.NavWindow->Name);
22260 Indent();
22261 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
22262 {
22263 ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
22264 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]);
22265 }
22266 Unindent();
22267 }
22268
22269 Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
22270 SameLine();
22271 SetNextItemWidth(GetFontSize() * 12);
22272 cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
22273 if (cfg->ShowTablesRects && g.NavWindow != NULL)
22274 {
22275 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
22276 {
22277 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
22278 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
22279 continue;
22280
22281 BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
22282 if (IsItemHovered())
22283 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);
22284 Indent();
22285 char buf[128];
22286 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
22287 {
22288 if (rect_n >= TRT_ColumnsRect)
22289 {
22290 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
22291 continue;
22292 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
22293 {
22294 ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
22295 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]);
22296 Selectable(buf);
22297 if (IsItemHovered())
22298 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
22299 }
22300 }
22301 else
22302 {
22303 ImRect r = Funcs::GetTableRect(table, rect_n, -1);
22304 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]);
22305 Selectable(buf);
22306 if (IsItemHovered())
22307 GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
22308 }
22309 }
22310 Unindent();
22311 }
22312 }
22313 Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
22314
22315 SeparatorText("Validate");
22316
22317 Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
22318 SameLine();
22319 MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
22320
22321 Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
22322 SameLine();
22323 MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
22324 if (cfg->ShowTextEncodingViewer)
22325 {
22326 static char buf[64] = "";
22327 SetNextItemWidth(-FLT_MIN);
22328 InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
22329 if (buf[0] != 0)
22330 DebugTextEncoding(buf);
22331 }
22332
22333 TreePop();
22334 }
22335
22336 // Windows
22337 if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
22338 {
22339 //SetNextItemOpen(true, ImGuiCond_Once);
22340 DebugNodeWindowsList(&g.Windows, "By display order");
22341 DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
22342 if (TreeNode("By submission order (begin stack)"))
22343 {
22344 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
22345 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
22346 temp_buffer.resize(0);
22347 for (ImGuiWindow* window : g.Windows)
22348 if (window->LastFrameActive + 1 >= g.FrameCount)
22349 temp_buffer.push_back(window);
22350 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); } };
22351 ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
22352 DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
22353 TreePop();
22354 }
22355
22356 TreePop();
22357 }
22358
22359 // DrawLists
22360 int drawlist_count = 0;
22361 for (ImGuiViewportP* viewport : g.Viewports)
22362 drawlist_count += viewport->DrawDataP.CmdLists.Size;
22363 if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
22364 {
22365 Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
22366 Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
22367 for (ImGuiViewportP* viewport : g.Viewports)
22368 {
22369 bool viewport_has_drawlist = false;
22370 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
22371 {
22372 if (!viewport_has_drawlist)
22373 Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
22374 viewport_has_drawlist = true;
22375 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
22376 }
22377 }
22378 TreePop();
22379 }
22380
22381 // Viewports
22382 if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
22383 {
22384 cfg->HighlightMonitorIdx = -1;
22385 bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
22386 SameLine();
22387 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.");
22388 if (open)
22389 {
22390 for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
22391 {
22392 DebugNodePlatformMonitor(&g.PlatformIO.Monitors[i], "Monitor", i);
22393 if (IsItemHovered())
22394 cfg->HighlightMonitorIdx = i;
22395 }
22396 DebugNodePlatformMonitor(&g.FallbackMonitor, "Fallback", 0);
22397 TreePop();
22398 }
22399
22400 SetNextItemOpen(true, ImGuiCond_Once);
22401 if (TreeNode("Windows Minimap"))
22402 {
22403 RenderViewportsThumbnails();
22404 TreePop();
22405 }
22406 cfg->HighlightViewportID = 0;
22407
22408 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);
22409 if (TreeNode("Inferred Z order (front-to-back)"))
22410 {
22411 static ImVector<ImGuiViewportP*> viewports;
22412 viewports.resize(g.Viewports.Size);
22413 memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
22414 if (viewports.Size > 1)
22415 ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
22416 for (ImGuiViewportP* viewport : viewports)
22417 {
22418 BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
22419 viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
22420 (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
22421 viewport->Window ? viewport->Window->Name : "N/A");
22422 if (IsItemHovered())
22423 cfg->HighlightViewportID = viewport->ID;
22424 }
22425 TreePop();
22426 }
22427
22428 for (ImGuiViewportP* viewport : g.Viewports)
22429 DebugNodeViewport(viewport);
22430 TreePop();
22431 }
22432
22433 // Details for Fonts
22434 for (ImFontAtlas* atlas : g.FontAtlases)
22435 if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size))
22436 {
22437 ShowFontAtlas(atlas);
22438 TreePop();
22439 }
22440
22441 // Details for Popups
22442 if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
22443 {
22444 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
22445 {
22446 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
22447 ImGuiWindow* window = popup_data.Window;
22448 BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
22449 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
22450 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
22451 }
22452 TreePop();
22453 }
22454
22455 // Details for TabBars
22456 if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
22457 {
22458 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
22459 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
22460 {
22461 PushID(tab_bar);
22462 DebugNodeTabBar(tab_bar, "TabBar");
22463 PopID();
22464 }
22465 TreePop();
22466 }
22467
22468 // Details for Tables
22469 if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
22470 {
22471 for (int n = 0; n < g.Tables.GetMapSize(); n++)
22472 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
22473 DebugNodeTable(table);
22474 TreePop();
22475 }
22476
22477 // Details for InputText
22478 if (TreeNode("InputText"))
22479 {
22480 DebugNodeInputTextState(&g.InputTextState);
22481 TreePop();
22482 }
22483
22484 // Details for TypingSelect
22485 if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
22486 {
22487 DebugNodeTypingSelectState(&g.TypingSelectState);
22488 TreePop();
22489 }
22490
22491 // Details for MultiSelect
22492 if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
22493 {
22494 ImGuiBoxSelectState* bs = &g.BoxSelectState;
22495 BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
22496 for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
22497 if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
22498 DebugNodeMultiSelectState(state);
22499 TreePop();
22500 }
22501
22502 // Details for Docking
22503 #ifdef IMGUI_HAS_DOCK
22504 if (TreeNode("Docking"))
22505 {
22506 static bool root_nodes_only = true;
22507 ImGuiDockContext* dc = &g.DockContext;
22508 Checkbox("List root nodes", &root_nodes_only);
22509 Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
22510 if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
22511 SameLine();
22512 if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
22513 for (int n = 0; n < dc->Nodes.Data.Size; n++)
22514 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
22515 if (!root_nodes_only || node->IsRootNode())
22516 DebugNodeDockNode(node, "Node");
22517 TreePop();
22518 }
22519 #endif // #ifdef IMGUI_HAS_DOCK
22520
22521 // Settings
22522 if (TreeNode("Settings"))
22523 {
22524 if (SmallButton("Clear"))
22525 ClearIniSettings();
22526 SameLine();
22527 if (SmallButton("Save to memory"))
22528 SaveIniSettingsToMemory();
22529 SameLine();
22530 if (SmallButton("Save to disk"))
22531 SaveIniSettingsToDisk(g.IO.IniFilename);
22532 SameLine();
22533 if (g.IO.IniFilename)
22534 Text("\"%s\"", g.IO.IniFilename);
22535 else
22536 TextUnformatted("<NULL>");
22537 Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
22538 Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
22539 if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
22540 {
22541 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
22542 BulletText("\"%s\"", handler.TypeName);
22543 TreePop();
22544 }
22545 if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
22546 {
22547 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
22548 DebugNodeWindowSettings(settings);
22549 TreePop();
22550 }
22551
22552 if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
22553 {
22554 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
22555 DebugNodeTableSettings(settings);
22556 TreePop();
22557 }
22558
22559 #ifdef IMGUI_HAS_DOCK
22560 if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
22561 {
22562 ImGuiDockContext* dc = &g.DockContext;
22563 Text("In SettingsWindows:");
22564 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
22565 if (settings->DockId != 0)
22566 BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
22567 Text("In SettingsNodes:");
22568 for (int n = 0; n < dc->NodesSettings.Size; n++)
22569 {
22570 ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
22571 const char* selected_tab_name = NULL;
22572 if (settings->SelectedTabId)
22573 {
22574 if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
22575 selected_tab_name = window->Name;
22576 else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
22577 selected_tab_name = window_settings->GetName();
22578 }
22579 BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
22580 }
22581 TreePop();
22582 }
22583 #endif // #ifdef IMGUI_HAS_DOCK
22584
22585 if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
22586 {
22587 InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
22588 TreePop();
22589 }
22590 TreePop();
22591 }
22592
22593 // Settings
22594 if (TreeNode("Memory allocations"))
22595 {
22596 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
22597 Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
22598 if (SmallButton("GC now")) { g.GcCompactAll = true; }
22599 Text("Recent frames with allocations:");
22600 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
22601 for (int n = buf_size - 1; n >= 0; n--)
22602 {
22603 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
22604 BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
22605 if (n == 0)
22606 {
22607 SameLine();
22608 Text("<- %d frames ago", g.FrameCount - entry->FrameCount);
22609 }
22610 }
22611 TreePop();
22612 }
22613
22614 if (TreeNode("Inputs"))
22615 {
22616 Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
22617 {
22618 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
22619 Indent();
22620 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); }
22621 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); }
22622 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); }
22623 Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
22624 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.
22625 DebugRenderKeyboardPreview(GetWindowDrawList());
22626 Unindent();
22627 }
22628
22629 Text("MOUSE STATE");
22630 {
22631 Indent();
22632 if (IsMousePosValid())
22633 Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
22634 else
22635 Text("Mouse pos: <INVALID>");
22636 Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
22637 int count = IM_ARRAYSIZE(io.MouseDown);
22638 Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
22639 Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
22640 Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
22641 Text("Mouse wheel: %.1f", io.MouseWheel);
22642 Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
22643 Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
22644 Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
22645 Unindent();
22646 }
22647
22648 Text("MOUSE WHEELING");
22649 {
22650 Indent();
22651 Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
22652 Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
22653 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>");
22654 Unindent();
22655 }
22656
22657 Text("KEY OWNERS");
22658 {
22659 Indent();
22660 if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
22661 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
22662 {
22663 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
22664 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
22665 continue;
22666 Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
22667 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
22668 DebugLocateItemOnHover(owner_data->OwnerCurr);
22669 }
22670 EndChild();
22671 Unindent();
22672 }
22673 Text("SHORTCUT ROUTING");
22674 SameLine();
22675 MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
22676 {
22677 Indent();
22678 if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
22679 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
22680 {
22681 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
22682 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
22683 {
22684 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
22685 ImGuiKeyChord key_chord = key | routing_data->Mods;
22686 Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
22687 DebugLocateItemOnHover(routing_data->RoutingCurr);
22688 if (g.IO.ConfigDebugIsDebuggerPresent)
22689 {
22690 SameLine();
22691 if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
22692 g.DebugBreakInShortcutRouting = key_chord;
22693 }
22694 idx = routing_data->NextEntryIndex;
22695 }
22696 }
22697 EndChild();
22698 Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
22699 Unindent();
22700 }
22701 TreePop();
22702 }
22703
22704 if (TreeNode("Internal state"))
22705 {
22706 Text("WINDOWING");
22707 Indent();
22708 Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
22709 Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
22710 Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
22711 Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
22712 Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
22713 Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
22714 Unindent();
22715
22716 Text("ITEMS");
22717 Indent();
22718 Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
22719 DebugLocateItemOnHover(g.ActiveId);
22720 Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
22721 Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
22722 Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
22723 Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
22724 Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
22725 DebugLocateItemOnHover(g.DragDropPayload.SourceId);
22726 Unindent();
22727
22728 Text("NAV,FOCUS");
22729 Indent();
22730 Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
22731 Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
22732 DebugLocateItemOnHover(g.NavId);
22733 Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
22734 Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
22735 Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
22736 Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
22737 Text("NavActivateFlags: %04X", g.NavActivateFlags);
22738 Text("NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav);
22739 Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
22740 Text("NavFocusRoute[] = ");
22741 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
22742 {
22743 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
22744 SameLine(0.0f, 0.0f);
22745 Text("0x%08X/", focus_scope.ID);
22746 SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
22747 }
22748 Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
22749 Unindent();
22750
22751 TreePop();
22752 }
22753
22754 // Overlay: Display windows Rectangles and Begin Order
22755 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
22756 {
22757 for (ImGuiWindow* window : g.Windows)
22758 {
22759 if (!window->WasActive)
22760 continue;
22761 ImDrawList* draw_list = GetForegroundDrawList(window);
22762 if (cfg->ShowWindowsRects)
22763 {
22764 ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
22765 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
22766 }
22767 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
22768 {
22769 char buf[32];
22770 ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
22771 float font_size = GetFontSize();
22772 draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
22773 draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
22774 }
22775 }
22776 }
22777
22778 // Overlay: Display Tables Rectangles
22779 if (cfg->ShowTablesRects)
22780 {
22781 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
22782 {
22783 ImGuiTable* table = g.Tables.TryGetMapData(table_n);
22784 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
22785 continue;
22786 ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
22787 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
22788 {
22789 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
22790 {
22791 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
22792 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
22793 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
22794 draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
22795 }
22796 }
22797 else
22798 {
22799 ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
22800 draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
22801 }
22802 }
22803 }
22804
22805 #ifdef IMGUI_HAS_DOCK
22806 // Overlay: Display Docking info
22807 if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
22808 {
22809 char buf[64] = "";
22810 char* p = buf;
22811 ImGuiDockNode* node = g.DebugHoveredDockNode;
22812 ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
22813 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
22814 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
22815 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
22816 p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
22817 int depth = DockNodeGetDepth(node);
22818 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));
22819 ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
22820 overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
22821 overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
22822 }
22823 #endif // #ifdef IMGUI_HAS_DOCK
22824
22825 End();
22826 }
22827
22828 void ImGui::DebugBreakClearData()
22829 {
22830 // Those fields are scattered in their respective subsystem to stay in hot-data locations
22831 ImGuiContext& g = *GImGui;
22832 g.DebugBreakInWindow = 0;
22833 g.DebugBreakInTable = 0;
22834 g.DebugBreakInShortcutRouting = ImGuiKey_None;
22835 }
22836
22837 void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
22838 {
22839 if (!BeginItemTooltip())
22840 return;
22841 Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
22842 Separator();
22843 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.");
22844 Separator();
22845 TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
22846 EndTooltip();
22847 }
22848
22849 // Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
22850 // In order to reduce interferences with the contents we are trying to debug into.
22851 bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
22852 {
22853 ImGuiWindow* window = GetCurrentWindow();
22854 if (window->SkipItems)
22855 return false;
22856
22857 ImGuiContext& g = *GImGui;
22858 const ImGuiID id = window->GetID(label);
22859 const ImVec2 label_size = CalcTextSize(label, NULL, true);
22860 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
22861 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
22862
22863 const ImRect bb(pos, pos + size);
22864 ItemSize(size, 0.0f);
22865 if (!ItemAdd(bb, id))
22866 return false;
22867
22868 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
22869 bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
22870 bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
22871 DebugBreakButtonTooltip(false, description_of_location);
22872
22873 ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
22874 ImVec4 hsv;
22875 ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
22876 ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
22877
22878 RenderNavCursor(bb, id);
22879 RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
22880 RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
22881
22882 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
22883 return pressed;
22884 }
22885
22886 // [DEBUG] Display contents of Columns
22887 void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
22888 {
22889 if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
22890 return;
22891 BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
22892 for (ImGuiOldColumnData& column : columns->Columns)
22893 BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
22894 TreePop();
22895 }
22896
22897 static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
22898 {
22899 using namespace ImGui;
22900 PushID(label);
22901 PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
22902 Text("%s:", label);
22903 if (!enabled)
22904 BeginDisabled();
22905 CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
22906 CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
22907 CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
22908 CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
22909 CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
22910 CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
22911 CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
22912 CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
22913 CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
22914 CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
22915 CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
22916 CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
22917 CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
22918 CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
22919 CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
22920 if (!enabled)
22921 EndDisabled();
22922 PopStyleVar();
22923 PopID();
22924 }
22925
22926 // [DEBUG] Display contents of ImDockNode
22927 void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
22928 {
22929 ImGuiContext& g = *GImGui;
22930 const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
22931 const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted
22932 if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
22933 bool open;
22934 ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
22935 if (node->Windows.Size > 0)
22936 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");
22937 else
22938 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");
22939 if (!is_alive) { PopStyleColor(); }
22940 if (is_active && IsItemHovered())
22941 if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
22942 GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
22943 if (open)
22944 {
22945 IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
22946 IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
22947 BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
22948 node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
22949 DebugNodeWindow(node->HostWindow, "HostWindow");
22950 DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
22951 BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
22952 BulletText("Misc:%s%s%s%s%s%s%s",
22953 node->IsDockSpace() ? " IsDockSpace" : "",
22954 node->IsCentralNode() ? " IsCentralNode" : "",
22955 is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
22956 node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
22957 node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
22958 if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
22959 {
22960 if (BeginTable("flags", 4))
22961 {
22962 TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
22963 TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
22964 TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
22965 TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
22966 EndTable();
22967 }
22968 TreePop();
22969 }
22970 if (node->ParentNode)
22971 DebugNodeDockNode(node->ParentNode, "ParentNode");
22972 if (node->ChildNodes[0])
22973 DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
22974 if (node->ChildNodes[1])
22975 DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
22976 if (node->TabBar)
22977 DebugNodeTabBar(node->TabBar, "TabBar");
22978 DebugNodeWindowsList(&node->Windows, "Windows");
22979
22980 TreePop();
22981 }
22982 }
22983
22984 // [DEBUG] Display contents of ImDrawList
22985 // Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
22986 void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
22987 {
22988 ImGuiContext& g = *GImGui;
22989 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
22990 int cmd_count = draw_list->CmdBuffer.Size;
22991 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
22992 cmd_count--;
22993 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);
22994 if (draw_list == GetWindowDrawList())
22995 {
22996 SameLine();
22997 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)
22998 if (node_open)
22999 TreePop();
23000 return;
23001 }
23002
23003 ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
23004 if (window && IsItemHovered() && fg_draw_list)
23005 fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
23006 if (!node_open)
23007 return;
23008
23009 if (window && !window->WasActive)
23010 TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
23011
23012 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
23013 {
23014 if (pcmd->UserCallback)
23015 {
23016 BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
23017 continue;
23018 }
23019
23020 char texid_desc[30];
23021 FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd);
23022 char buf[300];
23023 ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
23024 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
23025 bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
23026 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
23027 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
23028 if (!pcmd_node_open)
23029 continue;
23030
23031 // Calculate approximate coverage area (touched pixel count)
23032 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
23033 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
23034 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
23035 float total_area = 0.0f;
23036 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
23037 {
23038 ImVec2 triangle[3];
23039 for (int n = 0; n < 3; n++, idx_n++)
23040 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
23041 total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
23042 }
23043
23044 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
23045 ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
23046 Selectable(buf);
23047 if (IsItemHovered() && fg_draw_list)
23048 DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
23049
23050 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
23051 ImGuiListClipper clipper;
23052 clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
23053 while (clipper.Step())
23054 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
23055 {
23056 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
23057 ImVec2 triangle[3];
23058 for (int n = 0; n < 3; n++, idx_i++)
23059 {
23060 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
23061 triangle[n] = v.pos;
23062 buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
23063 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
23064 }
23065
23066 Selectable(buf, false);
23067 if (fg_draw_list && IsItemHovered())
23068 {
23069 ImDrawListFlags backup_flags = fg_draw_list->Flags;
23070 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
23071 fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
23072 fg_draw_list->Flags = backup_flags;
23073 }
23074 }
23075 TreePop();
23076 }
23077 TreePop();
23078 }
23079
23080 // [DEBUG] Display mesh/aabb of a ImDrawCmd
23081 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
23082 {
23083 IM_ASSERT(show_mesh || show_aabb);
23084
23085 // Draw wire-frame version of all triangles
23086 ImRect clip_rect = draw_cmd->ClipRect;
23087 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
23088 ImDrawListFlags backup_flags = out_draw_list->Flags;
23089 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
23090 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
23091 {
23092 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
23093 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
23094
23095 ImVec2 triangle[3];
23096 for (int n = 0; n < 3; n++, idx_n++)
23097 vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
23098 if (show_mesh)
23099 out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
23100 }
23101 // Draw bounding boxes
23102 if (show_aabb)
23103 {
23104 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
23105 out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
23106 }
23107 out_draw_list->Flags = backup_flags;
23108 }
23109
23110 // [DEBUG] Compute mask of inputs with the same codepoint.
23111 static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint)
23112 {
23113 int mask = 0, count = 0;
23114 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
23115 {
23116 ImFontConfig* src = font->Sources[src_n];
23117 if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint))
23118 continue;
23119 mask |= (1 << src_n);
23120 count++;
23121 }
23122 return count > 1 ? mask : 0;
23123 }
23124
23125 // [DEBUG] Display details for a single font, called by ShowStyleEditor().
23126 void ImGui::DebugNodeFont(ImFont* font)
23127 {
23128 ImGuiContext& g = *GImGui;
23129 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
23130 ImFontAtlas* atlas = font->ContainerAtlas;
23131 bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size);
23132
23133 // Display preview text
23134 if (!opened)
23135 Indent();
23136 Indent();
23137 if (cfg->ShowFontPreview)
23138 {
23139 PushFont(font, 0.0f);
23140 Text("The quick brown fox jumps over the lazy dog");
23141 PopFont();
23142 }
23143 if (!opened)
23144 {
23145 Unindent();
23146 Unindent();
23147 return;
23148 }
23149 if (SmallButton("Set as default"))
23150 GetIO().FontDefault = font;
23151 SameLine();
23152 BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked);
23153 if (SmallButton("Remove"))
23154 atlas->RemoveFont(font);
23155 EndDisabled();
23156 SameLine();
23157 if (SmallButton("Clear bakes"))
23158 ImFontAtlasFontDiscardBakes(atlas, font, 0);
23159 SameLine();
23160 if (SmallButton("Clear unused"))
23161 ImFontAtlasFontDiscardBakes(atlas, font, 2);
23162
23163 // Display details
23164 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
23165 SetNextItemWidth(GetFontSize() * 8);
23166 DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
23167 /*SameLine(); MetricsHelpMarker(
23168 "Note that the default embedded font is NOT meant to be scaled.\n\n"
23169 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
23170 "You may oversample them to get some flexibility with scaling. "
23171 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
23172 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/
23173 #endif
23174
23175 char c_str[5];
23176 ImTextCharToUtf8(c_str, font->FallbackChar);
23177 Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar);
23178 ImTextCharToUtf8(c_str, font->EllipsisChar);
23179 Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar);
23180
23181 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
23182 {
23183 ImFontConfig* src = font->Sources[src_n];
23184 if (TreeNode(src, "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)",
23185 src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y))
23186 {
23187 const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader;
23188 Text("Loader: '%s'", loader->Name ? loader->Name : "N/A");
23189 #ifdef IMGUI_ENABLE_FREETYPE
23190 if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0)
23191 {
23192 unsigned int loader_flags = src->FontLoaderFlags;
23193 Text("FreeType Loader Flags: 0x%08X", loader_flags);
23194 if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags))
23195 {
23196 ImFontAtlasFontDestroyOutput(atlas, font);
23197 src->FontLoaderFlags = loader_flags;
23198 ImFontAtlasFontInitOutput(atlas, font);
23199 }
23200 }
23201 #endif
23202 TreePop();
23203 }
23204 }
23205 if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool"))
23206 {
23207 TextWrapped("- First Input that contains the glyph is used.\n"
23208 "- 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!");
23209 if (BeginTable("table", 2))
23210 {
23211 for (unsigned int c = 0; c < 0x10000; c++)
23212 if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c))
23213 {
23214 unsigned int c_end = c + 1;
23215 while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask)
23216 c_end++;
23217 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)))
23218 {
23219 char utf8_buf[5];
23220 for (unsigned int n = c; n < c_end; n++)
23221 {
23222 ImTextCharToUtf8(utf8_buf, n);
23223 BulletText("Codepoint U+%04X (%s)", n, utf8_buf);
23224 }
23225 TreePop();
23226 }
23227 TableNextColumn();
23228 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
23229 if (overlap_mask & (1 << src_n))
23230 {
23231 Text("%d ", src_n);
23232 SameLine();
23233 }
23234 c = c_end - 1;
23235 }
23236 EndTable();
23237 }
23238 TreePop();
23239 }
23240
23241 // Display all glyphs of the fonts in separate pages of 256 characters
23242 for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++)
23243 {
23244 ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n];
23245 if (baked->ContainerFont != font)
23246 continue;
23247 PushID(baked_n);
23248 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*" : ""))
23249 {
23250 if (SmallButton("Load all"))
23251 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++)
23252 baked->FindGlyph((ImWchar)base);
23253
23254 const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface);
23255 Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent);
23256 Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt);
23257 for (int src_n = 0; src_n < font->Sources.Size; src_n++)
23258 {
23259 ImFontConfig* src = font->Sources[src_n];
23260 int oversample_h, oversample_v;
23261 ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v);
23262 BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
23263 src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y);
23264 }
23265
23266 DebugNodeFontGlyphesForSrcMask(font, baked, ~0);
23267 TreePop();
23268 }
23269 PopID();
23270 }
23271 TreePop();
23272 Unindent();
23273 }
23274
23275 void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask)
23276 {
23277 ImDrawList* draw_list = GetWindowDrawList();
23278 const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
23279 const float cell_size = baked->Size * 1;
23280 const float cell_spacing = GetStyle().ItemSpacing.y;
23281 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
23282 {
23283 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
23284 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
23285 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
23286 if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191))
23287 {
23288 base += 8192 - 256;
23289 continue;
23290 }
23291
23292 int count = 0;
23293 for (unsigned int n = 0; n < 256; n++)
23294 if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL)
23295 if (src_mask & (1 << glyph->SourceIdx))
23296 count++;
23297 if (count <= 0)
23298 continue;
23299 if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
23300 continue;
23301
23302 // Draw a 16x16 grid of glyphs
23303 ImVec2 base_pos = GetCursorScreenPos();
23304 for (unsigned int n = 0; n < 256; n++)
23305 {
23306 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
23307 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
23308 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
23309 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
23310 const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL;
23311 draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
23312 if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0)
23313 continue;
23314 font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
23315 if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
23316 {
23317 DebugNodeFontGlyph(font, glyph);
23318 EndTooltip();
23319 }
23320 }
23321 Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
23322 TreePop();
23323 }
23324 }
23325
23326 void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph)
23327 {
23328 Text("Codepoint: U+%04X", glyph->Codepoint);
23329 Separator();
23330 Text("Visible: %d", glyph->Visible);
23331 Text("AdvanceX: %.1f", glyph->AdvanceX);
23332 Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
23333 Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
23334 if (glyph->PackId >= 0)
23335 {
23336 ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId);
23337 Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);
23338 }
23339 Text("SourceIdx: %d", glyph->SourceIdx);
23340 }
23341
23342 // [DEBUG] Display contents of ImGuiStorage
23343 void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
23344 {
23345 if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
23346 return;
23347 for (const ImGuiStoragePair& p : storage->Data)
23348 {
23349 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.
23350 DebugLocateItemOnHover(p.key);
23351 }
23352 TreePop();
23353 }
23354
23355 // [DEBUG] Display contents of ImGuiTabBar
23356 void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
23357 {
23358 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
23359 char buf[256];
23360 char* p = buf;
23361 const char* buf_end = buf + IM_ARRAYSIZE(buf);
23362 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
23363 p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
23364 for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
23365 {
23366 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
23367 p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
23368 }
23369 p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
23370 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
23371 bool open = TreeNode(label, "%s", buf);
23372 if (!is_active) { PopStyleColor(); }
23373 if (is_active && IsItemHovered())
23374 {
23375 ImDrawList* draw_list = GetForegroundDrawList();
23376 draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
23377 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));
23378 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));
23379 }
23380 if (open)
23381 {
23382 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
23383 {
23384 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
23385 PushID(tab);
23386 if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
23387 if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
23388 Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
23389 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
23390 PopID();
23391 }
23392 TreePop();
23393 }
23394 }
23395
23396 void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
23397 {
23398 ImGuiContext& g = *GImGui;
23399 SetNextItemOpen(true, ImGuiCond_Once);
23400 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");
23401 if (IsItemHovered())
23402 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
23403 if (open)
23404 {
23405 ImGuiWindowFlags flags = viewport->Flags;
23406 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%%",
23407 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
23408 viewport->FramebufferScale.x, viewport->FramebufferScale.y,
23409 viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y,
23410 viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
23411 if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
23412 BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
23413 //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
23414 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
23415 (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
23416 (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
23417 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
23418 (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
23419 (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
23420 (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
23421 (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
23422 (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
23423 (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
23424 (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
23425 (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
23426 (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
23427 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
23428 DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
23429 TreePop();
23430 }
23431 }
23432
23433 void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx)
23434 {
23435 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)",
23436 label, idx, monitor->DpiScale * 100.0f,
23437 monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y,
23438 monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y);
23439 }
23440
23441 void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
23442 {
23443 if (window == NULL)
23444 {
23445 BulletText("%s: NULL", label);
23446 return;
23447 }
23448
23449 ImGuiContext& g = *GImGui;
23450 const bool is_active = window->WasActive;
23451 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
23452 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
23453 const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
23454 if (!is_active) { PopStyleColor(); }
23455 if (IsItemHovered() && is_active)
23456 GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
23457 if (!open)
23458 return;
23459
23460 if (window->MemoryCompacted)
23461 TextDisabled("Note: some memory buffers have been compacted/freed.");
23462
23463 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
23464 g.DebugBreakInWindow = window->ID;
23465
23466 ImGuiWindowFlags flags = window->Flags;
23467 DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
23468 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);
23469 BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
23470 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
23471 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
23472 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
23473 if (flags & ImGuiWindowFlags_ChildWindow)
23474 BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
23475 (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "",
23476 (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
23477 (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
23478 (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
23479 BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
23480 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" : "");
23481 BulletText("InertialScrollSpeed: %.2f,%.2f",window->InertialScrollSpeed.x,window->InertialScrollSpeed.y);
23482 BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
23483 BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d, InertialScroll: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems, window->InertialScroll);
23484 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
23485 {
23486 ImRect r = window->NavRectRel[layer];
23487 if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
23488 BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
23489 else
23490 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);
23491 DebugLocateItemOnHover(window->NavLastIds[layer]);
23492 }
23493 const ImVec2* pr = window->NavPreferredScoringPosRel;
23494 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
23495 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.
23496 BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
23497
23498 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);
23499 BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
23500 BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
23501 if (window->DockNode || window->DockNodeAsHost)
23502 DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
23503
23504 if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
23505 if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
23506 if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
23507 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
23508 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
23509 if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
23510 {
23511 for (ImGuiOldColumns& columns : window->ColumnsStorage)
23512 DebugNodeColumns(&columns);
23513 TreePop();
23514 }
23515 DebugNodeStorage(&window->StateStorage, "Storage");
23516 TreePop();
23517 }
23518
23519 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
23520 {
23521 if (settings->WantDelete)
23522 BeginDisabled();
23523 Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
23524 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
23525 if (settings->WantDelete)
23526 EndDisabled();
23527 }
23528
23529 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
23530 {
23531 if (!TreeNode(label, "%s (%d)", label, windows->Size))
23532 return;
23533 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
23534 {
23535 PushID((*windows)[i]);
23536 DebugNodeWindow((*windows)[i], "Window");
23537 PopID();
23538 }
23539 TreePop();
23540 }
23541
23542 // FIXME-OPT: This is technically suboptimal, but it is simpler this way.
23543 void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
23544 {
23545 for (int i = 0; i < windows_size; i++)
23546 {
23547 ImGuiWindow* window = windows[i];
23548 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
23549 continue;
23550 char buf[20];
23551 ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
23552 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
23553 DebugNodeWindow(window, buf);
23554 TreePush(buf);
23555 DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
23556 TreePop();
23557 }
23558 }
23559
23560 //-----------------------------------------------------------------------------
23561 // [SECTION] DEBUG LOG WINDOW
23562 //-----------------------------------------------------------------------------
23563
23564 void ImGui::DebugLog(const char* fmt, ...)
23565 {
23566 va_list args;
23567 va_start(args, fmt);
23568 DebugLogV(fmt, args);
23569 va_end(args);
23570 }
23571
23572 void ImGui::DebugLogV(const char* fmt, va_list args)
23573 {
23574 ImGuiContext& g = *GImGui;
23575 const int old_size = g.DebugLogBuf.size();
23576 if (g.ContextName[0] != 0)
23577 g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
23578 else
23579 g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
23580 g.DebugLogBuf.appendfv(fmt, args);
23581 g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
23582 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
23583 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
23584 #ifdef IMGUI_ENABLE_TEST_ENGINE
23585 // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
23586 const int new_size = g.DebugLogBuf.size();
23587 const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
23588 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
23589 IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
23590 #endif
23591 }
23592
23593 // FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
23594 static void SameLineOrWrap(const ImVec2& size)
23595 {
23596 ImGuiContext& g = *GImGui;
23597 ImGuiWindow* window = g.CurrentWindow;
23598 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
23599 if (window->WorkRect.Contains(ImRect(pos, pos + size)))
23600 ImGui::SameLine();
23601 }
23602
23603 static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
23604 {
23605 ImGuiContext& g = *GImGui;
23606 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
23607 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
23608
23609 bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0);
23610 if (highlight_errors)
23611 ImGui::PushStyleColor(ImGuiCol_Text, ImLerp(g.Style.Colors[ImGuiCol_Text], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.30f));
23612 if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
23613 {
23614 g.DebugLogAutoDisableFrames = 2;
23615 g.DebugLogAutoDisableFlags |= flags;
23616 }
23617 if (highlight_errors)
23618 {
23619 ImGui::PopStyleColor();
23620 ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors);
23621 }
23622 else
23623 {
23624 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
23625 }
23626 }
23627
23628 void ImGui::ShowDebugLogWindow(bool* p_open)
23629 {
23630 ImGuiContext& g = *GImGui;
23631 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
23632 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
23633 if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
23634 {
23635 End();
23636 return;
23637 }
23638
23639 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
23640 CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
23641 SetItemTooltip("(except InputRouting which is spammy)");
23642
23643 ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError);
23644 ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
23645 ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
23646 ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
23647 ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
23648 ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
23649 ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont);
23650 ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
23651 ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
23652 ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
23653 ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
23654 ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
23655
23656 if (SmallButton("Clear"))
23657 {
23658 g.DebugLogBuf.clear();
23659 g.DebugLogIndex.clear();
23660 g.DebugLogSkippedErrors = 0;
23661 }
23662 SameLine();
23663 if (SmallButton("Copy"))
23664 SetClipboardText(g.DebugLogBuf.c_str());
23665 SameLine();
23666 if (SmallButton("Configure Outputs.."))
23667 OpenPopup("Outputs");
23668 if (BeginPopup("Outputs"))
23669 {
23670 CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
23671 #ifndef IMGUI_ENABLE_TEST_ENGINE
23672 BeginDisabled();
23673 #endif
23674 CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
23675 #ifndef IMGUI_ENABLE_TEST_ENGINE
23676 EndDisabled();
23677 #endif
23678 EndPopup();
23679 }
23680
23681 BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
23682
23683 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
23684 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
23685
23686 ImGuiListClipper clipper;
23687 clipper.Begin(g.DebugLogIndex.size());
23688 while (clipper.Step())
23689 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
23690 DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
23691 g.DebugLogFlags = backup_log_flags;
23692 if (GetScrollY() >= GetScrollMaxY())
23693 SetScrollHereY(1.0f);
23694 EndChild();
23695
23696 End();
23697 }
23698
23699 // Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
23700 void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
23701 {
23702 TextUnformatted(line_begin, line_end);
23703 if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
23704 return;
23705 ImGuiContext& g = *GImGui;
23706 ImRect text_rect = g.LastItemData.Rect;
23707 for (const char* p = line_begin; p <= line_end - 10; p++)
23708 {
23709 ImGuiID id = 0;
23710 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10]))
23711 continue;
23712 ImVec2 p0 = CalcTextSize(line_begin, p);
23713 ImVec2 p1 = CalcTextSize(p, p + 10);
23714 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
23715 if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
23716 DebugLocateItemOnHover(id);
23717 p += 10;
23718 }
23719 }
23720
23721 //-----------------------------------------------------------------------------
23722 // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
23723 //-----------------------------------------------------------------------------
23724
23725 // Draw a small cross at current CursorPos in current window's DrawList
23726 void ImGui::DebugDrawCursorPos(ImU32 col)
23727 {
23728 ImGuiContext& g = *GImGui;
23729 ImGuiWindow* window = g.CurrentWindow;
23730 ImVec2 pos = window->DC.CursorPos;
23731 window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
23732 window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
23733 }
23734
23735 // Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
23736 void ImGui::DebugDrawLineExtents(ImU32 col)
23737 {
23738 ImGuiContext& g = *GImGui;
23739 ImGuiWindow* window = g.CurrentWindow;
23740 float curr_x = window->DC.CursorPos.x;
23741 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
23742 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
23743 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
23744 window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
23745 window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
23746 }
23747
23748 // Draw last item rect in ForegroundDrawList (so it is always visible)
23749 void ImGui::DebugDrawItemRect(ImU32 col)
23750 {
23751 ImGuiContext& g = *GImGui;
23752 ImGuiWindow* window = g.CurrentWindow;
23753 GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
23754 }
23755
23756 // [DEBUG] Locate item position/rectangle given an ID.
23757 static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
23758
23759 void ImGui::DebugLocateItem(ImGuiID target_id)
23760 {
23761 ImGuiContext& g = *GImGui;
23762 g.DebugLocateId = target_id;
23763 g.DebugLocateFrames = 2;
23764 g.DebugBreakInLocateId = false;
23765 }
23766
23767 // FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
23768 void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
23769 {
23770 if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
23771 return;
23772 ImGuiContext& g = *GImGui;
23773 DebugLocateItem(target_id);
23774 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);
23775
23776 // Can't easily use a context menu here because it will mess with focus, active id etc.
23777 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
23778 {
23779 DebugBreakButtonTooltip(false, "in ItemAdd()");
23780 if (IsKeyChordPressed(g.DebugBreakKeyChord))
23781 g.DebugBreakInLocateId = true;
23782 }
23783 }
23784
23785 void ImGui::DebugLocateItemResolveWithLastItem()
23786 {
23787 ImGuiContext& g = *GImGui;
23788
23789 // [DEBUG] Debug break requested by user
23790 if (g.DebugBreakInLocateId)
23791 IM_DEBUG_BREAK();
23792
23793 ImGuiLastItemData item_data = g.LastItemData;
23794 g.DebugLocateId = 0;
23795 ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
23796 ImRect r = item_data.Rect;
23797 r.Expand(3.0f);
23798 ImVec2 p1 = g.IO.MousePos;
23799 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);
23800 draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
23801 draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
23802 }
23803
23804 void ImGui::DebugStartItemPicker()
23805 {
23806 ImGuiContext& g = *GImGui;
23807 g.DebugItemPickerActive = true;
23808 }
23809
23810 // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
23811 void ImGui::UpdateDebugToolItemPicker()
23812 {
23813 ImGuiContext& g = *GImGui;
23814 g.DebugItemPickerBreakId = 0;
23815 if (!g.DebugItemPickerActive)
23816 return;
23817
23818 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
23819 SetMouseCursor(ImGuiMouseCursor_Hand);
23820 if (IsKeyPressed(ImGuiKey_Escape))
23821 g.DebugItemPickerActive = false;
23822 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
23823 if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
23824 {
23825 g.DebugItemPickerBreakId = hovered_id;
23826 g.DebugItemPickerActive = false;
23827 }
23828 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
23829 if (change_mapping && IsMouseClicked(mouse_button))
23830 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
23831 SetNextWindowBgAlpha(0.70f);
23832 if (!BeginTooltip())
23833 return;
23834 Text("HoveredId: 0x%08X", hovered_id);
23835 Text("Press ESC to abort picking.");
23836 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
23837 if (change_mapping)
23838 Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
23839 else
23840 TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
23841 EndTooltip();
23842 }
23843
23844 // [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
23845 void ImGui::UpdateDebugToolStackQueries()
23846 {
23847 ImGuiContext& g = *GImGui;
23848 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23849
23850 // Clear hook when id stack tool is not visible
23851 g.DebugHookIdInfo = 0;
23852 if (g.FrameCount != tool->LastActiveFrame + 1)
23853 return;
23854
23855 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
23856 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
23857 const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
23858 if (tool->QueryId != query_id)
23859 {
23860 tool->QueryId = query_id;
23861 tool->StackLevel = -1;
23862 tool->Results.resize(0);
23863 }
23864 if (query_id == 0)
23865 return;
23866
23867 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
23868 int stack_level = tool->StackLevel;
23869 if (stack_level >= 0 && stack_level < tool->Results.Size)
23870 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
23871 tool->StackLevel++;
23872
23873 // Update hook
23874 stack_level = tool->StackLevel;
23875 if (stack_level == -1)
23876 g.DebugHookIdInfo = query_id;
23877 if (stack_level >= 0 && stack_level < tool->Results.Size)
23878 {
23879 g.DebugHookIdInfo = tool->Results[stack_level].ID;
23880 tool->Results[stack_level].QueryFrameCount++;
23881 }
23882 }
23883
23884 // [DEBUG] ID Stack tool: hooks called by GetID() family functions
23885 void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
23886 {
23887 ImGuiContext& g = *GImGui;
23888 ImGuiWindow* window = g.CurrentWindow;
23889 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23890
23891 // Step 0: stack query
23892 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
23893 if (tool->StackLevel == -1)
23894 {
23895 tool->StackLevel++;
23896 tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
23897 for (int n = 0; n < window->IDStack.Size + 1; n++)
23898 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
23899 return;
23900 }
23901
23902 // Step 1+: query for individual level
23903 IM_ASSERT(tool->StackLevel >= 0);
23904 if (tool->StackLevel != window->IDStack.Size)
23905 return;
23906 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
23907 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
23908
23909 switch (data_type)
23910 {
23911 case ImGuiDataType_S32:
23912 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
23913 break;
23914 case ImGuiDataType_String:
23915 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id);
23916 break;
23917 case ImGuiDataType_Pointer:
23918 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
23919 break;
23920 case ImGuiDataType_ID:
23921 if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
23922 return;
23923 ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
23924 break;
23925 default:
23926 IM_ASSERT(0);
23927 }
23928 info->QuerySuccess = true;
23929 info->DataType = data_type;
23930 }
23931
23932 static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
23933 {
23934 ImGuiStackLevelInfo* info = &tool->Results[n];
23935 ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
23936 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
23937 return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
23938 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
23939 return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
23940 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
23941 return (*buf = 0);
23942 #ifdef IMGUI_ENABLE_TEST_ENGINE
23943 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
23944 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
23945 #endif
23946 return ImFormatString(buf, buf_size, "???");
23947 }
23948
23949 // ID Stack Tool: Display UI
23950 void ImGui::ShowIDStackToolWindow(bool* p_open)
23951 {
23952 ImGuiContext& g = *GImGui;
23953 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0)
23954 SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
23955 if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
23956 {
23957 End();
23958 return;
23959 }
23960
23961 // Display hovered/active status
23962 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
23963
23964 // Build and display path
23965 tool->ResultPathBuf.resize(0);
23966 for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++)
23967 {
23968 char level_desc[256];
23969 StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
23970 tool->ResultPathBuf.append(stack_n == 0 ? "//" : "/");
23971 for (int n = 0; level_desc[n]; n++)
23972 {
23973 if (level_desc[n] == '/')
23974 tool->ResultPathBuf.append("\\");
23975 tool->ResultPathBuf.append(level_desc + n, level_desc + n + 1);
23976 }
23977 }
23978 Text("0x%08X", tool->QueryId);
23979 SameLine();
23980 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.");
23981
23982 // CTRL+C to copy path
23983 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
23984 SameLine();
23985 PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f); Checkbox("Ctrl+C: copy path", &tool->CopyToClipboardOnCtrlC); PopStyleVar();
23986 SameLine();
23987 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*");
23988 if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
23989 {
23990 tool->CopyToClipboardLastTime = (float)g.Time;
23991 SetClipboardText(tool->ResultPathBuf.c_str());
23992 }
23993
23994 Text("- Path \"%s\"", tool->ResultPathBuf.c_str());
23995 #ifdef IMGUI_ENABLE_TEST_ENGINE
23996 Text("- Label \"%s\"", tool->QueryId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryId) : "");
23997 #endif
23998
23999 Separator();
24000
24001 // Display decorated stack
24002 tool->LastActiveFrame = g.FrameCount;
24003 if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
24004 {
24005 const float id_width = CalcTextSize("0xDDDDDDDD").x;
24006 TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
24007 TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
24008 TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
24009 TableHeadersRow();
24010 for (int n = 0; n < tool->Results.Size; n++)
24011 {
24012 ImGuiStackLevelInfo* info = &tool->Results[n];
24013 TableNextColumn();
24014 Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
24015 TableNextColumn();
24016 StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
24017 TextUnformatted(g.TempBuffer.Data);
24018 TableNextColumn();
24019 Text("0x%08X", info->ID);
24020 if (n == tool->Results.Size - 1)
24021 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
24022 }
24023 EndTable();
24024 }
24025 End();
24026 }
24027
24028 #else
24029
24030 void ImGui::ShowMetricsWindow(bool*) {}
24031 void ImGui::ShowFontAtlas(ImFontAtlas*) {}
24032 void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
24033 void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
24034 void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
24035 void ImGui::DebugNodeFont(ImFont*) {}
24036 void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {}
24037 void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
24038 void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
24039 void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
24040 void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
24041 void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
24042 void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
24043
24044 void ImGui::ShowDebugLogWindow(bool*) {}
24045 void ImGui::ShowIDStackToolWindow(bool*) {}
24046 void ImGui::DebugStartItemPicker() {}
24047 void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
24048
24049 #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
24050
24051 #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
24052 // Demo helper function to select among loaded fonts.
24053 // Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.
24054 void ImGui::ShowFontSelector(const char* label)
24055 {
24056 ImGuiIO& io = GetIO();
24057 ImFont* font_current = GetFont();
24058 if (BeginCombo(label, font_current->GetDebugName()))
24059 {
24060 for (ImFont* font : io.Fonts->Fonts)
24061 {
24062 PushID((void*)font);
24063 if (Selectable(font->GetDebugName(), font == font_current))
24064 io.FontDefault = font;
24065 if (font == font_current)
24066 SetItemDefaultFocus();
24067 PopID();
24068 }
24069 EndCombo();
24070 }
24071 SameLine();
24072 if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
24073 MetricsHelpMarker(
24074 "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
24075 "- Read FAQ and docs/FONTS.md for more details.");
24076 else
24077 MetricsHelpMarker(
24078 "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n"
24079 "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
24080 "- Read FAQ and docs/FONTS.md for more details.\n"
24081 "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
24082 }
24083 #endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS)
24084
24085 //-----------------------------------------------------------------------------
24086
24087 // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
24088 // 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.
24089 #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
24090 #include "imgui_user.inl"
24091 #endif
24092
24093 //-----------------------------------------------------------------------------
24094
24095 #endif // #ifndef IMGUI_DISABLE