1// dear imgui, v1.90.5
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/6897 (please post your screenshots/video there!)
14// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21// - Issues & support ........... https://github.com/ocornut/imgui/issues
22// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24// For first-time users having issues compiling/linking/running/loading fonts:
25// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28// Copyright (c) 2014-2024 Omar Cornut
29// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30// See LICENSE.txt for copyright and licensing details (standard MIT License).
31// This library is free but needs your support to sustain development and maintenance.
32// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40// to a better solution or official support for them.
41
42/*
43
44Index of this file:
45
46DOCUMENTATION
47
48- MISSION STATEMENT
49- CONTROLS GUIDE
50- PROGRAMMER GUIDE
51 - READ FIRST
52 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55 - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56- API BREAKING CHANGES (read me when you update!)
57- FREQUENTLY ASKED QUESTIONS (FAQ)
58 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60CODE
61(search for "[SECTION]" in the code to find them)
62
63// [SECTION] INCLUDES
64// [SECTION] FORWARD DECLARATIONS
65// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69// [SECTION] MISC HELPERS/UTILITIES (File functions)
70// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72// [SECTION] ImGuiStorage
73// [SECTION] ImGuiTextFilter
74// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75// [SECTION] ImGuiListClipper
76// [SECTION] STYLING
77// [SECTION] RENDER HELPERS
78// [SECTION] INITIALIZATION, SHUTDOWN
79// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80// [SECTION] ID STACK
81// [SECTION] INPUTS
82// [SECTION] ERROR CHECKING
83// [SECTION] ITEM SUBMISSION
84// [SECTION] LAYOUT
85// [SECTION] SCROLLING
86// [SECTION] TOOLTIPS
87// [SECTION] POPUPS
88// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89// [SECTION] DRAG AND DROP
90// [SECTION] LOGGING/CAPTURING
91// [SECTION] SETTINGS
92// [SECTION] LOCALIZATION
93// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94// [SECTION] DOCKING
95// [SECTION] PLATFORM DEPENDENT HELPERS
96// [SECTION] METRICS/DEBUGGER WINDOW
97// [SECTION] DEBUG LOG WINDOW
98// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100*/
101
102//-----------------------------------------------------------------------------
103// DOCUMENTATION
104//-----------------------------------------------------------------------------
105
106/*
107
108 MISSION STATEMENT
109 =================
110
111 - Easy to use to create code-driven and data-driven tools.
112 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113 - Easy to hack and improve.
114 - Minimize setup and maintenance.
115 - Minimize state storage on user side.
116 - Minimize state synchronization.
117 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118 - Efficient runtime and memory consumption.
119
120 Designed primarily for developers and content-creators, not the typical end-user!
121 Some of the current weaknesses (which we aim to address in the future) includes:
122
123 - Doesn't look fancy.
124 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127 CONTROLS GUIDE
128 ==============
129
130 - MOUSE CONTROLS
131 - Mouse wheel: Scroll vertically.
132 - SHIFT+Mouse wheel: Scroll horizontally.
133 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134 - Click ^, Double-Click title: Collapse window.
135 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
136 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139 - TEXT EDITOR
140 - Hold SHIFT or Drag Mouse: Select text.
141 - CTRL+Left/Right: Word jump.
142 - CTRL+Shift+Left/Right: Select words.
143 - CTRL+A or Double-Click: Select All.
144 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
145 - CTRL+Z, CTRL+Y: Undo, Redo.
146 - ESCAPE: Revert text to its original value.
147 - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
148
149 - KEYBOARD CONTROLS
150 - Basic:
151 - Tab, SHIFT+Tab Cycle through text editable fields.
152 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
153 - CTRL+Click Input text into a Slider or Drag widget.
154 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155 - Tab, SHIFT+Tab: Cycle through every items.
156 - Arrow keys Move through items using directional navigation. Tweak value.
157 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
158 - Enter Activate item (prefer text input when possible).
159 - Space Activate item (prefer tweaking with arrows when possible).
160 - Escape Deactivate item, leave child window, close popup.
161 - Page Up, Page Down Previous page, next page.
162 - Home, End Scroll to top, scroll to bottom.
163 - Alt Toggle between scrolling layer and menu layer.
164 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
165 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170 - GAMEPAD CONTROLS
171 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174 - Backend support: backend needs to:
175 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177 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.).
178 - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182 - REMOTE INPUTS SHARING & MOUSE EMULATION
183 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184 - 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)
185 in order to share your PC mouse/keyboard.
186 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187 - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188 Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189 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.
190 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.
191 (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!)
192 (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
193 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196 PROGRAMMER GUIDE
197 ================
198
199 READ FIRST
200 ----------
201 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204 data retention on your side, less state duplication, less state synchronization, fewer bugs.
205 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211 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,
212 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215 If you get an assert, read the messages and comments around the assert.
216 - This codebase aims to be highly optimized:
217 - A typical idle frame should never call malloc/free.
218 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221 - This codebase aims to be both highly opinionated and highly flexible:
222 - This code works because of the things it choose to solve or not solve.
223 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225 This is to increase compatibility, increase maintainability and facilitate use from other languages.
226 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230 (so don't use ImVector in your code or at our own risk!).
231 - Building: We don't use nor mandate a build system for the main library.
232 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233 This is also because providing a build system for the main library would be of little-value.
234 The build problems are almost never coming from the main library but from specific backends.
235
236
237 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238 ----------------------------------------------
239 - Update submodule or copy/overwrite every file.
240 - About imconfig.h:
241 - You may modify your copy of imconfig.h, in this case don't overwrite it.
242 - or you may locally branch to modify imconfig.h and merge/rebase latest.
243 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244 specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252 likely be a comment about it. Please report any issue to the GitHub page!
253 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258 ---------------------------------------------------------------
259 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264 - 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.
265 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270 - 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.
271
272
273 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274 --------------------------------------
275 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276 The sub-folders in examples/ contain examples applications following this structure.
277
278 // Application init: create a dear imgui context, setup some options, load fonts
279 ImGui::CreateContext();
280 ImGuiIO& io = ImGui::GetIO();
281 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282 // TODO: Fill optional fields of the io structure later.
283 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286 ImGui_ImplWin32_Init(hwnd);
287 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289 // Application main loop
290 while (true)
291 {
292 // Feed inputs to dear imgui, start new frame
293 ImGui_ImplDX11_NewFrame();
294 ImGui_ImplWin32_NewFrame();
295 ImGui::NewFrame();
296
297 // Any application code here
298 ImGui::Text("Hello, world!");
299
300 // Render dear imgui into screen
301 ImGui::Render();
302 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303 g_pSwapChain->Present(1, 0);
304 }
305
306 // Shutdown
307 ImGui_ImplDX11_Shutdown();
308 ImGui_ImplWin32_Shutdown();
309 ImGui::DestroyContext();
310
311 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313 // Application init: create a dear imgui context, setup some options, load fonts
314 ImGui::CreateContext();
315 ImGuiIO& io = ImGui::GetIO();
316 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317 // TODO: Fill optional fields of the io structure later.
318 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320 // Build and load the texture atlas into a texture
321 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322 int width, height;
323 unsigned char* pixels = nullptr;
324 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326 // At this point you've got the texture data and you need to upload that to your graphic system:
327 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330 io.Fonts->SetTexID((void*)texture);
331
332 // Application main loop
333 while (true)
334 {
335 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
338 io.DisplaySize.x = 1920.0f; // set the current display width
339 io.DisplaySize.y = 1280.0f; // set the current display height here
340 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
341 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
342 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
343
344 // Call NewFrame(), after this point you can use ImGui::* functions anytime
345 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346 ImGui::NewFrame();
347
348 // Most of your application code here
349 ImGui::Text("Hello, world!");
350 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351 MyGameRender(); // may use any Dear ImGui functions as well!
352
353 // Render dear imgui, swap buffers
354 // (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)
355 ImGui::EndFrame();
356 ImGui::Render();
357 ImDrawData* draw_data = ImGui::GetDrawData();
358 MyImGuiRenderFunction(draw_data);
359 SwapBuffers();
360 }
361
362 // Shutdown
363 ImGui::DestroyContext();
364
365 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371 ---------------------------------------------
372 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374 void MyImGuiRenderFunction(ImDrawData* draw_data)
375 {
376 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377 // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381 ImVec2 clip_off = draw_data->DisplayPos;
382 for (int n = 0; n < draw_data->CmdListsCount; n++)
383 {
384 const ImDrawList* cmd_list = draw_data->CmdLists[n];
385 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
386 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
387 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388 {
389 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390 if (pcmd->UserCallback)
391 {
392 pcmd->UserCallback(cmd_list, pcmd);
393 }
394 else
395 {
396 // Project scissor/clipping rectangles into framebuffer space
397 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400 continue;
401
402 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404 // (some elements visible outside their bounds) but you can fix that once everything else works!
405 // - Clipping coordinates are provided in imgui coordinates space:
406 // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407 // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408 // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413 // The texture for the draw call is specified by pcmd->GetTexID().
414 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417 // Render 'pcmd->ElemCount/3' indexed triangles.
418 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420 }
421 }
422 }
423 }
424
425
426 API BREAKING CHANGES
427 ====================
428
429 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430 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.
431 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.
432 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434(Docking/Viewport Branch)
435 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436 - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437 you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438 - likewise io.MousePos and GetMousePos() will use OS coordinates.
439 If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441 - 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)
442 - 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)
443 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
444 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
445 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
446 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
447 - 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.
448 - 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.
449 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
450 - 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).
451 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.
452 - 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.
453 - old: BeginChild("Name", size, true)
454 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
455 - old: BeginChild("Name", size, false)
456 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
457 - 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.
458 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
459 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
460 - 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).
461 - 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)
462 - 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).
463 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
464 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
465 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
466 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
467 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
468 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
469 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
470 - 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
471 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
472 - 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)
473 - 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).
474 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
475 - 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.
476 - 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)
477 - 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.
478 - 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.
479 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
480 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
481 - ListBoxFooter() -> use EndListBox()
482 - 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().
483 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
484 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
485 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
486 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
487 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
488 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
489 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
490 - 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.
491 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
492 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
493 it has been frequently requested by people to use our own. We had an opt-in define which was
494 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
495 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
496 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
497 - 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.
498 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
499 - 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.
500 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
501 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
502 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
503 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
504 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
505 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
506 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
507 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.
508 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
509 this will require uses of legacy backend-dependent indices to be casted, e.g.
510 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
511 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
512 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
513 - 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);
514 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
515 - 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.
516 - 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.
517 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
518 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
519 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
520 - previously this would make the window content size ~200x200:
521 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
522 - instead, please submit an item:
523 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
524 - alternative:
525 Begin(...) + Dummy(ImVec2(200,200)) + End();
526 - content size is now only extended when submitting an item!
527 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
528 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
529 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
530 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
531 - 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));
532 - 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.
533 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
534 - 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));
535 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
536 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
537 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
538 - Official backends from 1.87+ -> no issue.
539 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
540 - Custom backends not writing to io.NavInputs[] -> no issue.
541 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
542 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
543 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
544 - 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.
545 - 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.
546 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
547 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
548 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
549 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
550 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
551 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
552 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
553 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
554 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
555 read https://github.com/ocornut/imgui/issues/4921 for details.
556 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. 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.
557 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
558 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
559 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
560 - 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.*
561 - 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.
562 - 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.
563 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
564 - 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'.
565 - 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)
566 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
567 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
568 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
569 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
570 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
571 - 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
572 - 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.
573 - 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.
574 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
575 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
576 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
577 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
578 - if you are using official backends from the source tree: you have nothing to do.
579 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
580 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
581 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
582 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
583 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
584 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
585 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
586 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
587 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
588 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
589 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
590 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
591 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.
592 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).
593 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
594 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
595 - 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.
596 - 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.
597 - 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'.
598 - 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.
599 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
600 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
601 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
602 - 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.
603 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
604 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
605 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
606 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
607 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
608 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
609 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
610 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
611 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
612 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
613 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
614 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
615 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
616 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
617 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
618 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
619 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
620 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
621 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
622 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
623 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
624 - 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).
625 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
626 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
627 - 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.
628 - 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.
629 - 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!
630 - 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().
631 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
632 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
633 - if you omitted the 'power' parameter (likely!), you are not affected.
634 - 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.
635 - 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.
636 see https://github.com/ocornut/imgui/issues/3361 for all details.
637 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.
638 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
639 - 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.
640 - 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.
641 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
642 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
643 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
644 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
645 - 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.
646 - 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.
647 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
648 - ShowTestWindow() -> use ShowDemoWindow()
649 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
650 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
651 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
652 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
653 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
654 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
655 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
656 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
657 - 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.
658 - 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).
659 - 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.
660 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
661 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
662 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
663 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
664 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
665 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
666 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
667 - ImFont::Glyph -> use ImFontGlyph
668 - 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.
669 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.
670 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).
671 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
672 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
673 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
674 - 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.
675 - 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
676 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.
677 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.
678 Please reach out if you are affected.
679 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
680 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
681 - 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.
682 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
683 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
684 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
685 - 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!
686 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
687 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
688 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
689 - 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.
690 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
691 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
692 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
693 - 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.
694 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
695 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
696 - 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.
697 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
698 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
699 - 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).
700 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
701 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
702 - 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.
703 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
704 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
705 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
706 - 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.).
707 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
708 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
709 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
710 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
711 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
712 - 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.
713 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
714 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.
715 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.
716 - 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",
717 consistent with other functions. Kept redirection functions (will obsolete).
718 - 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.
719 - 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).
720 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
721 - 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.
722 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
723 - 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.
724 - 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.
725 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
726 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
727 - removed Shutdown() function, as DestroyContext() serve this purpose.
728 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
729 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
730 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
731 - 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.
732 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
733 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
734 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
735 - 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.
736 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
737 - 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
738 - 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.
739 - 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.
740 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
741 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
742 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
743 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
744 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
745 - 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.
746 - 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.
747 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.
748 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
749 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
750 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
751 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
752 - 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.
753 - 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.
754 - 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.
755 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
756 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
757 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
758 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
759 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
760 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
761 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
762 - 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).
763 - 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)".
764 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
765 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
766 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
767 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
768 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
769 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
770 - 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.
771 - 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).
772 - 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).
773 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
774 - 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.
775 - 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.
776 - 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))'
777 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
778 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
779 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
780 - 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().
781 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
782 - 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.
783 - 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.
784 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
785 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.
786 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:
787 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); }
788 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.
789 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
790 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
791 - 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).
792 - 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.
793 - 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).
794 - 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)
795 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
796 - 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.
797 - 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.
798 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
799 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
800 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
801 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.
802 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!
803 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
804 - 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.
805 - 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
806 - 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.
807 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
808 - 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.
809 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
810 - 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.
811 - the signature of the io.RenderDrawListsFn handler has changed!
812 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
813 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
814 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
815 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
816 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
817 - 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.
818 - 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!
819 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
820 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
821 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
822 - 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.
823 - 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
824 - 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!
825 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
826 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
827 - 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.
828 - 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.
829 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
830 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
831 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
832 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
833 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
834 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
835 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
836 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
837 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
838 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
839 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
840 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
841 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
842 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
843 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
844 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
845 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
846 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
847 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
848 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
849 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.
850 - 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()
851 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
852 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
853 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
854 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
855 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
856 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
857 - 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)
858 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
859 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
860 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
861 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
862 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
863 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
864
865
866 FREQUENTLY ASKED QUESTIONS (FAQ)
867 ================================
868
869 Read all answers online:
870 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
871 Read all answers locally (with a text editor or ideally a Markdown viewer):
872 docs/FAQ.md
873 Some answers are copied down here to facilitate searching in code.
874
875 Q&A: Basics
876 ===========
877
878 Q: Where is the documentation?
879 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
880 - Run the examples/ applications and explore them.
881 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
882 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
883 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
884 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
885 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
886 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
887 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
888 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
889 - Your programming IDE is your friend, find the type or function declaration to find comments
890 associated with it.
891
892 Q: What is this library called?
893 Q: Which version should I get?
894 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
895 >> See https://www.dearimgui.com/faq for details.
896
897 Q&A: Integration
898 ================
899
900 Q: How to get started?
901 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
902
903 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
904 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
905 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
906
907 Q. How can I enable keyboard or gamepad controls?
908 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
909 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
910 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
911 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
912 >> See https://www.dearimgui.com/faq
913
914 Q&A: Usage
915 ----------
916
917 Q: About the ID Stack system..
918 - Why is my widget not reacting when I click on it?
919 - How can I have widgets with an empty label?
920 - How can I have multiple widgets with the same label?
921 - How can I have multiple windows with the same label?
922 Q: How can I display an image? What is ImTextureID, how does it work?
923 Q: How can I use my own math types instead of ImVec2?
924 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
925 Q: How can I display custom shapes? (using low-level ImDrawList API)
926 >> See https://www.dearimgui.com/faq
927
928 Q&A: Fonts, Text
929 ================
930
931 Q: How should I handle DPI in my application?
932 Q: How can I load a different font than the default?
933 Q: How can I easily use icons in my application?
934 Q: How can I load multiple fonts?
935 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
936 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
937
938 Q&A: Concerns
939 =============
940
941 Q: Who uses Dear ImGui?
942 Q: Can you create elaborate/serious tools with Dear ImGui?
943 Q: Can you reskin the look of Dear ImGui?
944 Q: Why using C++ (as opposed to C)?
945 >> See https://www.dearimgui.com/faq
946
947 Q&A: Community
948 ==============
949
950 Q: How can I help?
951 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
952 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
953 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
954 >>> See https://github.com/ocornut/imgui/wiki/Funding
955 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
956 - 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!
957 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
958 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
959 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
960 - 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).
961
962*/
963
964//-------------------------------------------------------------------------
965// [SECTION] INCLUDES
966//-------------------------------------------------------------------------
967
968#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
969#define _CRT_SECURE_NO_WARNINGS
970#endif
971
972#ifndef IMGUI_DEFINE_MATH_OPERATORS
973#define IMGUI_DEFINE_MATH_OPERATORS
974#endif
975
976#include "imgui.h"
977#ifndef IMGUI_DISABLE
978#include "imgui_internal.h"
979
980// System includes
981#include <stdio.h> // vsnprintf, sscanf, printf
982#include <stdint.h> // intptr_t
983
984// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
985#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
986#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
987#endif
988
989// [Windows] OS specific includes (optional)
990#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_WIN32_FUNCTIONS)
991#define IMGUI_DISABLE_WIN32_FUNCTIONS
992#endif
993#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
994#ifndef WIN32_LEAN_AND_MEAN
995#define WIN32_LEAN_AND_MEAN
996#endif
997#ifndef NOMINMAX
998#define NOMINMAX
999#endif
1000#ifndef __MINGW32__
1001#include <Windows.h> // _wfopen, OpenClipboard
1002#else
1003#include <windows.h>
1004#endif
1005#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
1006#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1007#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1008#endif
1009#endif
1010
1011// [Apple] OS specific includes
1012#if defined(__APPLE__)
1013#include <TargetConditionals.h>
1014#endif
1015
1016// Visual Studio warnings
1017#ifdef _MSC_VER
1018#pragma warning (disable: 4127) // condition expression is constant
1019#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1020#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1021#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1022#endif
1023#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).
1024#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1025#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1026#endif
1027
1028// Clang/GCC warnings with -Weverything
1029#if defined(__clang__)
1030#if __has_warning("-Wunknown-warning-option")
1031#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!
1032#endif
1033#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1034#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1035#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.
1036#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.
1037#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.
1038#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1039#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1040#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.
1041#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1042#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1043#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.
1044#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1045#elif defined(__GNUC__)
1046// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1047#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1048#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1049#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1050#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1051#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1052#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1053#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1054#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1055#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
1056#endif
1057
1058// Debug options
1059#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1060#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1061
1062// 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.
1063static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1064static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1065
1066static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1067
1068// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1069static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1070static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1071static 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.
1072
1073// Tooltip offset
1074static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1075
1076// Docking
1077static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1078
1079//-------------------------------------------------------------------------
1080// [SECTION] FORWARD DECLARATIONS
1081//-------------------------------------------------------------------------
1082
1083static void SetCurrentWindow(ImGuiWindow* window);
1084static void FindHoveredWindow();
1085static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1086static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1087
1088static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1089
1090// Settings
1091static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1092static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1093static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1094static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1095static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1096
1097// Platform Dependents default implementation for IO functions
1098static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1099static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1100static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1101
1102namespace ImGui
1103{
1104// Navigation
1105static void NavUpdate();
1106static void NavUpdateWindowing();
1107static void NavUpdateWindowingOverlay();
1108static void NavUpdateCancelRequest();
1109static void NavUpdateCreateMoveRequest();
1110static void NavUpdateCreateTabbingRequest();
1111static float NavUpdatePageUpPageDown();
1112static inline void NavUpdateAnyRequestFlag();
1113static void NavUpdateCreateWrappingRequest();
1114static void NavEndFrame();
1115static bool NavScoreItem(ImGuiNavItemData* result);
1116static void NavApplyItemToResult(ImGuiNavItemData* result);
1117static void NavProcessItem();
1118static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1119static ImVec2 NavCalcPreferredRefPos();
1120static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1121static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1122static void NavRestoreLayer(ImGuiNavLayer layer);
1123static int FindWindowFocusIndex(ImGuiWindow* window);
1124
1125// Error Checking and Debug Tools
1126static void ErrorCheckNewFrameSanityChecks();
1127static void ErrorCheckEndFrameSanityChecks();
1128static void UpdateDebugToolItemPicker();
1129static void UpdateDebugToolStackQueries();
1130static void UpdateDebugToolFlashStyleColor();
1131
1132// Inputs
1133static void UpdateKeyboardInputs();
1134static void UpdateMouseInputs();
1135static void UpdateMouseWheel();
1136static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1137
1138// Misc
1139static void UpdateSettings();
1140static 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);
1141static void RenderWindowOuterBorders(ImGuiWindow* window);
1142static 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);
1143static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1144static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1145static void RenderDimmedBackgrounds();
1146
1147// Viewports
1148const 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.
1149static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1150static void DestroyViewport(ImGuiViewportP* viewport);
1151static void UpdateViewportsNewFrame();
1152static void UpdateViewportsEndFrame();
1153static void WindowSelectViewport(ImGuiWindow* window);
1154static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1155static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1156static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1157static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1158static int FindPlatformMonitorForPos(const ImVec2& pos);
1159static int FindPlatformMonitorForRect(const ImRect& r);
1160static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1161
1162}
1163
1164//-----------------------------------------------------------------------------
1165// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1166//-----------------------------------------------------------------------------
1167
1168// DLL users:
1169// - Heaps and globals are not shared across DLL boundaries!
1170// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1171// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1172// - 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.
1173// - 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).
1174
1175// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1176// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1177// Change to a different context by calling ImGui::SetCurrentContext().
1178// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1179// If you want thread-safety to allow N threads to access N different contexts:
1180// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1181// struct ImGuiContext;
1182// extern thread_local ImGuiContext* MyImGuiTLS;
1183// #define GImGui MyImGuiTLS
1184// 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.
1185// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1186// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1187// - DLL users: read comments above.
1188#ifndef GImGui
1189ImGuiContext* GImGui = NULL;
1190#endif
1191
1192// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1193// - 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.
1194// - DLL users: read comments above.
1195#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1196static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size: size); }
1197static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr: ptr); }
1198#else
1199static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1200static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1201#endif
1202static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1203static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1204static void* GImAllocatorUserData = NULL;
1205
1206//-----------------------------------------------------------------------------
1207// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1208//-----------------------------------------------------------------------------
1209
1210ImGuiStyle::ImGuiStyle()
1211{
1212 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1213 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1214 WindowPadding = ImVec2(8,8); // Padding within a window
1215 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.
1216 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1217 WindowMinSize = ImVec2(32,32); // Minimum window size
1218 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1219 WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1220 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1221 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1222 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1223 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1224 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1225 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1226 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1227 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1228 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1229 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1230 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!
1231 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1232 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1233 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1234 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1235 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1236 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1237 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1238 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1239 TabBorderSize = 0.0f; // Thickness of border around tabs.
1240 TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1241 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1242 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1243 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1244 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1245 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.
1246 SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText()
1247 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1248 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.
1249 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.
1250 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.
1251 DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
1252 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1253 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1254 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1255 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1256 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.
1257 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.
1258
1259 // Behaviors
1260 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1261 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1262 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1263 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1264 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1265
1266 // Default theme
1267 ImGui::StyleColorsDark(dst: this);
1268}
1269
1270// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1271// 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.
1272void ImGuiStyle::ScaleAllSizes(float scale_factor)
1273{
1274 WindowPadding = ImTrunc(v: WindowPadding * scale_factor);
1275 WindowRounding = ImTrunc(f: WindowRounding * scale_factor);
1276 WindowMinSize = ImTrunc(v: WindowMinSize * scale_factor);
1277 ChildRounding = ImTrunc(f: ChildRounding * scale_factor);
1278 PopupRounding = ImTrunc(f: PopupRounding * scale_factor);
1279 FramePadding = ImTrunc(v: FramePadding * scale_factor);
1280 FrameRounding = ImTrunc(f: FrameRounding * scale_factor);
1281 ItemSpacing = ImTrunc(v: ItemSpacing * scale_factor);
1282 ItemInnerSpacing = ImTrunc(v: ItemInnerSpacing * scale_factor);
1283 CellPadding = ImTrunc(v: CellPadding * scale_factor);
1284 TouchExtraPadding = ImTrunc(v: TouchExtraPadding * scale_factor);
1285 IndentSpacing = ImTrunc(f: IndentSpacing * scale_factor);
1286 ColumnsMinSpacing = ImTrunc(f: ColumnsMinSpacing * scale_factor);
1287 ScrollbarSize = ImTrunc(f: ScrollbarSize * scale_factor);
1288 ScrollbarRounding = ImTrunc(f: ScrollbarRounding * scale_factor);
1289 GrabMinSize = ImTrunc(f: GrabMinSize * scale_factor);
1290 GrabRounding = ImTrunc(f: GrabRounding * scale_factor);
1291 LogSliderDeadzone = ImTrunc(f: LogSliderDeadzone * scale_factor);
1292 TabRounding = ImTrunc(f: TabRounding * scale_factor);
1293 TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(f: TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1294 SeparatorTextPadding = ImTrunc(v: SeparatorTextPadding * scale_factor);
1295 DockingSeparatorSize = ImTrunc(f: DockingSeparatorSize * scale_factor);
1296 DisplayWindowPadding = ImTrunc(v: DisplayWindowPadding * scale_factor);
1297 DisplaySafeAreaPadding = ImTrunc(v: DisplaySafeAreaPadding * scale_factor);
1298 MouseCursorScale = ImTrunc(f: MouseCursorScale * scale_factor);
1299}
1300
1301ImGuiIO::ImGuiIO()
1302{
1303 // Most fields are initialized with zero
1304 memset(s: this, c: 0, n: sizeof(*this));
1305 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1306
1307 // Settings
1308 ConfigFlags = ImGuiConfigFlags_None;
1309 BackendFlags = ImGuiBackendFlags_None;
1310 DisplaySize = ImVec2(-1.0f, -1.0f);
1311 DeltaTime = 1.0f / 60.0f;
1312 IniSavingRate = 5.0f;
1313 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).
1314 LogFilename = "imgui_log.txt";
1315#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1316 for (int i = 0; i < ImGuiKey_COUNT; i++)
1317 KeyMap[i] = -1;
1318#endif
1319 UserData = NULL;
1320
1321 Fonts = NULL;
1322 FontGlobalScale = 1.0f;
1323 FontDefault = NULL;
1324 FontAllowUserScaling = false;
1325 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1326
1327 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1328 ConfigDockingNoSplit = false;
1329 ConfigDockingWithShift = false;
1330 ConfigDockingAlwaysTabBar = false;
1331 ConfigDockingTransparentPayload = false;
1332
1333 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1334 ConfigViewportsNoAutoMerge = false;
1335 ConfigViewportsNoTaskBarIcon = false;
1336 ConfigViewportsNoDecoration = true;
1337 ConfigViewportsNoDefaultParent = false;
1338
1339 // Miscellaneous options
1340 MouseDrawCursor = false;
1341#ifdef __APPLE__
1342 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1343#else
1344 ConfigMacOSXBehaviors = false;
1345#endif
1346 ConfigInputTrickleEventQueue = true;
1347 ConfigInputTextCursorBlink = true;
1348 ConfigInputTextEnterKeepActive = false;
1349 ConfigDragClickToInputText = false;
1350 ConfigWindowsResizeFromEdges = true;
1351 ConfigWindowsMoveFromTitleBarOnly = false;
1352 ConfigMemoryCompactTimer = 60.0f;
1353 ConfigDebugBeginReturnValueOnce = false;
1354 ConfigDebugBeginReturnValueLoop = false;
1355
1356 // Inputs Behaviors
1357 MouseDoubleClickTime = 0.30f;
1358 MouseDoubleClickMaxDist = 6.0f;
1359 MouseDragThreshold = 6.0f;
1360 KeyRepeatDelay = 0.275f;
1361 KeyRepeatRate = 0.050f;
1362
1363 // Platform Functions
1364 // Note: Initialize() will setup default clipboard/ime handlers.
1365 BackendPlatformName = BackendRendererName = NULL;
1366 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1367 PlatformLocaleDecimalPoint = '.';
1368
1369 // Input (NB: we already have memset zero the entire structure!)
1370 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1371 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1372 MouseSource = ImGuiMouseSource_Mouse;
1373 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1374 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1375 AppAcceptingEvents = true;
1376 BackendUsingLegacyKeyArrays = (ImS8)-1;
1377 BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1378}
1379
1380// Pass in translated ASCII characters for text input.
1381// - with glfw you can get those from the callback set in glfwSetCharCallback()
1382// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1383// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1384void ImGuiIO::AddInputCharacter(unsigned int c)
1385{
1386 IM_ASSERT(Ctx != NULL);
1387 ImGuiContext& g = *Ctx;
1388 if (c == 0 || !AppAcceptingEvents)
1389 return;
1390
1391 ImGuiInputEvent e;
1392 e.Type = ImGuiInputEventType_Text;
1393 e.Source = ImGuiInputSource_Keyboard;
1394 e.EventId = g.InputEventsNextEventId++;
1395 e.Text.Char = c;
1396 g.InputEventsQueue.push_back(v: e);
1397}
1398
1399// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1400// we should save the high surrogate.
1401void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1402{
1403 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1404 return;
1405
1406 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1407 {
1408 if (InputQueueSurrogate != 0)
1409 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1410 InputQueueSurrogate = c;
1411 return;
1412 }
1413
1414 ImWchar cp = c;
1415 if (InputQueueSurrogate != 0)
1416 {
1417 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1418 {
1419 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1420 }
1421 else
1422 {
1423#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1424 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1425#else
1426 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1427#endif
1428 }
1429
1430 InputQueueSurrogate = 0;
1431 }
1432 AddInputCharacter(c: (unsigned)cp);
1433}
1434
1435void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1436{
1437 if (!AppAcceptingEvents)
1438 return;
1439 while (*utf8_chars != 0)
1440 {
1441 unsigned int c = 0;
1442 utf8_chars += ImTextCharFromUtf8(out_char: &c, in_text: utf8_chars, NULL);
1443 AddInputCharacter(c);
1444 }
1445}
1446
1447// Clear all incoming events.
1448void ImGuiIO::ClearEventsQueue()
1449{
1450 IM_ASSERT(Ctx != NULL);
1451 ImGuiContext& g = *Ctx;
1452 g.InputEventsQueue.clear();
1453}
1454
1455// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1456void ImGuiIO::ClearInputKeys()
1457{
1458#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1459 memset(s: KeysDown, c: 0, n: sizeof(KeysDown));
1460#endif
1461 for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1462 {
1463 KeysData[n].Down = false;
1464 KeysData[n].DownDuration = -1.0f;
1465 KeysData[n].DownDurationPrev = -1.0f;
1466 }
1467 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1468 KeyMods = ImGuiMod_None;
1469 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1470 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1471 {
1472 MouseDown[n] = false;
1473 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1474 }
1475 MouseWheel = MouseWheelH = 0.0f;
1476 InputQueueCharacters.resize(new_size: 0); // Behavior of old ClearInputCharacters().
1477}
1478
1479// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1480// Current frame character buffer is now also cleared by ClearInputKeys().
1481#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1482void ImGuiIO::ClearInputCharacters()
1483{
1484 InputQueueCharacters.resize(new_size: 0);
1485}
1486#endif
1487
1488static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1489{
1490 ImGuiContext& g = *ctx;
1491 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1492 {
1493 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1494 if (e->Type != type)
1495 continue;
1496 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1497 continue;
1498 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1499 continue;
1500 return e;
1501 }
1502 return NULL;
1503}
1504
1505// Queue a new key down/up event.
1506// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1507// - bool down: Is the key down? use false to signify a key release.
1508// - float analog_value: 0.0f..1.0f
1509// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1510// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1511void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1512{
1513 //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); }
1514 IM_ASSERT(Ctx != NULL);
1515 if (key == ImGuiKey_None || !AppAcceptingEvents)
1516 return;
1517 ImGuiContext& g = *Ctx;
1518 IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1519 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1520 IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1521
1522 // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1523#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1524 IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1525 if (BackendUsingLegacyKeyArrays == -1)
1526 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1527 IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1528 BackendUsingLegacyKeyArrays = 0;
1529#endif
1530 if (ImGui::IsGamepadKey(key))
1531 BackendUsingLegacyNavInputArray = false;
1532
1533 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1534 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)key);
1535 const ImGuiKeyData* key_data = ImGui::GetKeyData(ctx: &g, key);
1536 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1537 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1538 if (latest_key_down == down && latest_key_analog == analog_value)
1539 return;
1540
1541 // Add event
1542 ImGuiInputEvent e;
1543 e.Type = ImGuiInputEventType_Key;
1544 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1545 e.EventId = g.InputEventsNextEventId++;
1546 e.Key.Key = key;
1547 e.Key.Down = down;
1548 e.Key.AnalogValue = analog_value;
1549 g.InputEventsQueue.push_back(v: e);
1550}
1551
1552void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1553{
1554 if (!AppAcceptingEvents)
1555 return;
1556 AddKeyAnalogEvent(key, down, analog_value: down ? 1.0f : 0.0f);
1557}
1558
1559// [Optional] Call after AddKeyEvent().
1560// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1561// 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.
1562void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1563{
1564 if (key == ImGuiKey_None)
1565 return;
1566 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1567 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1568 IM_UNUSED(native_keycode); // Yet unused
1569 IM_UNUSED(native_scancode); // Yet unused
1570
1571 // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1572#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1573 const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1574 if (!ImGui::IsLegacyKey(key: (ImGuiKey)legacy_key))
1575 return;
1576 KeyMap[legacy_key] = key;
1577 KeyMap[key] = legacy_key;
1578#else
1579 IM_UNUSED(key);
1580 IM_UNUSED(native_legacy_index);
1581#endif
1582}
1583
1584// 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.
1585void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1586{
1587 AppAcceptingEvents = accepting_events;
1588}
1589
1590// Queue a mouse move event
1591void ImGuiIO::AddMousePosEvent(float x, float y)
1592{
1593 IM_ASSERT(Ctx != NULL);
1594 ImGuiContext& g = *Ctx;
1595 if (!AppAcceptingEvents)
1596 return;
1597
1598 // Apply same flooring as UpdateMouseInputs()
1599 ImVec2 pos((x > -FLT_MAX) ? ImFloor(f: x) : x, (y > -FLT_MAX) ? ImFloor(f: y) : y);
1600
1601 // Filter duplicate
1602 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MousePos);
1603 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1604 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1605 return;
1606
1607 ImGuiInputEvent e;
1608 e.Type = ImGuiInputEventType_MousePos;
1609 e.Source = ImGuiInputSource_Mouse;
1610 e.EventId = g.InputEventsNextEventId++;
1611 e.MousePos.PosX = pos.x;
1612 e.MousePos.PosY = pos.y;
1613 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1614 g.InputEventsQueue.push_back(v: e);
1615}
1616
1617void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1618{
1619 IM_ASSERT(Ctx != NULL);
1620 ImGuiContext& g = *Ctx;
1621 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1622 if (!AppAcceptingEvents)
1623 return;
1624
1625 // Filter duplicate
1626 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseButton, arg: (int)mouse_button);
1627 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1628 if (latest_button_down == down)
1629 return;
1630
1631 ImGuiInputEvent e;
1632 e.Type = ImGuiInputEventType_MouseButton;
1633 e.Source = ImGuiInputSource_Mouse;
1634 e.EventId = g.InputEventsNextEventId++;
1635 e.MouseButton.Button = mouse_button;
1636 e.MouseButton.Down = down;
1637 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1638 g.InputEventsQueue.push_back(v: e);
1639}
1640
1641// Queue a mouse wheel event (some mouse/API may only have a Y component)
1642void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1643{
1644 IM_ASSERT(Ctx != NULL);
1645 ImGuiContext& g = *Ctx;
1646
1647 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1648 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1649 return;
1650
1651 ImGuiInputEvent e;
1652 e.Type = ImGuiInputEventType_MouseWheel;
1653 e.Source = ImGuiInputSource_Mouse;
1654 e.EventId = g.InputEventsNextEventId++;
1655 e.MouseWheel.WheelX = wheel_x;
1656 e.MouseWheel.WheelY = wheel_y;
1657 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1658 g.InputEventsQueue.push_back(v: e);
1659}
1660
1661// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1662// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1663void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1664{
1665 IM_ASSERT(Ctx != NULL);
1666 ImGuiContext& g = *Ctx;
1667 g.InputEventsNextMouseSource = source;
1668}
1669
1670void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1671{
1672 IM_ASSERT(Ctx != NULL);
1673 ImGuiContext& g = *Ctx;
1674 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1675 if (!AppAcceptingEvents)
1676 return;
1677
1678 // Filter duplicate
1679 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseViewport);
1680 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1681 if (latest_viewport_id == viewport_id)
1682 return;
1683
1684 ImGuiInputEvent e;
1685 e.Type = ImGuiInputEventType_MouseViewport;
1686 e.Source = ImGuiInputSource_Mouse;
1687 e.MouseViewport.HoveredViewportID = viewport_id;
1688 g.InputEventsQueue.push_back(v: e);
1689}
1690
1691void ImGuiIO::AddFocusEvent(bool focused)
1692{
1693 IM_ASSERT(Ctx != NULL);
1694 ImGuiContext& g = *Ctx;
1695
1696 // Filter duplicate
1697 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Focus);
1698 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1699 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1700 return;
1701
1702 ImGuiInputEvent e;
1703 e.Type = ImGuiInputEventType_Focus;
1704 e.EventId = g.InputEventsNextEventId++;
1705 e.AppFocused.Focused = focused;
1706 g.InputEventsQueue.push_back(v: e);
1707}
1708
1709//-----------------------------------------------------------------------------
1710// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1711//-----------------------------------------------------------------------------
1712
1713ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1714{
1715 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1716 ImVec2 p_last = p1;
1717 ImVec2 p_closest;
1718 float p_closest_dist2 = FLT_MAX;
1719 float t_step = 1.0f / (float)num_segments;
1720 for (int i_step = 1; i_step <= num_segments; i_step++)
1721 {
1722 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t: t_step * i_step);
1723 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
1724 float dist2 = ImLengthSqr(lhs: p - p_line);
1725 if (dist2 < p_closest_dist2)
1726 {
1727 p_closest = p_line;
1728 p_closest_dist2 = dist2;
1729 }
1730 p_last = p_current;
1731 }
1732 return p_closest;
1733}
1734
1735// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1736static 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)
1737{
1738 float dx = x4 - x1;
1739 float dy = y4 - y1;
1740 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1741 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1742 d2 = (d2 >= 0) ? d2 : -d2;
1743 d3 = (d3 >= 0) ? d3 : -d3;
1744 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1745 {
1746 ImVec2 p_current(x4, y4);
1747 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
1748 float dist2 = ImLengthSqr(lhs: p - p_line);
1749 if (dist2 < p_closest_dist2)
1750 {
1751 p_closest = p_line;
1752 p_closest_dist2 = dist2;
1753 }
1754 p_last = p_current;
1755 }
1756 else if (level < 10)
1757 {
1758 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
1759 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
1760 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
1761 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
1762 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
1763 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1764 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x2: x12, y2: y12, x3: x123, y3: y123, x4: x1234, y4: y1234, tess_tol, level: level + 1);
1765 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: x1234, y1: y1234, x2: x234, y2: y234, x3: x34, y3: y34, x4, y4, tess_tol, level: level + 1);
1766 }
1767}
1768
1769// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1770// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1771ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1772{
1773 IM_ASSERT(tess_tol > 0.0f);
1774 ImVec2 p_last = p1;
1775 ImVec2 p_closest;
1776 float p_closest_dist2 = FLT_MAX;
1777 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y, x3: p3.x, y3: p3.y, x4: p4.x, y4: p4.y, tess_tol, level: 0);
1778 return p_closest;
1779}
1780
1781ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1782{
1783 ImVec2 ap = p - a;
1784 ImVec2 ab_dir = b - a;
1785 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1786 if (dot < 0.0f)
1787 return a;
1788 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1789 if (dot > ab_len_sqr)
1790 return b;
1791 return a + ab_dir * dot / ab_len_sqr;
1792}
1793
1794bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1795{
1796 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1797 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1798 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1799 return ((b1 == b2) && (b2 == b3));
1800}
1801
1802void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1803{
1804 ImVec2 v0 = b - a;
1805 ImVec2 v1 = c - a;
1806 ImVec2 v2 = p - a;
1807 const float denom = v0.x * v1.y - v1.x * v0.y;
1808 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1809 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1810 out_u = 1.0f - out_v - out_w;
1811}
1812
1813ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1814{
1815 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1816 ImVec2 proj_bc = ImLineClosestPoint(a: b, b: c, p);
1817 ImVec2 proj_ca = ImLineClosestPoint(a: c, b: a, p);
1818 float dist2_ab = ImLengthSqr(lhs: p - proj_ab);
1819 float dist2_bc = ImLengthSqr(lhs: p - proj_bc);
1820 float dist2_ca = ImLengthSqr(lhs: p - proj_ca);
1821 float m = ImMin(lhs: dist2_ab, rhs: ImMin(lhs: dist2_bc, rhs: dist2_ca));
1822 if (m == dist2_ab)
1823 return proj_ab;
1824 if (m == dist2_bc)
1825 return proj_bc;
1826 return proj_ca;
1827}
1828
1829//-----------------------------------------------------------------------------
1830// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1831//-----------------------------------------------------------------------------
1832
1833// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1834int ImStricmp(const char* str1, const char* str2)
1835{
1836 int d;
1837 while ((d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; }
1838 return d;
1839}
1840
1841int ImStrnicmp(const char* str1, const char* str2, size_t count)
1842{
1843 int d = 0;
1844 while (count > 0 && (d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; count--; }
1845 return d;
1846}
1847
1848void ImStrncpy(char* dst, const char* src, size_t count)
1849{
1850 if (count < 1)
1851 return;
1852 if (count > 1)
1853 strncpy(dest: dst, src: src, n: count - 1);
1854 dst[count - 1] = 0;
1855}
1856
1857char* ImStrdup(const char* str)
1858{
1859 size_t len = strlen(s: str);
1860 void* buf = IM_ALLOC(len + 1);
1861 return (char*)memcpy(dest: buf, src: (const void*)str, n: len + 1);
1862}
1863
1864char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1865{
1866 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(s: dst) + 1;
1867 size_t src_size = strlen(s: src) + 1;
1868 if (dst_buf_size < src_size)
1869 {
1870 IM_FREE(dst);
1871 dst = (char*)IM_ALLOC(src_size);
1872 if (p_dst_size)
1873 *p_dst_size = src_size;
1874 }
1875 return (char*)memcpy(dest: dst, src: (const void*)src, n: src_size);
1876}
1877
1878const char* ImStrchrRange(const char* str, const char* str_end, char c)
1879{
1880 const char* p = (const char*)memchr(s: str, c: (int)c, n: str_end - str);
1881 return p;
1882}
1883
1884int ImStrlenW(const ImWchar* str)
1885{
1886 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
1887 int n = 0;
1888 while (*str++) n++;
1889 return n;
1890}
1891
1892// Find end-of-line. Return pointer will point to either first \n, either str_end.
1893const char* ImStreolRange(const char* str, const char* str_end)
1894{
1895 const char* p = (const char*)memchr(s: str, c: '\n', n: str_end - str);
1896 return p ? p : str_end;
1897}
1898
1899const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1900{
1901 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1902 buf_mid_line--;
1903 return buf_mid_line;
1904}
1905
1906const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1907{
1908 if (!needle_end)
1909 needle_end = needle + strlen(s: needle);
1910
1911 const char un0 = (char)ImToUpper(c: *needle);
1912 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1913 {
1914 if (ImToUpper(c: *haystack) == un0)
1915 {
1916 const char* b = needle + 1;
1917 for (const char* a = haystack + 1; b < needle_end; a++, b++)
1918 if (ImToUpper(c: *a) != ImToUpper(c: *b))
1919 break;
1920 if (b == needle_end)
1921 return haystack;
1922 }
1923 haystack++;
1924 }
1925 return NULL;
1926}
1927
1928// 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.
1929void ImStrTrimBlanks(char* buf)
1930{
1931 char* p = buf;
1932 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
1933 p++;
1934 char* p_start = p;
1935 while (*p != 0) // Find end of string
1936 p++;
1937 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
1938 p--;
1939 if (p_start != buf) // Copy memory if we had leading blanks
1940 memmove(dest: buf, src: p_start, n: p - p_start);
1941 buf[p - p_start] = 0; // Zero terminate
1942}
1943
1944const char* ImStrSkipBlank(const char* str)
1945{
1946 while (str[0] == ' ' || str[0] == '\t')
1947 str++;
1948 return str;
1949}
1950
1951// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1952// 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.
1953// B) When buf==NULL vsnprintf() will return the output size.
1954#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1955
1956// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1957// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1958// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1959// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1960#ifdef IMGUI_USE_STB_SPRINTF
1961#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1962#define STB_SPRINTF_IMPLEMENTATION
1963#endif
1964#ifdef IMGUI_STB_SPRINTF_FILENAME
1965#include IMGUI_STB_SPRINTF_FILENAME
1966#else
1967#include "stb_sprintf.h"
1968#endif
1969#endif // #ifdef IMGUI_USE_STB_SPRINTF
1970
1971#if defined(_MSC_VER) && !defined(vsnprintf)
1972#define vsnprintf _vsnprintf
1973#endif
1974
1975int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1976{
1977 va_list args;
1978 va_start(args, fmt);
1979#ifdef IMGUI_USE_STB_SPRINTF
1980 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1981#else
1982 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
1983#endif
1984 va_end(args);
1985 if (buf == NULL)
1986 return w;
1987 if (w == -1 || w >= (int)buf_size)
1988 w = (int)buf_size - 1;
1989 buf[w] = 0;
1990 return w;
1991}
1992
1993int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1994{
1995#ifdef IMGUI_USE_STB_SPRINTF
1996 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1997#else
1998 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
1999#endif
2000 if (buf == NULL)
2001 return w;
2002 if (w == -1 || w >= (int)buf_size)
2003 w = (int)buf_size - 1;
2004 buf[w] = 0;
2005 return w;
2006}
2007#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2008
2009void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2010{
2011 va_list args;
2012 va_start(args, fmt);
2013 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2014 va_end(args);
2015}
2016
2017void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2018{
2019 ImGuiContext& g = *GImGui;
2020 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2021 {
2022 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2023 if (buf == NULL)
2024 buf = "(null)";
2025 *out_buf = buf;
2026 if (out_buf_end) { *out_buf_end = buf + strlen(s: buf); }
2027 }
2028 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2029 {
2030 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2031 const char* buf = va_arg(args, const char*);
2032 if (buf == NULL)
2033 {
2034 buf = "(null)";
2035 buf_len = ImMin(lhs: buf_len, rhs: 6);
2036 }
2037 *out_buf = buf;
2038 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2039 }
2040 else
2041 {
2042 int buf_len = ImFormatStringV(buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size, fmt, args);
2043 *out_buf = g.TempBuffer.Data;
2044 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2045 }
2046}
2047
2048// CRC32 needs a 1KB lookup table (not cache friendly)
2049// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2050// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2051static const ImU32 GCrc32LookupTable[256] =
2052{
2053 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2054 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2055 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2056 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2057 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2058 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2059 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2060 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2061 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2062 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2063 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2064 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2065 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2066 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2067 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2068 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2069};
2070
2071// Known size hash
2072// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2073// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2074ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2075{
2076 ImU32 crc = ~seed;
2077 const unsigned char* data = (const unsigned char*)data_p;
2078 const ImU32* crc32_lut = GCrc32LookupTable;
2079 while (data_size-- != 0)
2080 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2081 return ~crc;
2082}
2083
2084// Zero-terminated string hash, with support for ### to reset back to seed value
2085// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2086// Because this syntax is rarely used we are optimizing for the common case.
2087// - If we reach ### in the string we discard the hash so far and reset to the seed.
2088// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2089// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2090ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2091{
2092 seed = ~seed;
2093 ImU32 crc = seed;
2094 const unsigned char* data = (const unsigned char*)data_p;
2095 const ImU32* crc32_lut = GCrc32LookupTable;
2096 if (data_size != 0)
2097 {
2098 while (data_size-- != 0)
2099 {
2100 unsigned char c = *data++;
2101 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2102 crc = seed;
2103 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2104 }
2105 }
2106 else
2107 {
2108 while (unsigned char c = *data++)
2109 {
2110 if (c == '#' && data[0] == '#' && data[1] == '#')
2111 crc = seed;
2112 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2113 }
2114 }
2115 return ~crc;
2116}
2117
2118//-----------------------------------------------------------------------------
2119// [SECTION] MISC HELPERS/UTILITIES (File functions)
2120//-----------------------------------------------------------------------------
2121
2122// Default file functions
2123#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2124
2125ImFileHandle ImFileOpen(const char* filename, const char* mode)
2126{
2127#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2128 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2129 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2130 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2131 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2132
2133 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2134 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2135 wchar_t local_temp_stack[FILENAME_MAX];
2136 ImVector<wchar_t> local_temp_heap;
2137 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2138 local_temp_heap.resize(filename_wsize + mode_wsize);
2139 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2140 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2141 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2142 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2143 return ::_wfopen(filename_wbuf, mode_wbuf);
2144#else
2145 return fopen(filename: filename, modes: mode);
2146#endif
2147}
2148
2149// 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.
2150bool ImFileClose(ImFileHandle f) { return fclose(stream: f) == 0; }
2151ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(stream: f)) != -1 && !fseek(stream: f, off: 0, SEEK_END) && (sz = ftell(stream: f)) != -1 && !fseek(stream: f, off: off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2152ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(ptr: data, size: (size_t)sz, n: (size_t)count, stream: f); }
2153ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(ptr: data, size: (size_t)sz, n: (size_t)count, s: f); }
2154#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2155
2156// Helper: Load file content into memory
2157// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2158// This can't really be used with "rt" because fseek size won't match read size.
2159void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2160{
2161 IM_ASSERT(filename && mode);
2162 if (out_file_size)
2163 *out_file_size = 0;
2164
2165 ImFileHandle f;
2166 if ((f = ImFileOpen(filename, mode)) == NULL)
2167 return NULL;
2168
2169 size_t file_size = (size_t)ImFileGetSize(f);
2170 if (file_size == (size_t)-1)
2171 {
2172 ImFileClose(f);
2173 return NULL;
2174 }
2175
2176 void* file_data = IM_ALLOC(file_size + padding_bytes);
2177 if (file_data == NULL)
2178 {
2179 ImFileClose(f);
2180 return NULL;
2181 }
2182 if (ImFileRead(data: file_data, sz: 1, count: file_size, f) != file_size)
2183 {
2184 ImFileClose(f);
2185 IM_FREE(file_data);
2186 return NULL;
2187 }
2188 if (padding_bytes > 0)
2189 memset(s: (void*)(((char*)file_data) + file_size), c: 0, n: (size_t)padding_bytes);
2190
2191 ImFileClose(f);
2192 if (out_file_size)
2193 *out_file_size = file_size;
2194
2195 return file_data;
2196}
2197
2198//-----------------------------------------------------------------------------
2199// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2200//-----------------------------------------------------------------------------
2201
2202IM_MSVC_RUNTIME_CHECKS_OFF
2203
2204// Convert UTF-8 to 32-bit character, process single character input.
2205// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2206// We handle UTF-8 decoding error by skipping forward.
2207int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2208{
2209 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 };
2210 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2211 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2212 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2213 static const int shifte[] = { 0, 6, 4, 2, 0 };
2214 int len = lengths[*(const unsigned char*)in_text >> 3];
2215 int wanted = len + (len ? 0 : 1);
2216
2217 if (in_text_end == NULL)
2218 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2219
2220 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2221 // so it is fast even with excessive branching.
2222 unsigned char s[4];
2223 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2224 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2225 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2226 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2227
2228 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2229 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2230 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2231 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2232 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2233 *out_char >>= shiftc[len];
2234
2235 // Accumulate the various error conditions.
2236 int e = 0;
2237 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2238 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2239 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
2240 e |= (s[1] & 0xc0) >> 2;
2241 e |= (s[2] & 0xc0) >> 4;
2242 e |= (s[3] ) >> 6;
2243 e ^= 0x2a; // top two bits of each tail byte correct?
2244 e >>= shifte[len];
2245
2246 if (e)
2247 {
2248 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2249 // One byte is consumed in case of invalid first byte of in_text.
2250 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2251 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2252 wanted = ImMin(lhs: wanted, rhs: !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2253 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2254 }
2255
2256 return wanted;
2257}
2258
2259int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2260{
2261 ImWchar* buf_out = buf;
2262 ImWchar* buf_end = buf + buf_size;
2263 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2264 {
2265 unsigned int c;
2266 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2267 *buf_out++ = (ImWchar)c;
2268 }
2269 *buf_out = 0;
2270 if (in_text_remaining)
2271 *in_text_remaining = in_text;
2272 return (int)(buf_out - buf);
2273}
2274
2275int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2276{
2277 int char_count = 0;
2278 while ((!in_text_end || in_text < in_text_end) && *in_text)
2279 {
2280 unsigned int c;
2281 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2282 char_count++;
2283 }
2284 return char_count;
2285}
2286
2287// Based on stb_to_utf8() from github.com/nothings/stb/
2288static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2289{
2290 if (c < 0x80)
2291 {
2292 buf[0] = (char)c;
2293 return 1;
2294 }
2295 if (c < 0x800)
2296 {
2297 if (buf_size < 2) return 0;
2298 buf[0] = (char)(0xc0 + (c >> 6));
2299 buf[1] = (char)(0x80 + (c & 0x3f));
2300 return 2;
2301 }
2302 if (c < 0x10000)
2303 {
2304 if (buf_size < 3) return 0;
2305 buf[0] = (char)(0xe0 + (c >> 12));
2306 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2307 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2308 return 3;
2309 }
2310 if (c <= 0x10FFFF)
2311 {
2312 if (buf_size < 4) return 0;
2313 buf[0] = (char)(0xf0 + (c >> 18));
2314 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2315 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2316 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2317 return 4;
2318 }
2319 // Invalid code point, the max unicode is 0x10FFFF
2320 return 0;
2321}
2322
2323const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2324{
2325 int count = ImTextCharToUtf8_inline(buf: out_buf, buf_size: 5, c);
2326 out_buf[count] = 0;
2327 return out_buf;
2328}
2329
2330// Not optimal but we very rarely use this function.
2331int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2332{
2333 unsigned int unused = 0;
2334 return ImTextCharFromUtf8(out_char: &unused, in_text, in_text_end);
2335}
2336
2337static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2338{
2339 if (c < 0x80) return 1;
2340 if (c < 0x800) return 2;
2341 if (c < 0x10000) return 3;
2342 if (c <= 0x10FFFF) return 4;
2343 return 3;
2344}
2345
2346int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2347{
2348 char* buf_p = out_buf;
2349 const char* buf_end = out_buf + out_buf_size;
2350 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2351 {
2352 unsigned int c = (unsigned int)(*in_text++);
2353 if (c < 0x80)
2354 *buf_p++ = (char)c;
2355 else
2356 buf_p += ImTextCharToUtf8_inline(buf: buf_p, buf_size: (int)(buf_end - buf_p - 1), c);
2357 }
2358 *buf_p = 0;
2359 return (int)(buf_p - out_buf);
2360}
2361
2362int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2363{
2364 int bytes_count = 0;
2365 while ((!in_text_end || in_text < in_text_end) && *in_text)
2366 {
2367 unsigned int c = (unsigned int)(*in_text++);
2368 if (c < 0x80)
2369 bytes_count++;
2370 else
2371 bytes_count += ImTextCountUtf8BytesFromChar(c);
2372 }
2373 return bytes_count;
2374}
2375
2376const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2377{
2378 while (in_text_curr > in_text_start)
2379 {
2380 in_text_curr--;
2381 if ((*in_text_curr & 0xC0) != 0x80)
2382 return in_text_curr;
2383 }
2384 return in_text_start;
2385}
2386
2387IM_MSVC_RUNTIME_CHECKS_RESTORE
2388
2389//-----------------------------------------------------------------------------
2390// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2391// Note: The Convert functions are early design which are not consistent with other API.
2392//-----------------------------------------------------------------------------
2393
2394IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2395{
2396 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2397 int r = ImLerp(a: (int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2398 int g = ImLerp(a: (int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2399 int b = ImLerp(a: (int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2400 return IM_COL32(r, g, b, 0xFF);
2401}
2402
2403ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2404{
2405 float s = 1.0f / 255.0f;
2406 return ImVec4(
2407 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2408 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2409 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2410 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2411}
2412
2413ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2414{
2415 ImU32 out;
2416 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2417 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2418 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2419 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2420 return out;
2421}
2422
2423// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2424// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2425void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2426{
2427 float K = 0.f;
2428 if (g < b)
2429 {
2430 ImSwap(a&: g, b);
2431 K = -1.f;
2432 }
2433 if (r < g)
2434 {
2435 ImSwap(a&: r, b&: g);
2436 K = -2.f / 6.f - K;
2437 }
2438
2439 const float chroma = r - (g < b ? g : b);
2440 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2441 out_s = chroma / (r + 1e-20f);
2442 out_v = r;
2443}
2444
2445// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2446// also http://en.wikipedia.org/wiki/HSL_and_HSV
2447void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2448{
2449 if (s == 0.0f)
2450 {
2451 // gray
2452 out_r = out_g = out_b = v;
2453 return;
2454 }
2455
2456 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2457 int i = (int)h;
2458 float f = h - (float)i;
2459 float p = v * (1.0f - s);
2460 float q = v * (1.0f - s * f);
2461 float t = v * (1.0f - s * (1.0f - f));
2462
2463 switch (i)
2464 {
2465 case 0: out_r = v; out_g = t; out_b = p; break;
2466 case 1: out_r = q; out_g = v; out_b = p; break;
2467 case 2: out_r = p; out_g = v; out_b = t; break;
2468 case 3: out_r = p; out_g = q; out_b = v; break;
2469 case 4: out_r = t; out_g = p; out_b = v; break;
2470 case 5: default: out_r = v; out_g = p; out_b = q; break;
2471 }
2472}
2473
2474//-----------------------------------------------------------------------------
2475// [SECTION] ImGuiStorage
2476// Helper: Key->value storage
2477//-----------------------------------------------------------------------------
2478
2479// std::lower_bound but without the bullshit
2480static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2481{
2482 ImGuiStorage::ImGuiStoragePair* first = data.Data;
2483 ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2484 size_t count = (size_t)(last - first);
2485 while (count > 0)
2486 {
2487 size_t count2 = count >> 1;
2488 ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2489 if (mid->key < key)
2490 {
2491 first = ++mid;
2492 count -= count2 + 1;
2493 }
2494 else
2495 {
2496 count = count2;
2497 }
2498 }
2499 return first;
2500}
2501
2502// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2503void ImGuiStorage::BuildSortByKey()
2504{
2505 struct StaticFunc
2506 {
2507 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2508 {
2509 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2510 if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2511 if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2512 return 0;
2513 }
2514 };
2515 ImQsort(base: Data.Data, count: (size_t)Data.Size, size_of_element: sizeof(ImGuiStoragePair), compare_func: StaticFunc::PairComparerByID);
2516}
2517
2518int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2519{
2520 ImGuiStoragePair* it = LowerBound(data&: const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2521 if (it == Data.end() || it->key != key)
2522 return default_val;
2523 return it->val_i;
2524}
2525
2526bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2527{
2528 return GetInt(key, default_val: default_val ? 1 : 0) != 0;
2529}
2530
2531float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2532{
2533 ImGuiStoragePair* it = LowerBound(data&: const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2534 if (it == Data.end() || it->key != key)
2535 return default_val;
2536 return it->val_f;
2537}
2538
2539void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2540{
2541 ImGuiStoragePair* it = LowerBound(data&: const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2542 if (it == Data.end() || it->key != key)
2543 return NULL;
2544 return it->val_p;
2545}
2546
2547// 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.
2548int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2549{
2550 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2551 if (it == Data.end() || it->key != key)
2552 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2553 return &it->val_i;
2554}
2555
2556bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2557{
2558 return (bool*)GetIntRef(key, default_val: default_val ? 1 : 0);
2559}
2560
2561float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2562{
2563 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2564 if (it == Data.end() || it->key != key)
2565 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2566 return &it->val_f;
2567}
2568
2569void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2570{
2571 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2572 if (it == Data.end() || it->key != key)
2573 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2574 return &it->val_p;
2575}
2576
2577// 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)
2578void ImGuiStorage::SetInt(ImGuiID key, int val)
2579{
2580 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2581 if (it == Data.end() || it->key != key)
2582 Data.insert(it, v: ImGuiStoragePair(key, val));
2583 else
2584 it->val_i = val;
2585}
2586
2587void ImGuiStorage::SetBool(ImGuiID key, bool val)
2588{
2589 SetInt(key, val: val ? 1 : 0);
2590}
2591
2592void ImGuiStorage::SetFloat(ImGuiID key, float val)
2593{
2594 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2595 if (it == Data.end() || it->key != key)
2596 Data.insert(it, v: ImGuiStoragePair(key, val));
2597 else
2598 it->val_f = val;
2599}
2600
2601void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2602{
2603 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2604 if (it == Data.end() || it->key != key)
2605 Data.insert(it, v: ImGuiStoragePair(key, val));
2606 else
2607 it->val_p = val;
2608}
2609
2610void ImGuiStorage::SetAllInt(int v)
2611{
2612 for (int i = 0; i < Data.Size; i++)
2613 Data[i].val_i = v;
2614}
2615
2616//-----------------------------------------------------------------------------
2617// [SECTION] ImGuiTextFilter
2618//-----------------------------------------------------------------------------
2619
2620// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2621ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2622{
2623 InputBuf[0] = 0;
2624 CountGrep = 0;
2625 if (default_filter)
2626 {
2627 ImStrncpy(dst: InputBuf, src: default_filter, IM_ARRAYSIZE(InputBuf));
2628 Build();
2629 }
2630}
2631
2632bool ImGuiTextFilter::Draw(const char* label, float width)
2633{
2634 if (width != 0.0f)
2635 ImGui::SetNextItemWidth(width);
2636 bool value_changed = ImGui::InputText(label, buf: InputBuf, IM_ARRAYSIZE(InputBuf));
2637 if (value_changed)
2638 Build();
2639 return value_changed;
2640}
2641
2642void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2643{
2644 out->resize(new_size: 0);
2645 const char* wb = b;
2646 const char* we = wb;
2647 while (we < e)
2648 {
2649 if (*we == separator)
2650 {
2651 out->push_back(v: ImGuiTextRange(wb, we));
2652 wb = we + 1;
2653 }
2654 we++;
2655 }
2656 if (wb != we)
2657 out->push_back(v: ImGuiTextRange(wb, we));
2658}
2659
2660void ImGuiTextFilter::Build()
2661{
2662 Filters.resize(new_size: 0);
2663 ImGuiTextRange input_range(InputBuf, InputBuf + strlen(s: InputBuf));
2664 input_range.split(separator: ',', out: &Filters);
2665
2666 CountGrep = 0;
2667 for (ImGuiTextRange& f : Filters)
2668 {
2669 while (f.b < f.e && ImCharIsBlankA(c: f.b[0]))
2670 f.b++;
2671 while (f.e > f.b && ImCharIsBlankA(c: f.e[-1]))
2672 f.e--;
2673 if (f.empty())
2674 continue;
2675 if (f.b[0] != '-')
2676 CountGrep += 1;
2677 }
2678}
2679
2680bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2681{
2682 if (Filters.empty())
2683 return true;
2684
2685 if (text == NULL)
2686 text = "";
2687
2688 for (const ImGuiTextRange& f : Filters)
2689 {
2690 if (f.empty())
2691 continue;
2692 if (f.b[0] == '-')
2693 {
2694 // Subtract
2695 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b + 1, needle_end: f.e) != NULL)
2696 return false;
2697 }
2698 else
2699 {
2700 // Grep
2701 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b, needle_end: f.e) != NULL)
2702 return true;
2703 }
2704 }
2705
2706 // Implicit * grep
2707 if (CountGrep == 0)
2708 return true;
2709
2710 return false;
2711}
2712
2713//-----------------------------------------------------------------------------
2714// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2715//-----------------------------------------------------------------------------
2716
2717// On some platform vsnprintf() takes va_list by reference and modifies it.
2718// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2719#ifndef va_copy
2720#if defined(__GNUC__) || defined(__clang__)
2721#define va_copy(dest, src) __builtin_va_copy(dest, src)
2722#else
2723#define va_copy(dest, src) (dest = src)
2724#endif
2725#endif
2726
2727char ImGuiTextBuffer::EmptyString[1] = { 0 };
2728
2729void ImGuiTextBuffer::append(const char* str, const char* str_end)
2730{
2731 int len = str_end ? (int)(str_end - str) : (int)strlen(s: str);
2732
2733 // Add zero-terminator the first time
2734 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2735 const int needed_sz = write_off + len;
2736 if (write_off + len >= Buf.Capacity)
2737 {
2738 int new_capacity = Buf.Capacity * 2;
2739 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
2740 }
2741
2742 Buf.resize(new_size: needed_sz);
2743 memcpy(dest: &Buf[write_off - 1], src: str, n: (size_t)len);
2744 Buf[write_off - 1 + len] = 0;
2745}
2746
2747void ImGuiTextBuffer::appendf(const char* fmt, ...)
2748{
2749 va_list args;
2750 va_start(args, fmt);
2751 appendfv(fmt, args);
2752 va_end(args);
2753}
2754
2755// Helper: Text buffer for logging/accumulating text
2756void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2757{
2758 va_list args_copy;
2759 va_copy(args_copy, args);
2760
2761 int len = ImFormatStringV(NULL, buf_size: 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2762 if (len <= 0)
2763 {
2764 va_end(args_copy);
2765 return;
2766 }
2767
2768 // Add zero-terminator the first time
2769 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2770 const int needed_sz = write_off + len;
2771 if (write_off + len >= Buf.Capacity)
2772 {
2773 int new_capacity = Buf.Capacity * 2;
2774 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
2775 }
2776
2777 Buf.resize(new_size: needed_sz);
2778 ImFormatStringV(buf: &Buf[write_off - 1], buf_size: (size_t)len + 1, fmt, args: args_copy);
2779 va_end(args_copy);
2780}
2781
2782void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2783{
2784 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2785 if (old_size == new_size)
2786 return;
2787 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2788 LineOffsets.push_back(v: EndOffset);
2789 const char* base_end = base + new_size;
2790 for (const char* p = base + old_size; (p = (const char*)memchr(s: p, c: '\n', n: base_end - p)) != 0; )
2791 if (++p < base_end) // Don't push a trailing offset on last \n
2792 LineOffsets.push_back(v: (int)(intptr_t)(p - base));
2793 EndOffset = ImMax(lhs: EndOffset, rhs: new_size);
2794}
2795
2796//-----------------------------------------------------------------------------
2797// [SECTION] ImGuiListClipper
2798//-----------------------------------------------------------------------------
2799
2800// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2801// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2802static bool GetSkipItemForListClipping()
2803{
2804 ImGuiContext& g = *GImGui;
2805 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2806}
2807
2808static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2809{
2810 if (ranges.Size - offset <= 1)
2811 return;
2812
2813 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2814 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2815 for (int i = offset; i < sort_end + offset; ++i)
2816 if (ranges[i].Min > ranges[i + 1].Min)
2817 ImSwap(a&: ranges[i], b&: ranges[i + 1]);
2818
2819 // Now fuse ranges together as much as possible.
2820 for (int i = 1 + offset; i < ranges.Size; i++)
2821 {
2822 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2823 if (ranges[i - 1].Max < ranges[i].Min)
2824 continue;
2825 ranges[i - 1].Min = ImMin(lhs: ranges[i - 1].Min, rhs: ranges[i].Min);
2826 ranges[i - 1].Max = ImMax(lhs: ranges[i - 1].Max, rhs: ranges[i].Max);
2827 ranges.erase(it: ranges.Data + i);
2828 i--;
2829 }
2830}
2831
2832static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2833{
2834 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2835 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2836 // 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?
2837 ImGuiContext& g = *GImGui;
2838 ImGuiWindow* window = g.CurrentWindow;
2839 float off_y = pos_y - window->DC.CursorPos.y;
2840 window->DC.CursorPos.y = pos_y;
2841 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: pos_y - g.Style.ItemSpacing.y);
2842 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.
2843 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.
2844 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2845 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
2846 if (ImGuiTable* table = g.CurrentTable)
2847 {
2848 if (table->IsInsideRow)
2849 ImGui::TableEndRow(table);
2850 table->RowPosY2 = window->DC.CursorPos.y;
2851 const int row_increase = (int)((off_y / line_height) + 0.5f);
2852 //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2853 table->RowBgColorCounter += row_increase;
2854 }
2855}
2856
2857static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2858{
2859 // StartPosY starts from ItemsFrozen hence the subtraction
2860 // Perform the add and multiply with double to allow seeking through larger ranges
2861 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2862 float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2863 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, line_height: clipper->ItemsHeight);
2864}
2865
2866ImGuiListClipper::ImGuiListClipper()
2867{
2868 memset(s: this, c: 0, n: sizeof(*this));
2869}
2870
2871ImGuiListClipper::~ImGuiListClipper()
2872{
2873 End();
2874}
2875
2876void ImGuiListClipper::Begin(int items_count, float items_height)
2877{
2878 if (Ctx == NULL)
2879 Ctx = ImGui::GetCurrentContext();
2880
2881 ImGuiContext& g = *Ctx;
2882 ImGuiWindow* window = g.CurrentWindow;
2883 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2884
2885 if (ImGuiTable* table = g.CurrentTable)
2886 if (table->IsInsideRow)
2887 ImGui::TableEndRow(table);
2888
2889 StartPosY = window->DC.CursorPos.y;
2890 ItemsHeight = items_height;
2891 ItemsCount = items_count;
2892 DisplayStart = -1;
2893 DisplayEnd = 0;
2894
2895 // Acquire temporary buffer
2896 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2897 g.ClipperTempData.resize(new_size: g.ClipperTempDataStacked, v: ImGuiListClipperData());
2898 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2899 data->Reset(clipper: this);
2900 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2901 TempData = data;
2902}
2903
2904void ImGuiListClipper::End()
2905{
2906 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2907 {
2908 // 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.
2909 ImGuiContext& g = *Ctx;
2910 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2911 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2912 ImGuiListClipper_SeekCursorForItem(clipper: this, item_n: ItemsCount);
2913
2914 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2915 IM_ASSERT(data->ListClipper == this);
2916 data->StepNo = data->Ranges.Size;
2917 if (--g.ClipperTempDataStacked > 0)
2918 {
2919 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2920 data->ListClipper->TempData = data;
2921 }
2922 TempData = NULL;
2923 }
2924 ItemsCount = -1;
2925}
2926
2927void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2928{
2929 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2930 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2931 IM_ASSERT(item_begin <= item_end);
2932 if (item_begin < item_end)
2933 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: item_begin, max: item_end));
2934}
2935
2936static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2937{
2938 ImGuiContext& g = *clipper->Ctx;
2939 ImGuiWindow* window = g.CurrentWindow;
2940 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2941 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2942
2943 ImGuiTable* table = g.CurrentTable;
2944 if (table && table->IsInsideRow)
2945 ImGui::TableEndRow(table);
2946
2947 // No items
2948 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2949 return false;
2950
2951 // While we are in frozen row state, keep displaying items one by one, unclipped
2952 // FIXME: Could be stored as a table-agnostic state.
2953 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2954 {
2955 clipper->DisplayStart = data->ItemsFrozen;
2956 clipper->DisplayEnd = ImMin(lhs: data->ItemsFrozen + 1, rhs: clipper->ItemsCount);
2957 if (clipper->DisplayStart < clipper->DisplayEnd)
2958 data->ItemsFrozen++;
2959 return true;
2960 }
2961
2962 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2963 bool calc_clipping = false;
2964 if (data->StepNo == 0)
2965 {
2966 clipper->StartPosY = window->DC.CursorPos.y;
2967 if (clipper->ItemsHeight <= 0.0f)
2968 {
2969 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2970 data->Ranges.push_front(v: ImGuiListClipperRange::FromIndices(min: data->ItemsFrozen, max: data->ItemsFrozen + 1));
2971 clipper->DisplayStart = ImMax(lhs: data->Ranges[0].Min, rhs: data->ItemsFrozen);
2972 clipper->DisplayEnd = ImMin(lhs: data->Ranges[0].Max, rhs: clipper->ItemsCount);
2973 data->StepNo = 1;
2974 return true;
2975 }
2976 calc_clipping = true; // If on the first step with known item height, calculate clipping.
2977 }
2978
2979 // Step 1: Let the clipper infer height from first range
2980 if (clipper->ItemsHeight <= 0.0f)
2981 {
2982 IM_ASSERT(data->StepNo == 1);
2983 if (table)
2984 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2985
2986 clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2987 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(f: clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(f: window->DC.CursorPos.y);
2988 if (affected_by_floating_point_precision)
2989 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2990
2991 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2992 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
2993 }
2994
2995 // Step 0 or 1: Calculate the actual ranges of visible elements.
2996 const int already_submitted = clipper->DisplayEnd;
2997 if (calc_clipping)
2998 {
2999 if (g.LogEnabled)
3000 {
3001 // If logging is active, do not perform any clipping
3002 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: 0, max: clipper->ItemsCount));
3003 }
3004 else
3005 {
3006 // Add range selected to be included for navigation
3007 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3008 if (is_nav_request)
3009 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringNoClipRect.Min.y, y2: g.NavScoringNoClipRect.Max.y, off_min: 0, off_max: 0));
3010 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3011 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: clipper->ItemsCount - 1, max: clipper->ItemsCount));
3012
3013 // Add focused/active item
3014 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, r: window->NavRectRel[0]);
3015 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3016 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: nav_rect_abs.Min.y, y2: nav_rect_abs.Max.y, off_min: 0, off_max: 0));
3017
3018 // Add visible range
3019 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3020 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3021 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: window->ClipRect.Min.y, y2: window->ClipRect.Max.y, off_min, off_max));
3022 }
3023
3024 // Convert position ranges to item index ranges
3025 // - 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.
3026 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3027 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3028 for (ImGuiListClipperRange& range : data->Ranges)
3029 if (range.PosToIndexConvert)
3030 {
3031 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3032 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3033 range.Min = ImClamp(v: already_submitted + m1 + range.PosToIndexOffsetMin, mn: already_submitted, mx: clipper->ItemsCount - 1);
3034 range.Max = ImClamp(v: already_submitted + m2 + range.PosToIndexOffsetMax, mn: range.Min + 1, mx: clipper->ItemsCount);
3035 range.PosToIndexConvert = false;
3036 }
3037 ImGuiListClipper_SortAndFuseRanges(ranges&: data->Ranges, offset: data->StepNo);
3038 }
3039
3040 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3041 while (data->StepNo < data->Ranges.Size)
3042 {
3043 clipper->DisplayStart = ImMax(lhs: data->Ranges[data->StepNo].Min, rhs: already_submitted);
3044 clipper->DisplayEnd = ImMin(lhs: data->Ranges[data->StepNo].Max, rhs: clipper->ItemsCount);
3045 if (clipper->DisplayStart > already_submitted) //-V1051
3046 ImGuiListClipper_SeekCursorForItem(clipper, item_n: clipper->DisplayStart);
3047 data->StepNo++;
3048 if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3049 continue;
3050 return true;
3051 }
3052
3053 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3054 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3055 if (clipper->ItemsCount < INT_MAX)
3056 ImGuiListClipper_SeekCursorForItem(clipper, item_n: clipper->ItemsCount);
3057
3058 return false;
3059}
3060
3061bool ImGuiListClipper::Step()
3062{
3063 ImGuiContext& g = *Ctx;
3064 bool need_items_height = (ItemsHeight <= 0.0f);
3065 bool ret = ImGuiListClipper_StepInternal(clipper: this);
3066 if (ret && (DisplayStart == DisplayEnd))
3067 ret = false;
3068 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3069 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3070 if (need_items_height && ItemsHeight > 0.0f)
3071 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3072 if (ret)
3073 {
3074 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3075 }
3076 else
3077 {
3078 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3079 End();
3080 }
3081 return ret;
3082}
3083
3084//-----------------------------------------------------------------------------
3085// [SECTION] STYLING
3086//-----------------------------------------------------------------------------
3087
3088ImGuiStyle& ImGui::GetStyle()
3089{
3090 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3091 return GImGui->Style;
3092}
3093
3094ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3095{
3096 ImGuiStyle& style = GImGui->Style;
3097 ImVec4 c = style.Colors[idx];
3098 c.w *= style.Alpha * alpha_mul;
3099 return ColorConvertFloat4ToU32(in: c);
3100}
3101
3102ImU32 ImGui::GetColorU32(const ImVec4& col)
3103{
3104 ImGuiStyle& style = GImGui->Style;
3105 ImVec4 c = col;
3106 c.w *= style.Alpha;
3107 return ColorConvertFloat4ToU32(in: c);
3108}
3109
3110const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3111{
3112 ImGuiStyle& style = GImGui->Style;
3113 return style.Colors[idx];
3114}
3115
3116ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3117{
3118 ImGuiStyle& style = GImGui->Style;
3119 alpha_mul *= style.Alpha;
3120 if (alpha_mul >= 1.0f)
3121 return col;
3122 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3123 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3124 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3125}
3126
3127// 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
3128void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3129{
3130 ImGuiContext& g = *GImGui;
3131 ImGuiColorMod backup;
3132 backup.Col = idx;
3133 backup.BackupValue = g.Style.Colors[idx];
3134 g.ColorStack.push_back(v: backup);
3135 if (g.DebugFlashStyleColorIdx != idx)
3136 g.Style.Colors[idx] = ColorConvertU32ToFloat4(in: col);
3137}
3138
3139void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3140{
3141 ImGuiContext& g = *GImGui;
3142 ImGuiColorMod backup;
3143 backup.Col = idx;
3144 backup.BackupValue = g.Style.Colors[idx];
3145 g.ColorStack.push_back(v: backup);
3146 if (g.DebugFlashStyleColorIdx != idx)
3147 g.Style.Colors[idx] = col;
3148}
3149
3150void ImGui::PopStyleColor(int count)
3151{
3152 ImGuiContext& g = *GImGui;
3153 if (g.ColorStack.Size < count)
3154 {
3155 IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3156 count = g.ColorStack.Size;
3157 }
3158 while (count > 0)
3159 {
3160 ImGuiColorMod& backup = g.ColorStack.back();
3161 g.Style.Colors[backup.Col] = backup.BackupValue;
3162 g.ColorStack.pop_back();
3163 count--;
3164 }
3165}
3166
3167static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3168{
3169 ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3170};
3171
3172static const ImGuiDataVarInfo GStyleVarInfo[] =
3173{
3174 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3175 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3176 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3177 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3178 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3179 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3180 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3181 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3182 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3183 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3184 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3185 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3186 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3187 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3188 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3189 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3190 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3191 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3192 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3193 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3194 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3195 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3196 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3197 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3198 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3199 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},// ImGuiStyleVar_TableAngledHeadersAngle
3200 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3201 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3202 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3203 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3204 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3205 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3206};
3207
3208const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3209{
3210 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3211 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3212 return &GStyleVarInfo[idx];
3213}
3214
3215void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3216{
3217 ImGuiContext& g = *GImGui;
3218 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3219 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3220 {
3221 float* pvar = (float*)var_info->GetVarPtr(parent: &g.Style);
3222 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3223 *pvar = val;
3224 return;
3225 }
3226 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3227}
3228
3229void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3230{
3231 ImGuiContext& g = *GImGui;
3232 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3233 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3234 {
3235 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3236 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3237 *pvar = val;
3238 return;
3239 }
3240 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3241}
3242
3243void ImGui::PopStyleVar(int count)
3244{
3245 ImGuiContext& g = *GImGui;
3246 if (g.StyleVarStack.Size < count)
3247 {
3248 IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3249 count = g.StyleVarStack.Size;
3250 }
3251 while (count > 0)
3252 {
3253 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3254 ImGuiStyleMod& backup = g.StyleVarStack.back();
3255 const ImGuiDataVarInfo* info = GetStyleVarInfo(idx: backup.VarIdx);
3256 void* data = info->GetVarPtr(parent: &g.Style);
3257 if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3258 else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3259 g.StyleVarStack.pop_back();
3260 count--;
3261 }
3262}
3263
3264const char* ImGui::GetStyleColorName(ImGuiCol idx)
3265{
3266 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3267 switch (idx)
3268 {
3269 case ImGuiCol_Text: return "Text";
3270 case ImGuiCol_TextDisabled: return "TextDisabled";
3271 case ImGuiCol_WindowBg: return "WindowBg";
3272 case ImGuiCol_ChildBg: return "ChildBg";
3273 case ImGuiCol_PopupBg: return "PopupBg";
3274 case ImGuiCol_Border: return "Border";
3275 case ImGuiCol_BorderShadow: return "BorderShadow";
3276 case ImGuiCol_FrameBg: return "FrameBg";
3277 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3278 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3279 case ImGuiCol_TitleBg: return "TitleBg";
3280 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3281 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3282 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3283 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3284 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3285 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3286 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3287 case ImGuiCol_CheckMark: return "CheckMark";
3288 case ImGuiCol_SliderGrab: return "SliderGrab";
3289 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3290 case ImGuiCol_Button: return "Button";
3291 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3292 case ImGuiCol_ButtonActive: return "ButtonActive";
3293 case ImGuiCol_Header: return "Header";
3294 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3295 case ImGuiCol_HeaderActive: return "HeaderActive";
3296 case ImGuiCol_Separator: return "Separator";
3297 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3298 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3299 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3300 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3301 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3302 case ImGuiCol_Tab: return "Tab";
3303 case ImGuiCol_TabHovered: return "TabHovered";
3304 case ImGuiCol_TabActive: return "TabActive";
3305 case ImGuiCol_TabUnfocused: return "TabUnfocused";
3306 case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3307 case ImGuiCol_DockingPreview: return "DockingPreview";
3308 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3309 case ImGuiCol_PlotLines: return "PlotLines";
3310 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3311 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3312 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3313 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3314 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3315 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3316 case ImGuiCol_TableRowBg: return "TableRowBg";
3317 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3318 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3319 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3320 case ImGuiCol_NavHighlight: return "NavHighlight";
3321 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3322 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3323 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3324 }
3325 IM_ASSERT(0);
3326 return "Unknown";
3327}
3328
3329
3330//-----------------------------------------------------------------------------
3331// [SECTION] RENDER HELPERS
3332// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3333// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3334// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3335//-----------------------------------------------------------------------------
3336
3337const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3338{
3339 const char* text_display_end = text;
3340 if (!text_end)
3341 text_end = (const char*)-1;
3342
3343 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3344 text_display_end++;
3345 return text_display_end;
3346}
3347
3348// Internal ImGui functions to render text
3349// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3350void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3351{
3352 ImGuiContext& g = *GImGui;
3353 ImGuiWindow* window = g.CurrentWindow;
3354
3355 // Hide anything after a '##' string
3356 const char* text_display_end;
3357 if (hide_text_after_hash)
3358 {
3359 text_display_end = FindRenderedTextEnd(text, text_end);
3360 }
3361 else
3362 {
3363 if (!text_end)
3364 text_end = text + strlen(s: text); // FIXME-OPT
3365 text_display_end = text_end;
3366 }
3367
3368 if (text != text_display_end)
3369 {
3370 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end);
3371 if (g.LogEnabled)
3372 LogRenderedText(ref_pos: &pos, text, text_end: text_display_end);
3373 }
3374}
3375
3376void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3377{
3378 ImGuiContext& g = *GImGui;
3379 ImGuiWindow* window = g.CurrentWindow;
3380
3381 if (!text_end)
3382 text_end = text + strlen(s: text); // FIXME-OPT
3383
3384 if (text != text_end)
3385 {
3386 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end, wrap_width);
3387 if (g.LogEnabled)
3388 LogRenderedText(ref_pos: &pos, text, text_end);
3389 }
3390}
3391
3392// Default clip_rect uses (pos_min,pos_max)
3393// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3394// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3395// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3396// better advantage of the render function taking size into account for coarse clipping.
3397void 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)
3398{
3399 // Perform CPU side clipping for single clipped element to avoid using scissor state
3400 ImVec2 pos = pos_min;
3401 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_display_end, hide_text_after_double_hash: false, wrap_width: 0.0f);
3402
3403 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3404 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3405 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3406 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3407 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3408
3409 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3410 if (align.x > 0.0f) pos.x = ImMax(lhs: pos.x, rhs: pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3411 if (align.y > 0.0f) pos.y = ImMax(lhs: pos.y, rhs: pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3412
3413 // Render
3414 if (need_clipping)
3415 {
3416 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3417 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, cpu_fine_clip_rect: &fine_clip_rect);
3418 }
3419 else
3420 {
3421 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, NULL);
3422 }
3423}
3424
3425void 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)
3426{
3427 // Hide anything after a '##' string
3428 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3429 const int text_len = (int)(text_display_end - text);
3430 if (text_len == 0)
3431 return;
3432
3433 ImGuiContext& g = *GImGui;
3434 ImGuiWindow* window = g.CurrentWindow;
3435 RenderTextClippedEx(draw_list: window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3436 if (g.LogEnabled)
3437 LogRenderedText(ref_pos: &pos_min, text, text_end: text_display_end);
3438}
3439
3440// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3441// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3442// 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.
3443void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3444{
3445 ImGuiContext& g = *GImGui;
3446 if (text_end_full == NULL)
3447 text_end_full = FindRenderedTextEnd(text);
3448 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_end_full, hide_text_after_double_hash: false, wrap_width: 0.0f);
3449
3450 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3451 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3452 //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3453 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3454 if (text_size.x > pos_max.x - pos_min.x)
3455 {
3456 // Hello wo...
3457 // | | |
3458 // min max ellipsis_max
3459 // <-> this is generally some padding value
3460
3461 const ImFont* font = draw_list->_Data->Font;
3462 const float font_size = draw_list->_Data->FontSize;
3463 const float font_scale = font_size / font->FontSize;
3464 const char* text_end_ellipsis = NULL;
3465 const float ellipsis_width = font->EllipsisWidth * font_scale;
3466
3467 // We can now claim the space between pos_max.x and ellipsis_max.x
3468 const float text_avail_width = ImMax(lhs: (ImMax(lhs: pos_max.x, rhs: ellipsis_max_x) - ellipsis_width) - pos_min.x, rhs: 1.0f);
3469 float text_size_clipped_x = font->CalcTextSizeA(size: font_size, max_width: text_avail_width, wrap_width: 0.0f, text_begin: text, text_end: text_end_full, remaining: &text_end_ellipsis).x;
3470 if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3471 {
3472 // Always display at least 1 character if there's no room for character + ellipsis
3473 text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(in_text: text, in_text_end: text_end_full);
3474 text_size_clipped_x = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text, text_end: text_end_ellipsis).x;
3475 }
3476 while (text_end_ellipsis > text && ImCharIsBlankA(c: text_end_ellipsis[-1]))
3477 {
3478 // 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)
3479 text_end_ellipsis--;
3480 text_size_clipped_x -= font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text_end_ellipsis, text_end: text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3481 }
3482
3483 // Render text, render ellipsis
3484 RenderTextClippedEx(draw_list, pos_min, pos_max: ImVec2(clip_max_x, pos_max.y), text, text_display_end: text_end_ellipsis, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3485 ImVec2 ellipsis_pos = ImTrunc(v: ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3486 if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3487 for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3488 font->RenderChar(draw_list, size: font_size, pos: ellipsis_pos, col: GetColorU32(idx: ImGuiCol_Text), c: font->EllipsisChar);
3489 }
3490 else
3491 {
3492 RenderTextClippedEx(draw_list, pos_min, pos_max: ImVec2(clip_max_x, pos_max.y), text, text_display_end: text_end_full, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3493 }
3494
3495 if (g.LogEnabled)
3496 LogRenderedText(ref_pos: &pos_min, text, text_end: text_end_full);
3497}
3498
3499// Render a rectangle shaped with optional rounding and borders
3500void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3501{
3502 ImGuiContext& g = *GImGui;
3503 ImGuiWindow* window = g.CurrentWindow;
3504 window->DrawList->AddRectFilled(p_min, p_max, col: fill_col, rounding);
3505 const float border_size = g.Style.FrameBorderSize;
3506 if (border && border_size > 0.0f)
3507 {
3508 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3509 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3510 }
3511}
3512
3513void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3514{
3515 ImGuiContext& g = *GImGui;
3516 ImGuiWindow* window = g.CurrentWindow;
3517 const float border_size = g.Style.FrameBorderSize;
3518 if (border_size > 0.0f)
3519 {
3520 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3521 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3522 }
3523}
3524
3525void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3526{
3527 ImGuiContext& g = *GImGui;
3528 if (id != g.NavId)
3529 return;
3530 if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3531 return;
3532 ImGuiWindow* window = g.CurrentWindow;
3533 if (window->DC.NavHideHighlightOneFrame)
3534 return;
3535
3536 float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3537 ImRect display_rect = bb;
3538 display_rect.ClipWith(r: window->ClipRect);
3539 const float thickness = 2.0f;
3540 if (flags & ImGuiNavHighlightFlags_Compact)
3541 {
3542 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavHighlight), rounding, flags: 0, thickness);
3543 }
3544 else
3545 {
3546 const float distance = 3.0f + thickness * 0.5f;
3547 display_rect.Expand(amount: ImVec2(distance, distance));
3548 bool fully_visible = window->ClipRect.Contains(r: display_rect);
3549 if (!fully_visible)
3550 window->DrawList->PushClipRect(clip_rect_min: display_rect.Min, clip_rect_max: display_rect.Max);
3551 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavHighlight), rounding, flags: 0, thickness);
3552 if (!fully_visible)
3553 window->DrawList->PopClipRect();
3554 }
3555}
3556
3557void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3558{
3559 ImGuiContext& g = *GImGui;
3560 IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3561 ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3562 for (ImGuiViewportP* viewport : g.Viewports)
3563 {
3564 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3565 ImVec2 offset, size, uv[4];
3566 if (!font_atlas->GetMouseCursorTexData(cursor: mouse_cursor, out_offset: &offset, out_size: &size, out_uv_border: &uv[0], out_uv_fill: &uv[2]))
3567 continue;
3568 const ImVec2 pos = base_pos - offset;
3569 const float scale = base_scale * viewport->DpiScale;
3570 if (!viewport->GetMainRect().Overlaps(r: ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3571 continue;
3572 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3573 ImTextureID tex_id = font_atlas->TexID;
3574 draw_list->PushTextureID(texture_id: tex_id);
3575 draw_list->AddImage(user_texture_id: tex_id, p_min: pos + ImVec2(1, 0) * scale, p_max: pos + (ImVec2(1, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3576 draw_list->AddImage(user_texture_id: tex_id, p_min: pos + ImVec2(2, 0) * scale, p_max: pos + (ImVec2(2, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3577 draw_list->AddImage(user_texture_id: tex_id, p_min: pos, p_max: pos + size * scale, uv_min: uv[2], uv_max: uv[3], col: col_border);
3578 draw_list->AddImage(user_texture_id: tex_id, p_min: pos, p_max: pos + size * scale, uv_min: uv[0], uv_max: uv[1], col: col_fill);
3579 draw_list->PopTextureID();
3580 }
3581}
3582
3583//-----------------------------------------------------------------------------
3584// [SECTION] INITIALIZATION, SHUTDOWN
3585//-----------------------------------------------------------------------------
3586
3587// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3588// 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
3589ImGuiContext* ImGui::GetCurrentContext()
3590{
3591 return GImGui;
3592}
3593
3594void ImGui::SetCurrentContext(ImGuiContext* ctx)
3595{
3596#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3597 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3598#else
3599 GImGui = ctx;
3600#endif
3601}
3602
3603void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3604{
3605 GImAllocatorAllocFunc = alloc_func;
3606 GImAllocatorFreeFunc = free_func;
3607 GImAllocatorUserData = user_data;
3608}
3609
3610// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3611void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3612{
3613 *p_alloc_func = GImAllocatorAllocFunc;
3614 *p_free_func = GImAllocatorFreeFunc;
3615 *p_user_data = GImAllocatorUserData;
3616}
3617
3618ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3619{
3620 ImGuiContext* prev_ctx = GetCurrentContext();
3621 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3622 SetCurrentContext(ctx);
3623 Initialize();
3624 if (prev_ctx != NULL)
3625 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3626 return ctx;
3627}
3628
3629void ImGui::DestroyContext(ImGuiContext* ctx)
3630{
3631 ImGuiContext* prev_ctx = GetCurrentContext();
3632 if (ctx == NULL) //-V1051
3633 ctx = prev_ctx;
3634 SetCurrentContext(ctx);
3635 Shutdown();
3636 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3637 IM_DELETE(p: ctx);
3638}
3639
3640// IMPORTANT: ###xxx suffixes must be same in ALL languages
3641static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3642{
3643 { .Key: ImGuiLocKey_VersionStr, .Text: "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3644 { .Key: ImGuiLocKey_TableSizeOne, .Text: "Size column to fit###SizeOne" },
3645 { .Key: ImGuiLocKey_TableSizeAllFit, .Text: "Size all columns to fit###SizeAll" },
3646 { .Key: ImGuiLocKey_TableSizeAllDefault, .Text: "Size all columns to default###SizeAll" },
3647 { .Key: ImGuiLocKey_TableResetOrder, .Text: "Reset order###ResetOrder" },
3648 { .Key: ImGuiLocKey_WindowingMainMenuBar, .Text: "(Main menu bar)" },
3649 { .Key: ImGuiLocKey_WindowingPopup, .Text: "(Popup)" },
3650 { .Key: ImGuiLocKey_WindowingUntitled, .Text: "(Untitled)" },
3651 { .Key: ImGuiLocKey_DockingHideTabBar, .Text: "Hide tab bar###HideTabBar" },
3652 { .Key: ImGuiLocKey_DockingHoldShiftToDock, .Text: "Hold SHIFT to enable Docking window." },
3653 { .Key: ImGuiLocKey_DockingDragToUndockOrMoveNode,.Text: "Click and drag to move or undock whole node." },
3654};
3655
3656void ImGui::Initialize()
3657{
3658 ImGuiContext& g = *GImGui;
3659 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3660
3661 // Add .ini handle for ImGuiWindow and ImGuiTable types
3662 {
3663 ImGuiSettingsHandler ini_handler;
3664 ini_handler.TypeName = "Window";
3665 ini_handler.TypeHash = ImHashStr(data_p: "Window");
3666 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3667 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3668 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3669 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3670 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3671 AddSettingsHandler(handler: &ini_handler);
3672 }
3673 TableSettingsAddSettingsHandler();
3674
3675 // Setup default localization table
3676 LocalizeRegisterEntries(entries: GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3677
3678 // Setup default platform clipboard/IME handlers.
3679 g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
3680 g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3681 g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3682 g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3683
3684 // Create default viewport
3685 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3686 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3687 viewport->Idx = 0;
3688 viewport->PlatformWindowCreated = true;
3689 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3690 g.Viewports.push_back(v: viewport);
3691 g.TempBuffer.resize(new_size: 1024 * 3 + 1, v: 0);
3692 g.ViewportCreatedCount++;
3693 g.PlatformIO.Viewports.push_back(v: g.Viewports[0]);
3694
3695 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3696 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3697 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3698 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3699 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3700 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3701 g.KeysMayBeCharInput.SetBit(key);
3702
3703#ifdef IMGUI_HAS_DOCK
3704 // Initialize Docking
3705 DockContextInitialize(ctx: &g);
3706#endif
3707
3708 g.Initialized = true;
3709}
3710
3711// This function is merely here to free heap allocations.
3712void ImGui::Shutdown()
3713{
3714 ImGuiContext& g = *GImGui;
3715 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3716 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3717
3718 // 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)
3719 if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3720 {
3721 g.IO.Fonts->Locked = false;
3722 IM_DELETE(p: g.IO.Fonts);
3723 }
3724 g.IO.Fonts = NULL;
3725 g.DrawListSharedData.TempBuffer.clear();
3726
3727 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3728 if (!g.Initialized)
3729 return;
3730
3731 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3732 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3733 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
3734
3735 // Destroy platform windows
3736 DestroyPlatformWindows();
3737
3738 // Shutdown extensions
3739 DockContextShutdown(ctx: &g);
3740
3741 CallContextHooks(context: &g, type: ImGuiContextHookType_Shutdown);
3742
3743 // Clear everything else
3744 g.Windows.clear_delete();
3745 g.WindowsFocusOrder.clear();
3746 g.WindowsTempSortBuffer.clear();
3747 g.CurrentWindow = NULL;
3748 g.CurrentWindowStack.clear();
3749 g.WindowsById.Clear();
3750 g.NavWindow = NULL;
3751 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3752 g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3753 g.MovingWindow = NULL;
3754
3755 g.KeysRoutingTable.Clear();
3756
3757 g.ColorStack.clear();
3758 g.StyleVarStack.clear();
3759 g.FontStack.clear();
3760 g.OpenPopupStack.clear();
3761 g.BeginPopupStack.clear();
3762 g.NavTreeNodeStack.clear();
3763
3764 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3765 g.Viewports.clear_delete();
3766
3767 g.TabBars.Clear();
3768 g.CurrentTabBarStack.clear();
3769 g.ShrinkWidthBuffer.clear();
3770
3771 g.ClipperTempData.clear_destruct();
3772
3773 g.Tables.Clear();
3774 g.TablesTempData.clear_destruct();
3775 g.DrawChannelsTempMergeBuffer.clear();
3776
3777 g.ClipboardHandlerData.clear();
3778 g.MenusIdSubmittedThisFrame.clear();
3779 g.InputTextState.ClearFreeMemory();
3780 g.InputTextDeactivatedState.ClearFreeMemory();
3781
3782 g.SettingsWindows.clear();
3783 g.SettingsHandlers.clear();
3784
3785 if (g.LogFile)
3786 {
3787#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3788 if (g.LogFile != stdout)
3789#endif
3790 ImFileClose(f: g.LogFile);
3791 g.LogFile = NULL;
3792 }
3793 g.LogBuffer.clear();
3794 g.DebugLogBuf.clear();
3795 g.DebugLogIndex.clear();
3796
3797 g.Initialized = false;
3798}
3799
3800// No specific ordering/dependency support, will see as needed
3801ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3802{
3803 ImGuiContext& g = *ctx;
3804 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3805 g.Hooks.push_back(v: *hook);
3806 g.Hooks.back().HookId = ++g.HookIdNext;
3807 return g.HookIdNext;
3808}
3809
3810// Deferred removal, avoiding issue with changing vector while iterating it
3811void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3812{
3813 ImGuiContext& g = *ctx;
3814 IM_ASSERT(hook_id != 0);
3815 for (ImGuiContextHook& hook : g.Hooks)
3816 if (hook.HookId == hook_id)
3817 hook.Type = ImGuiContextHookType_PendingRemoval_;
3818}
3819
3820// Call context hooks (used by e.g. test engine)
3821// We assume a small number of hooks so all stored in same array
3822void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3823{
3824 ImGuiContext& g = *ctx;
3825 for (ImGuiContextHook& hook : g.Hooks)
3826 if (hook.Type == hook_type)
3827 hook.Callback(&g, &hook);
3828}
3829
3830
3831//-----------------------------------------------------------------------------
3832// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3833//-----------------------------------------------------------------------------
3834
3835// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3836ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3837{
3838 memset(s: this, c: 0, n: sizeof(*this));
3839 Ctx = ctx;
3840 Name = ImStrdup(str: name);
3841 NameBufLen = (int)strlen(s: name) + 1;
3842 ID = ImHashStr(data_p: name);
3843 IDStack.push_back(v: ID);
3844 ViewportAllowPlatformMonitorExtend = -1;
3845 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3846 MoveId = GetID(str: "#MOVE");
3847 TabId = GetID(str: "#TAB");
3848 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3849 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3850 AutoFitFramesX = AutoFitFramesY = -1;
3851 AutoPosLastDirection = ImGuiDir_None;
3852 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3853 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3854 LastFrameActive = -1;
3855 LastFrameJustFocused = -1;
3856 LastTimeActive = -1.0f;
3857 FontWindowScale = FontDpiScale = 1.0f;
3858 SettingsOffset = -1;
3859 DockOrder = -1;
3860 DrawList = &DrawListInst;
3861 DrawList->_Data = &Ctx->DrawListSharedData;
3862 DrawList->_OwnerName = Name;
3863 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3864 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3865}
3866
3867ImGuiWindow::~ImGuiWindow()
3868{
3869 IM_ASSERT(DrawList == &DrawListInst);
3870 IM_DELETE(p: Name);
3871 ColumnsStorage.clear_destruct();
3872}
3873
3874static void SetCurrentWindow(ImGuiWindow* window)
3875{
3876 ImGuiContext& g = *GImGui;
3877 g.CurrentWindow = window;
3878 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(n: window->DC.CurrentTableIdx) : NULL;
3879 if (window)
3880 {
3881 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3882 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3883 }
3884}
3885
3886void ImGui::GcCompactTransientMiscBuffers()
3887{
3888 ImGuiContext& g = *GImGui;
3889 g.ItemFlagsStack.clear();
3890 g.GroupStack.clear();
3891 TableGcCompactSettings();
3892}
3893
3894// Free up/compact internal window buffers, we can use this when a window becomes unused.
3895// Not freed:
3896// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3897// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3898void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3899{
3900 window->MemoryCompacted = true;
3901 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3902 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3903 window->IDStack.clear();
3904 window->DrawList->_ClearFreeMemory();
3905 window->DC.ChildWindows.clear();
3906 window->DC.ItemWidthStack.clear();
3907 window->DC.TextWrapPosStack.clear();
3908}
3909
3910void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3911{
3912 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3913 // The other buffers tends to amortize much faster.
3914 window->MemoryCompacted = false;
3915 window->DrawList->IdxBuffer.reserve(new_capacity: window->MemoryDrawListIdxCapacity);
3916 window->DrawList->VtxBuffer.reserve(new_capacity: window->MemoryDrawListVtxCapacity);
3917 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3918}
3919
3920void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3921{
3922 ImGuiContext& g = *GImGui;
3923
3924 // Clear previous active id
3925 if (g.ActiveId != 0)
3926 {
3927 // While most behaved code would make an effort to not steal active id during window move/drag operations,
3928 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3929 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3930 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3931 {
3932 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3933 g.MovingWindow = NULL;
3934 }
3935
3936 // This could be written in a more general way (e.g associate a hook to ActiveId),
3937 // but since this is currently quite an exception we'll leave it as is.
3938 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3939 if (g.InputTextState.ID == g.ActiveId)
3940 InputTextDeactivateHook(id: g.ActiveId);
3941 }
3942
3943 // Set active id
3944 g.ActiveIdIsJustActivated = (g.ActiveId != id);
3945 if (g.ActiveIdIsJustActivated)
3946 {
3947 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 : "");
3948 g.ActiveIdTimer = 0.0f;
3949 g.ActiveIdHasBeenPressedBefore = false;
3950 g.ActiveIdHasBeenEditedBefore = false;
3951 g.ActiveIdMouseButton = -1;
3952 if (id != 0)
3953 {
3954 g.LastActiveId = id;
3955 g.LastActiveIdTimer = 0.0f;
3956 }
3957 }
3958 g.ActiveId = id;
3959 g.ActiveIdAllowOverlap = false;
3960 g.ActiveIdNoClearOnFocusLoss = false;
3961 g.ActiveIdWindow = window;
3962 g.ActiveIdHasBeenEditedThisFrame = false;
3963 g.ActiveIdFromShortcut = false;
3964 if (id)
3965 {
3966 g.ActiveIdIsAlive = id;
3967 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3968 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3969 }
3970
3971 // Clear declaration of inputs claimed by the widget
3972 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3973 g.ActiveIdUsingNavDirMask = 0x00;
3974 g.ActiveIdUsingAllKeyboardKeys = false;
3975#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3976 g.ActiveIdUsingNavInputMask = 0x00;
3977#endif
3978}
3979
3980void ImGui::ClearActiveID()
3981{
3982 SetActiveID(id: 0, NULL); // g.ActiveId = 0;
3983}
3984
3985void ImGui::SetHoveredID(ImGuiID id)
3986{
3987 ImGuiContext& g = *GImGui;
3988 g.HoveredId = id;
3989 g.HoveredIdAllowOverlap = false;
3990 if (id != 0 && g.HoveredIdPreviousFrame != id)
3991 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3992}
3993
3994ImGuiID ImGui::GetHoveredID()
3995{
3996 ImGuiContext& g = *GImGui;
3997 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3998}
3999
4000void ImGui::MarkItemEdited(ImGuiID id)
4001{
4002 // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4003 // 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.
4004 ImGuiContext& g = *GImGui;
4005 if (g.LockMarkEdited > 0)
4006 return;
4007 if (g.ActiveId == id || g.ActiveId == 0)
4008 {
4009 g.ActiveIdHasBeenEditedThisFrame = true;
4010 g.ActiveIdHasBeenEditedBefore = true;
4011 }
4012
4013 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4014 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4015 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4016
4017 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4018 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4019}
4020
4021bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4022{
4023 // An active popup disable hovering on other windows (apart from its own children)
4024 // FIXME-OPT: This could be cached/stored within the window.
4025 ImGuiContext& g = *GImGui;
4026 if (g.NavWindow)
4027 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4028 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4029 {
4030 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4031 // NB: The 'else' is important because Modal windows are also Popups.
4032 bool want_inhibit = false;
4033 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4034 want_inhibit = true;
4035 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4036 want_inhibit = true;
4037
4038 // Inhibit hover unless the window is within the stack of our modal/popup
4039 if (want_inhibit)
4040 if (!IsWindowWithinBeginStackOf(window: window->RootWindow, potential_parent: focused_root_window))
4041 return false;
4042 }
4043
4044 // Filter by viewport
4045 if (window->Viewport != g.MouseViewport)
4046 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4047 return false;
4048
4049 return true;
4050}
4051
4052static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4053{
4054 ImGuiContext& g = *GImGui;
4055 if (flags & ImGuiHoveredFlags_DelayNormal)
4056 return g.Style.HoverDelayNormal;
4057 if (flags & ImGuiHoveredFlags_DelayShort)
4058 return g.Style.HoverDelayShort;
4059 return 0.0f;
4060}
4061
4062static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4063{
4064 // Allow instance flags to override shared flags
4065 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4066 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4067 return user_flags | shared_flags;
4068}
4069
4070// This is roughly matching the behavior of internal-facing ItemHoverable()
4071// - 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()
4072// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4073bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4074{
4075 ImGuiContext& g = *GImGui;
4076 ImGuiWindow* window = g.CurrentWindow;
4077 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4078
4079 if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4080 {
4081 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4082 return false;
4083 if (!IsItemFocused())
4084 return false;
4085
4086 if (flags & ImGuiHoveredFlags_ForTooltip)
4087 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipNav);
4088 }
4089 else
4090 {
4091 // Test for bounding box overlap, as updated as ItemAdd()
4092 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4093 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4094 return false;
4095
4096 if (flags & ImGuiHoveredFlags_ForTooltip)
4097 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
4098
4099 IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0); // Flags not supported by this function
4100
4101 // Done with rectangle culling so we can perform heavier checks now
4102 // Test if we are hovering the right window (our window could be behind another window)
4103 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4104 // [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
4105 // 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
4106 // the test that has been running for a long while.
4107 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4108 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4109 return false;
4110
4111 // Test if another item is active (e.g. being dragged)
4112 const ImGuiID id = g.LastItemData.ID;
4113 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4114 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4115 if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4116 return false;
4117
4118 // Test if interactions on this window are blocked by an active popup or modal.
4119 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4120 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4121 return false;
4122
4123 // Test if the item is disabled
4124 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4125 return false;
4126
4127 // Special handling for calling after Begin() which represent the title bar or tab.
4128 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4129 // will never be overwritten so we need to detect the case.
4130 if (id == window->MoveId && window->WriteAccessed)
4131 return false;
4132
4133 // Test if using AllowOverlap and overlapped
4134 if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4135 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4136 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4137 return false;
4138 }
4139
4140 // Handle hover delay
4141 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4142 const float delay = CalcDelayFromHoveredFlags(flags);
4143 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4144 {
4145 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(r_abs: g.LastItemData.Rect);
4146 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4147 g.HoverItemDelayTimer = 0.0f;
4148 g.HoverItemDelayId = hover_delay_id;
4149
4150 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4151 // but once unlocked on a given item we also moving.
4152 //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); }
4153 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4154 return false;
4155
4156 if (g.HoverItemDelayTimer < delay)
4157 return false;
4158 }
4159
4160 return true;
4161}
4162
4163// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4164// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4165// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4166// If you used this in your legacy/custom widgets code:
4167// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4168// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4169bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4170{
4171 ImGuiContext& g = *GImGui;
4172 ImGuiWindow* window = g.CurrentWindow;
4173 if (g.HoveredWindow != window)
4174 return false;
4175 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
4176 return false;
4177
4178 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4179 return false;
4180 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4181 if (!g.ActiveIdFromShortcut)
4182 return false;
4183
4184 // Done with rectangle culling so we can perform heavier checks now.
4185 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, flags: ImGuiHoveredFlags_None))
4186 {
4187 g.HoveredIdDisabled = true;
4188 return false;
4189 }
4190
4191 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4192 // hover test in widgets code. We could also decide to split this function is two.
4193 if (id != 0)
4194 {
4195 // Drag source doesn't report as hovered
4196 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4197 return false;
4198
4199 SetHoveredID(id);
4200
4201 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4202 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4203 if (item_flags & ImGuiItemFlags_AllowOverlap)
4204 {
4205 g.HoveredIdAllowOverlap = true;
4206 if (g.HoveredIdPreviousFrame != id)
4207 return false;
4208 }
4209 }
4210
4211 // When disabled we'll return false but still set HoveredId
4212 if (item_flags & ImGuiItemFlags_Disabled)
4213 {
4214 // Release active id if turning disabled
4215 if (g.ActiveId == id && id != 0)
4216 ClearActiveID();
4217 g.HoveredIdDisabled = true;
4218 return false;
4219 }
4220
4221#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4222 if (id != 0)
4223 {
4224 // [DEBUG] Item Picker tool!
4225 // We perform the check here because reaching is path is rare (1~ time a frame),
4226 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4227 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4228 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4229 GetForegroundDrawList()->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
4230 if (g.DebugItemPickerBreakId == id)
4231 IM_DEBUG_BREAK();
4232 }
4233#endif
4234
4235 if (g.NavDisableMouseHover)
4236 return false;
4237
4238 return true;
4239}
4240
4241// FIXME: This is inlined/duplicated in ItemAdd()
4242// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4243bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4244{
4245 ImGuiContext& g = *GImGui;
4246 ImGuiWindow* window = g.CurrentWindow;
4247 if (!bb.Overlaps(r: window->ClipRect))
4248 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4249 if (!g.LogEnabled)
4250 return true;
4251 return false;
4252}
4253
4254// This is also inlined in ItemAdd()
4255// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4256void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4257{
4258 ImGuiContext& g = *GImGui;
4259 g.LastItemData.ID = item_id;
4260 g.LastItemData.InFlags = in_flags;
4261 g.LastItemData.StatusFlags = item_flags;
4262 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4263}
4264
4265float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4266{
4267 if (wrap_pos_x < 0.0f)
4268 return 0.0f;
4269
4270 ImGuiContext& g = *GImGui;
4271 ImGuiWindow* window = g.CurrentWindow;
4272 if (wrap_pos_x == 0.0f)
4273 {
4274 // We could decide to setup a default wrapping max point for auto-resizing windows,
4275 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4276 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4277 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4278 //else
4279 wrap_pos_x = window->WorkRect.Max.x;
4280 }
4281 else if (wrap_pos_x > 0.0f)
4282 {
4283 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4284 }
4285
4286 return ImMax(lhs: wrap_pos_x - pos.x, rhs: 1.0f);
4287}
4288
4289// IM_ALLOC() == ImGui::MemAlloc()
4290void* ImGui::MemAlloc(size_t size)
4291{
4292 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4293#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4294 if (ImGuiContext* ctx = GImGui)
4295 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size);
4296#endif
4297 return ptr;
4298}
4299
4300// IM_FREE() == ImGui::MemFree()
4301void ImGui::MemFree(void* ptr)
4302{
4303#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4304 if (ptr != NULL)
4305 if (ImGuiContext* ctx = GImGui)
4306 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size: (size_t)-1);
4307#endif
4308 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4309}
4310
4311// 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"
4312void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4313{
4314 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4315 IM_UNUSED(ptr);
4316 if (entry->FrameCount != frame_count)
4317 {
4318 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4319 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4320 entry->FrameCount = frame_count;
4321 entry->AllocCount = entry->FreeCount = 0;
4322 }
4323 if (size != (size_t)-1)
4324 {
4325 entry->AllocCount++;
4326 info->TotalAllocCount++;
4327 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4328 }
4329 else
4330 {
4331 entry->FreeCount++;
4332 info->TotalFreeCount++;
4333 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4334 }
4335}
4336
4337const char* ImGui::GetClipboardText()
4338{
4339 ImGuiContext& g = *GImGui;
4340 return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4341}
4342
4343void ImGui::SetClipboardText(const char* text)
4344{
4345 ImGuiContext& g = *GImGui;
4346 if (g.IO.SetClipboardTextFn)
4347 g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4348}
4349
4350const char* ImGui::GetVersion()
4351{
4352 return IMGUI_VERSION;
4353}
4354
4355ImGuiIO& ImGui::GetIO()
4356{
4357 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4358 return GImGui->IO;
4359}
4360
4361ImGuiPlatformIO& ImGui::GetPlatformIO()
4362{
4363 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4364 return GImGui->PlatformIO;
4365}
4366
4367// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4368ImDrawData* ImGui::GetDrawData()
4369{
4370 ImGuiContext& g = *GImGui;
4371 ImGuiViewportP* viewport = g.Viewports[0];
4372 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4373}
4374
4375double ImGui::GetTime()
4376{
4377 return GImGui->Time;
4378}
4379
4380int ImGui::GetFrameCount()
4381{
4382 return GImGui->FrameCount;
4383}
4384
4385static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4386{
4387 // Create the draw list on demand, because they are not frequently used for all viewports
4388 ImGuiContext& g = *GImGui;
4389 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4390 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4391 if (draw_list == NULL)
4392 {
4393 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4394 draw_list->_OwnerName = drawlist_name;
4395 viewport->BgFgDrawLists[drawlist_no] = draw_list;
4396 }
4397
4398 // Our ImDrawList system requires that there is always a command
4399 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4400 {
4401 draw_list->_ResetForNewFrame();
4402 draw_list->PushTextureID(texture_id: g.IO.Fonts->TexID);
4403 draw_list->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size, intersect_with_current_clip_rect: false);
4404 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4405 }
4406 return draw_list;
4407}
4408
4409ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4410{
4411 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 0, drawlist_name: "##Background");
4412}
4413
4414ImDrawList* ImGui::GetBackgroundDrawList()
4415{
4416 ImGuiContext& g = *GImGui;
4417 return GetBackgroundDrawList(viewport: g.CurrentWindow->Viewport);
4418}
4419
4420ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4421{
4422 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 1, drawlist_name: "##Foreground");
4423}
4424
4425ImDrawList* ImGui::GetForegroundDrawList()
4426{
4427 ImGuiContext& g = *GImGui;
4428 return GetForegroundDrawList(viewport: g.CurrentWindow->Viewport);
4429}
4430
4431ImDrawListSharedData* ImGui::GetDrawListSharedData()
4432{
4433 return &GImGui->DrawListSharedData;
4434}
4435
4436void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4437{
4438 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4439 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4440 // This is because we want ActiveId to be set even when the window is not permitted to move.
4441 ImGuiContext& g = *GImGui;
4442 FocusWindow(window);
4443 SetActiveID(id: window->MoveId, window);
4444 g.NavDisableHighlight = true;
4445 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4446 g.ActiveIdNoClearOnFocusLoss = true;
4447 SetActiveIdUsingAllKeyboardKeys();
4448
4449 bool can_move_window = true;
4450 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4451 can_move_window = false;
4452 if (ImGuiDockNode* node = window->DockNodeAsHost)
4453 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4454 can_move_window = false;
4455 if (can_move_window)
4456 g.MovingWindow = window;
4457}
4458
4459// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4460void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4461{
4462 ImGuiContext& g = *GImGui;
4463 bool can_undock_node = false;
4464 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4465 {
4466 // Can undock if:
4467 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4468 // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4469 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4470 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4471 can_undock_node = true;
4472 }
4473
4474 const bool clicked = IsMouseClicked(button: 0);
4475 const bool dragging = IsMouseDragging(button: 0);
4476 if (can_undock_node && dragging)
4477 DockContextQueueUndockNode(ctx: &g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4478 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4479 StartMouseMovingWindow(window);
4480}
4481
4482// Handle mouse moving window
4483// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4484// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4485// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4486// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4487void ImGui::UpdateMouseMovingWindowNewFrame()
4488{
4489 ImGuiContext& g = *GImGui;
4490 if (g.MovingWindow != NULL)
4491 {
4492 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4493 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4494 KeepAliveID(id: g.ActiveId);
4495 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4496 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4497
4498 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4499 const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4500 if (g.IO.MouseDown[0] && IsMousePosValid(mouse_pos: &g.IO.MousePos) && !window_disappared)
4501 {
4502 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4503 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4504 {
4505 SetWindowPos(window: moving_window, pos, cond: ImGuiCond_Always);
4506 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4507 {
4508 moving_window->Viewport->Pos = pos;
4509 moving_window->Viewport->UpdateWorkRect();
4510 }
4511 }
4512 FocusWindow(window: g.MovingWindow);
4513 }
4514 else
4515 {
4516 if (!window_disappared)
4517 {
4518 // Try to merge the window back into the main viewport.
4519 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4520 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4521 UpdateTryMergeWindowIntoHostViewport(window: moving_window, host_viewport: g.MouseViewport);
4522
4523 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4524 if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4525 g.MouseViewport = moving_window->Viewport;
4526
4527 // Clear the NoInput window flag set by the Viewport system
4528 if (moving_window->Viewport)
4529 moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4530 }
4531
4532 g.MovingWindow = NULL;
4533 ClearActiveID();
4534 }
4535 }
4536 else
4537 {
4538 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4539 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4540 {
4541 KeepAliveID(id: g.ActiveId);
4542 if (!g.IO.MouseDown[0])
4543 ClearActiveID();
4544 }
4545 }
4546}
4547
4548// Initiate moving window when clicking on empty space or title bar.
4549// Handle left-click and right-click focus.
4550void ImGui::UpdateMouseMovingWindowEndFrame()
4551{
4552 ImGuiContext& g = *GImGui;
4553 if (g.ActiveId != 0 || g.HoveredId != 0)
4554 return;
4555
4556 // Unless we just made a window/popup appear
4557 if (g.NavWindow && g.NavWindow->Appearing)
4558 return;
4559
4560 // Click on empty space to focus window and start moving
4561 // (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!)
4562 if (g.IO.MouseClicked[0])
4563 {
4564 // Handle the edge case of a popup being closed while clicking in its empty space.
4565 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4566 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4567 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(id: root_window->PopupId, popup_flags: ImGuiPopupFlags_AnyPopupLevel);
4568
4569 if (root_window != NULL && !is_closed_popup)
4570 {
4571 StartMouseMovingWindow(window: g.HoveredWindow); //-V595
4572
4573 // Cancel moving if clicked outside of title bar
4574 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4575 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4576 if (!root_window->TitleBarRect().Contains(p: g.IO.MouseClickedPos[0]))
4577 g.MovingWindow = NULL;
4578
4579 // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4580 if (g.HoveredIdDisabled)
4581 g.MovingWindow = NULL;
4582 }
4583 else if (root_window == NULL && g.NavWindow != NULL)
4584 {
4585 // Clicking on void disable focus
4586 FocusWindow(NULL, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
4587 }
4588 }
4589
4590 // With right mouse button we close popups without changing focus based on where the mouse is aimed
4591 // Instead, focus will be restored to the window under the bottom-most closed popup.
4592 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4593 if (g.IO.MouseClicked[1])
4594 {
4595 // Find the top-most window between HoveredWindow and the top-most Modal Window.
4596 // This is where we can trim the popup stack.
4597 ImGuiWindow* modal = GetTopMostPopupModal();
4598 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(potential_above: g.HoveredWindow, potential_below: modal));
4599 ClosePopupsOverWindow(ref_window: hovered_window_above_modal ? g.HoveredWindow : modal, restore_focus_to_window_under_popup: true);
4600 }
4601}
4602
4603// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4604// Need to keep in sync with SetWindowPos()
4605static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4606{
4607 window->Pos += delta;
4608 window->ClipRect.Translate(d: delta);
4609 window->OuterRectClipped.Translate(d: delta);
4610 window->InnerRect.Translate(d: delta);
4611 window->DC.CursorPos += delta;
4612 window->DC.CursorStartPos += delta;
4613 window->DC.CursorMaxPos += delta;
4614 window->DC.IdealMaxPos += delta;
4615}
4616
4617static void ScaleWindow(ImGuiWindow* window, float scale)
4618{
4619 ImVec2 origin = window->Viewport->Pos;
4620 window->Pos = ImFloor(v: (window->Pos - origin) * scale + origin);
4621 window->Size = ImTrunc(v: window->Size * scale);
4622 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
4623 window->ContentSize = ImTrunc(v: window->ContentSize * scale);
4624}
4625
4626static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4627{
4628 return (window->Active) && (!window->Hidden);
4629}
4630
4631// 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)
4632void ImGui::UpdateHoveredWindowAndCaptureFlags()
4633{
4634 ImGuiContext& g = *GImGui;
4635 ImGuiIO& io = g.IO;
4636 g.WindowsHoverPadding = ImMax(lhs: g.Style.TouchExtraPadding, rhs: ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4637
4638 // Find the window hovered by mouse:
4639 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4640 // - 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.
4641 // - 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.
4642 bool clear_hovered_windows = false;
4643 FindHoveredWindow();
4644 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4645
4646 // Modal windows prevents mouse from hovering behind them.
4647 ImGuiWindow* modal_window = GetTopMostPopupModal();
4648 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(window: g.HoveredWindow->RootWindow, potential_parent: modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4649 clear_hovered_windows = true;
4650
4651 // Disabled mouse?
4652 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4653 clear_hovered_windows = true;
4654
4655 // We track click ownership. When clicked outside of a window the click is owned by the application and
4656 // won't report hovering nor request capture even while dragging over our windows afterward.
4657 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4658 const bool has_open_modal = (modal_window != NULL);
4659 int mouse_earliest_down = -1;
4660 bool mouse_any_down = false;
4661 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4662 {
4663 if (io.MouseClicked[i])
4664 {
4665 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4666 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4667 }
4668 mouse_any_down |= io.MouseDown[i];
4669 if (io.MouseDown[i])
4670 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4671 mouse_earliest_down = i;
4672 }
4673 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4674 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4675
4676 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4677 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4678 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4679 if (!mouse_avail && !mouse_dragging_extern_payload)
4680 clear_hovered_windows = true;
4681
4682 if (clear_hovered_windows)
4683 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4684
4685 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4686 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4687 if (g.WantCaptureMouseNextFrame != -1)
4688 {
4689 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4690 }
4691 else
4692 {
4693 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4694 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4695 }
4696
4697 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4698 io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4699 if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4700 io.WantCaptureKeyboard = true;
4701 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4702 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4703
4704 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4705 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4706}
4707
4708void ImGui::NewFrame()
4709{
4710 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4711 ImGuiContext& g = *GImGui;
4712
4713 // Remove pending delete hooks before frame start.
4714 // This deferred removal avoid issues of removal while iterating the hook vector
4715 for (int n = g.Hooks.Size - 1; n >= 0; n--)
4716 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4717 g.Hooks.erase(it: &g.Hooks[n]);
4718
4719 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePre);
4720
4721 // Check and assert for various common IO and Configuration mistakes
4722 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4723 ErrorCheckNewFrameSanityChecks();
4724 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4725
4726 // Load settings on first frame, save settings when modified (after a delay)
4727 UpdateSettings();
4728
4729 g.Time += g.IO.DeltaTime;
4730 g.WithinFrameScope = true;
4731 g.FrameCount += 1;
4732 g.TooltipOverrideCount = 0;
4733 g.WindowsActiveCount = 0;
4734 g.MenusIdSubmittedThisFrame.resize(new_size: 0);
4735
4736 // Calculate frame-rate for the user, as a purely luxurious feature
4737 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4738 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4739 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4740 g.FramerateSecPerFrameCount = ImMin(lhs: g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4741 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4742
4743 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4744 g.InputEventsTrail.resize(new_size: 0);
4745 UpdateInputEvents(trickle_fast_inputs: g.IO.ConfigInputTrickleEventQueue);
4746
4747 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4748 UpdateViewportsNewFrame();
4749
4750 // Setup current font and draw list shared data
4751 // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4752 g.IO.Fonts->Locked = true;
4753 SetCurrentFont(GetDefaultFont());
4754 IM_ASSERT(g.Font->IsLoaded());
4755 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4756 for (ImGuiViewportP* viewport : g.Viewports)
4757 virtual_space.Add(r: viewport->GetMainRect());
4758 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4759 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4760 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4761 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4762 if (g.Style.AntiAliasedLines)
4763 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4764 if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4765 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4766 if (g.Style.AntiAliasedFill)
4767 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4768 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4769 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4770
4771 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4772 for (ImGuiViewportP* viewport : g.Viewports)
4773 {
4774 viewport->DrawData = NULL;
4775 viewport->DrawDataP.Valid = false;
4776 }
4777
4778 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4779 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4780 KeepAliveID(id: g.DragDropPayload.SourceId);
4781
4782 // Update HoveredId data
4783 if (!g.HoveredIdPreviousFrame)
4784 g.HoveredIdTimer = 0.0f;
4785 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4786 g.HoveredIdNotActiveTimer = 0.0f;
4787 if (g.HoveredId)
4788 g.HoveredIdTimer += g.IO.DeltaTime;
4789 if (g.HoveredId && g.ActiveId != g.HoveredId)
4790 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4791 g.HoveredIdPreviousFrame = g.HoveredId;
4792 g.HoveredId = 0;
4793 g.HoveredIdAllowOverlap = false;
4794 g.HoveredIdDisabled = false;
4795
4796 // Clear ActiveID if the item is not alive anymore.
4797 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4798 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4799 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4800 {
4801 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4802 ClearActiveID();
4803 }
4804
4805 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4806 if (g.ActiveId)
4807 g.ActiveIdTimer += g.IO.DeltaTime;
4808 g.LastActiveIdTimer += g.IO.DeltaTime;
4809 g.ActiveIdPreviousFrame = g.ActiveId;
4810 g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4811 g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4812 g.ActiveIdIsAlive = 0;
4813 g.ActiveIdHasBeenEditedThisFrame = false;
4814 g.ActiveIdPreviousFrameIsAlive = false;
4815 g.ActiveIdIsJustActivated = false;
4816 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4817 g.TempInputId = 0;
4818 if (g.ActiveId == 0)
4819 {
4820 g.ActiveIdUsingNavDirMask = 0x00;
4821 g.ActiveIdUsingAllKeyboardKeys = false;
4822#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4823 g.ActiveIdUsingNavInputMask = 0x00;
4824#endif
4825 }
4826
4827#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4828 if (g.ActiveId == 0)
4829 g.ActiveIdUsingNavInputMask = 0;
4830 else if (g.ActiveIdUsingNavInputMask != 0)
4831 {
4832 // If your custom widget code used: { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4833 // Since IMGUI_VERSION_NUM >= 18804 it should be: { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4834 if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4835 SetKeyOwner(key: ImGuiKey_Escape, owner_id: g.ActiveId);
4836 if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4837 IM_ASSERT(0); // Other values unsupported
4838 }
4839#endif
4840
4841 // Record when we have been stationary as this state is preserved while over same item.
4842 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4843 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4844 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4845 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4846 else if (g.HoverItemDelayId == 0)
4847 g.HoverItemUnlockedStationaryId = 0;
4848 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4849 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4850 else if (g.HoveredWindow == NULL)
4851 g.HoverWindowUnlockedStationaryId = 0;
4852
4853 // Update hover delay for IsItemHovered() with delays and tooltips
4854 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4855 if (g.HoverItemDelayId != 0)
4856 {
4857 g.HoverItemDelayTimer += g.IO.DeltaTime;
4858 g.HoverItemDelayClearTimer = 0.0f;
4859 g.HoverItemDelayId = 0;
4860 }
4861 else if (g.HoverItemDelayTimer > 0.0f)
4862 {
4863 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4864 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4865 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4866 if (g.HoverItemDelayClearTimer >= ImMax(lhs: 0.25f, rhs: g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4867 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.
4868 }
4869
4870 // Drag and drop
4871 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4872 g.DragDropAcceptIdCurr = 0;
4873 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4874 g.DragDropWithinSource = false;
4875 g.DragDropWithinTarget = false;
4876 g.DragDropHoldJustPressedId = 0;
4877
4878 // Close popups on focus lost (currently wip/opt-in)
4879 //if (g.IO.AppFocusLost)
4880 // ClosePopupsExceptModals();
4881
4882 // Update keyboard input state
4883 UpdateKeyboardInputs();
4884
4885 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4886 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4887 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4888 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4889
4890 // Update gamepad/keyboard navigation
4891 NavUpdate();
4892
4893 // Update mouse input state
4894 UpdateMouseInputs();
4895
4896 // Undocking
4897 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4898 DockContextNewFrameUpdateUndocking(ctx: &g);
4899
4900 // Find hovered window
4901 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4902 UpdateHoveredWindowAndCaptureFlags();
4903
4904 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4905 UpdateMouseMovingWindowNewFrame();
4906
4907 // Background darkening/whitening
4908 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4909 g.DimBgRatio = ImMin(lhs: g.DimBgRatio + g.IO.DeltaTime * 6.0f, rhs: 1.0f);
4910 else
4911 g.DimBgRatio = ImMax(lhs: g.DimBgRatio - g.IO.DeltaTime * 10.0f, rhs: 0.0f);
4912
4913 g.MouseCursor = ImGuiMouseCursor_Arrow;
4914 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4915
4916 // Platform IME data: reset for the frame
4917 g.PlatformImeDataPrev = g.PlatformImeData;
4918 g.PlatformImeData.WantVisible = false;
4919
4920 // Mouse wheel scrolling, scale
4921 UpdateMouseWheel();
4922
4923 // Mark all windows as not visible and compact unused memory.
4924 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4925 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4926 for (ImGuiWindow* window : g.Windows)
4927 {
4928 window->WasActive = window->Active;
4929 window->Active = false;
4930 window->WriteAccessed = false;
4931 window->BeginCountPreviousFrame = window->BeginCount;
4932 window->BeginCount = 0;
4933
4934 // Garbage collect transient buffers of recently unused windows
4935 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4936 GcCompactTransientWindowBuffers(window);
4937 }
4938
4939 // Garbage collect transient buffers of recently unused tables
4940 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4941 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4942 TableGcCompactTransientBuffers(table: g.Tables.GetByIndex(n: i));
4943 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4944 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4945 TableGcCompactTransientBuffers(table: &table_temp_data);
4946 if (g.GcCompactAll)
4947 GcCompactTransientMiscBuffers();
4948 g.GcCompactAll = false;
4949
4950 // Closing the focused window restore focus to the first active root window in descending z-order
4951 if (g.NavWindow && !g.NavWindow->WasActive)
4952 FocusTopMostWindowUnderOne(NULL, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
4953
4954 // No window should be open at the beginning of the frame.
4955 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4956 g.CurrentWindowStack.resize(new_size: 0);
4957 g.BeginPopupStack.resize(new_size: 0);
4958 g.ItemFlagsStack.resize(new_size: 0);
4959 g.ItemFlagsStack.push_back(v: ImGuiItemFlags_None);
4960 g.GroupStack.resize(new_size: 0);
4961
4962 // Docking
4963 DockContextNewFrameUpdateDocking(ctx: &g);
4964
4965 // [DEBUG] Update debug features
4966#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4967 UpdateDebugToolItemPicker();
4968 UpdateDebugToolStackQueries();
4969 UpdateDebugToolFlashStyleColor();
4970 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4971 {
4972 g.DebugLocateId = 0;
4973 g.DebugBreakInLocateId = false;
4974 }
4975 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
4976 {
4977 DebugLog(fmt: "(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
4978 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
4979 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4980 }
4981#endif
4982
4983 // Create implicit/fallback window - which we will only render it if the user has added something to it.
4984 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4985 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4986 g.WithinFrameScopeWithImplicitWindow = true;
4987 SetNextWindowSize(size: ImVec2(400, 400), cond: ImGuiCond_FirstUseEver);
4988 Begin(name: "Debug##Default");
4989 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4990
4991 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4992 // allowing to validate correct Begin/End behavior in user code.
4993#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4994 if (g.IO.ConfigDebugBeginReturnValueLoop)
4995 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4996 else
4997 g.DebugBeginReturnValueCullDepth = -1;
4998#endif
4999
5000 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePost);
5001}
5002
5003// FIXME: Add a more explicit sort order in the window structure.
5004static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5005{
5006 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5007 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5008 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5009 return d;
5010 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5011 return d;
5012 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5013}
5014
5015static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5016{
5017 out_sorted_windows->push_back(v: window);
5018 if (window->Active)
5019 {
5020 int count = window->DC.ChildWindows.Size;
5021 ImQsort(base: window->DC.ChildWindows.Data, count: (size_t)count, size_of_element: sizeof(ImGuiWindow*), compare_func: ChildWindowComparer);
5022 for (int i = 0; i < count; i++)
5023 {
5024 ImGuiWindow* child = window->DC.ChildWindows[i];
5025 if (child->Active)
5026 AddWindowToSortBuffer(out_sorted_windows, window: child);
5027 }
5028 }
5029}
5030
5031static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5032{
5033 ImGuiContext& g = *GImGui;
5034 ImGuiViewportP* viewport = window->Viewport;
5035 IM_ASSERT(viewport != NULL);
5036 g.IO.MetricsRenderWindows++;
5037 if (window->DrawList->_Splitter._Count > 1)
5038 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5039 ImGui::AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[layer], draw_list: window->DrawList);
5040 for (ImGuiWindow* child : window->DC.ChildWindows)
5041 if (IsWindowActiveAndVisible(window: child)) // Clipped children may have been marked not active
5042 AddWindowToDrawData(window: child, layer);
5043}
5044
5045static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5046{
5047 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5048}
5049
5050// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5051static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5052{
5053 AddWindowToDrawData(window, layer: GetWindowDisplayLayer(window));
5054}
5055
5056static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5057{
5058 int n = builder->Layers[0]->Size;
5059 int full_size = n;
5060 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5061 full_size += builder->Layers[i]->Size;
5062 builder->Layers[0]->resize(new_size: full_size);
5063 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5064 {
5065 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5066 if (layer->empty())
5067 continue;
5068 memcpy(dest: builder->Layers[0]->Data + n, src: layer->Data, n: layer->Size * sizeof(ImDrawList*));
5069 n += layer->Size;
5070 layer->resize(new_size: 0);
5071 }
5072}
5073
5074static void InitViewportDrawData(ImGuiViewportP* viewport)
5075{
5076 ImGuiIO& io = ImGui::GetIO();
5077 ImDrawData* draw_data = &viewport->DrawDataP;
5078
5079 viewport->DrawData = draw_data; // Make publicly accessible
5080 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5081 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5082 viewport->DrawDataBuilder.Layers[0]->resize(new_size: 0);
5083 viewport->DrawDataBuilder.Layers[1]->resize(new_size: 0);
5084
5085 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5086 // and to allow applications/backends to easily skip rendering.
5087 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5088 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5089 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5090 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5091
5092 draw_data->Valid = true;
5093 draw_data->CmdListsCount = 0;
5094 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5095 draw_data->DisplayPos = viewport->Pos;
5096 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5097 draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5098 draw_data->OwnerViewport = viewport;
5099}
5100
5101// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5102// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5103// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5104// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5105// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5106// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5107void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5108{
5109 ImGuiWindow* window = GetCurrentWindow();
5110 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5111 window->ClipRect = window->DrawList->_ClipRectStack.back();
5112}
5113
5114void ImGui::PopClipRect()
5115{
5116 ImGuiWindow* window = GetCurrentWindow();
5117 window->DrawList->PopClipRect();
5118 window->ClipRect = window->DrawList->_ClipRectStack.back();
5119}
5120
5121static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5122{
5123 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5124 if (IsWindowActiveAndVisible(window: window->DC.ChildWindows[n]))
5125 return FindFrontMostVisibleChildWindow(window: window->DC.ChildWindows[n]);
5126 return window;
5127}
5128
5129static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5130{
5131 if ((col & IM_COL32_A_MASK) == 0)
5132 return;
5133
5134 ImGuiViewportP* viewport = window->Viewport;
5135 ImRect viewport_rect = viewport->GetMainRect();
5136
5137 // Draw behind window by moving the draw command at the FRONT of the draw list
5138 {
5139 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5140 // 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.
5141 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5142 draw_list->ChannelsMerge();
5143 if (draw_list->CmdBuffer.Size == 0)
5144 draw_list->AddDrawCmd();
5145 draw_list->PushClipRect(clip_rect_min: viewport_rect.Min - ImVec2(1, 1), clip_rect_max: viewport_rect.Max + ImVec2(1, 1), intersect_with_current_clip_rect: false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5146 draw_list->AddRectFilled(p_min: viewport_rect.Min, p_max: viewport_rect.Max, col);
5147 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5148 IM_ASSERT(cmd.ElemCount == 6);
5149 draw_list->CmdBuffer.pop_back();
5150 draw_list->CmdBuffer.push_front(v: cmd);
5151 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5152 draw_list->PopClipRect();
5153 }
5154
5155 // Draw over sibling docking nodes in a same docking tree
5156 if (window->RootWindow->DockIsActive)
5157 {
5158 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window: window->RootWindowDockTree)->DrawList;
5159 draw_list->ChannelsMerge();
5160 if (draw_list->CmdBuffer.Size == 0)
5161 draw_list->AddDrawCmd();
5162 draw_list->PushClipRect(clip_rect_min: viewport_rect.Min, clip_rect_max: viewport_rect.Max, intersect_with_current_clip_rect: false);
5163 RenderRectFilledWithHole(draw_list, outer: window->RootWindowDockTree->Rect(), inner: window->RootWindow->Rect(), col, rounding: 0.0f);// window->RootWindowDockTree->WindowRounding);
5164 draw_list->PopClipRect();
5165 }
5166}
5167
5168ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5169{
5170 ImGuiContext& g = *GImGui;
5171 ImGuiWindow* bottom_most_visible_window = parent_window;
5172 for (int i = FindWindowDisplayIndex(window: parent_window); i >= 0; i--)
5173 {
5174 ImGuiWindow* window = g.Windows[i];
5175 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5176 continue;
5177 if (!IsWindowWithinBeginStackOf(window, potential_parent: parent_window))
5178 break;
5179 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(window: parent_window))
5180 bottom_most_visible_window = window;
5181 }
5182 return bottom_most_visible_window;
5183}
5184
5185// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5186// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5187static void ImGui::RenderDimmedBackgrounds()
5188{
5189 ImGuiContext& g = *GImGui;
5190 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5191 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5192 return;
5193 const bool dim_bg_for_modal = (modal_window != NULL);
5194 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5195 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5196 return;
5197
5198 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5199 if (dim_bg_for_modal)
5200 {
5201 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5202 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(parent_window: modal_window);
5203 RenderDimmedBackgroundBehindWindow(window: dim_behind_window, col: GetColorU32(col: modal_window->DC.ModalDimBgColor, alpha_mul: g.DimBgRatio));
5204 viewports_already_dimmed[0] = modal_window->Viewport;
5205 }
5206 else if (dim_bg_for_window_list)
5207 {
5208 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5209 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingTargetAnim, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
5210 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5211 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingListWindow, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
5212 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5213 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5214
5215 // Draw border around CTRL+Tab target window
5216 ImGuiWindow* window = g.NavWindowingTargetAnim;
5217 ImGuiViewport* viewport = window->Viewport;
5218 float distance = g.FontSize;
5219 ImRect bb = window->Rect();
5220 bb.Expand(amount: distance);
5221 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5222 bb.Expand(amount: -distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5223 window->DrawList->ChannelsMerge();
5224 if (window->DrawList->CmdBuffer.Size == 0)
5225 window->DrawList->AddDrawCmd();
5226 window->DrawList->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size);
5227 window->DrawList->AddRect(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_NavWindowingHighlight, alpha_mul: g.NavWindowingHighlightAlpha), rounding: window->WindowRounding, flags: 0, thickness: 3.0f);
5228 window->DrawList->PopClipRect();
5229 }
5230
5231 // Draw dimming background on _other_ viewports than the ones our windows are in
5232 for (ImGuiViewportP* viewport : g.Viewports)
5233 {
5234 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5235 continue;
5236 if (modal_window && viewport->Window && IsWindowAbove(potential_above: viewport->Window, potential_below: modal_window))
5237 continue;
5238 ImDrawList* draw_list = GetForegroundDrawList(viewport);
5239 const ImU32 dim_bg_col = GetColorU32(idx: dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio);
5240 draw_list->AddRectFilled(p_min: viewport->Pos, p_max: viewport->Pos + viewport->Size, col: dim_bg_col);
5241 }
5242}
5243
5244// 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.
5245void ImGui::EndFrame()
5246{
5247 ImGuiContext& g = *GImGui;
5248 IM_ASSERT(g.Initialized);
5249
5250 // Don't process EndFrame() multiple times.
5251 if (g.FrameCountEnded == g.FrameCount)
5252 return;
5253 IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5254
5255 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePre);
5256
5257 ErrorCheckEndFrameSanityChecks();
5258
5259 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5260 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5261 if (g.IO.SetPlatformImeDataFn && memcmp(s1: ime_data, s2: &g.PlatformImeDataPrev, n: sizeof(ImGuiPlatformImeData)) != 0)
5262 {
5263 ImGuiViewport* viewport = FindViewportByID(id: g.PlatformImeViewport);
5264 IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5265 if (viewport == NULL)
5266 viewport = GetMainViewport();
5267 g.IO.SetPlatformImeDataFn(viewport, ime_data);
5268 }
5269
5270 // Hide implicit/fallback "Debug" window if it hasn't been used
5271 g.WithinFrameScopeWithImplicitWindow = false;
5272 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5273 g.CurrentWindow->Active = false;
5274 End();
5275
5276 // Update navigation: CTRL+Tab, wrap-around requests
5277 NavEndFrame();
5278
5279 // Update docking
5280 DockContextEndFrame(ctx: &g);
5281
5282 SetCurrentViewport(NULL, NULL);
5283
5284 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5285 if (g.DragDropActive)
5286 {
5287 bool is_delivered = g.DragDropPayload.Delivery;
5288 bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(button: g.DragDropMouseButton));
5289 if (is_delivered || is_elapsed)
5290 ClearDragDrop();
5291 }
5292
5293 // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5294 if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5295 {
5296 g.DragDropWithinSource = true;
5297 SetTooltip("...");
5298 g.DragDropWithinSource = false;
5299 }
5300
5301 // End frame
5302 g.WithinFrameScope = false;
5303 g.FrameCountEnded = g.FrameCount;
5304
5305 // Initiate moving window + handle left-click and right-click focus
5306 UpdateMouseMovingWindowEndFrame();
5307
5308 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5309 UpdateViewportsEndFrame();
5310
5311 // Sort the window list so that all child windows are after their parent
5312 // We cannot do that on FocusWindow() because children may not exist yet
5313 g.WindowsTempSortBuffer.resize(new_size: 0);
5314 g.WindowsTempSortBuffer.reserve(new_capacity: g.Windows.Size);
5315 for (ImGuiWindow* window : g.Windows)
5316 {
5317 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
5318 continue;
5319 AddWindowToSortBuffer(out_sorted_windows: &g.WindowsTempSortBuffer, window);
5320 }
5321
5322 // 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.
5323 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5324 g.Windows.swap(rhs&: g.WindowsTempSortBuffer);
5325 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5326
5327 // Unlock font atlas
5328 g.IO.Fonts->Locked = false;
5329
5330 // Clear Input data for next frame
5331 g.IO.MousePosPrev = g.IO.MousePos;
5332 g.IO.AppFocusLost = false;
5333 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5334 g.IO.InputQueueCharacters.resize(new_size: 0);
5335
5336 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePost);
5337}
5338
5339// Prepare the data for rendering so you can call GetDrawData()
5340// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5341// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5342void ImGui::Render()
5343{
5344 ImGuiContext& g = *GImGui;
5345 IM_ASSERT(g.Initialized);
5346
5347 if (g.FrameCountEnded != g.FrameCount)
5348 EndFrame();
5349 if (g.FrameCountRendered == g.FrameCount)
5350 return;
5351 g.FrameCountRendered = g.FrameCount;
5352
5353 g.IO.MetricsRenderWindows = 0;
5354 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPre);
5355
5356 // Add background ImDrawList (for each active viewport)
5357 for (ImGuiViewportP* viewport : g.Viewports)
5358 {
5359 InitViewportDrawData(viewport);
5360 if (viewport->BgFgDrawLists[0] != NULL)
5361 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetBackgroundDrawList(viewport));
5362 }
5363
5364 // Draw modal/window whitening backgrounds
5365 RenderDimmedBackgrounds();
5366
5367 // Add ImDrawList to render
5368 ImGuiWindow* windows_to_render_top_most[2];
5369 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5370 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5371 for (ImGuiWindow* window : g.Windows)
5372 {
5373 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5374 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5375 AddRootWindowToDrawData(window);
5376 }
5377 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5378 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(window: windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5379 AddRootWindowToDrawData(window: windows_to_render_top_most[n]);
5380
5381 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5382 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5383 RenderMouseCursor(base_pos: g.IO.MousePos, base_scale: g.Style.MouseCursorScale, mouse_cursor: g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5384
5385 // Setup ImDrawData structures for end-user
5386 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5387 for (ImGuiViewportP* viewport : g.Viewports)
5388 {
5389 FlattenDrawDataIntoSingleLayer(builder: &viewport->DrawDataBuilder);
5390
5391 // Add foreground ImDrawList (for each active viewport)
5392 if (viewport->BgFgDrawLists[1] != NULL)
5393 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetForegroundDrawList(viewport));
5394
5395 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5396 ImDrawData* draw_data = &viewport->DrawDataP;
5397 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5398 for (ImDrawList* draw_list : draw_data->CmdLists)
5399 draw_list->_PopUnusedDrawCmd();
5400
5401 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5402 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5403 }
5404
5405 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPost);
5406}
5407
5408// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5409// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5410ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5411{
5412 ImGuiContext& g = *GImGui;
5413
5414 const char* text_display_end;
5415 if (hide_text_after_double_hash)
5416 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
5417 else
5418 text_display_end = text_end;
5419
5420 ImFont* font = g.Font;
5421 const float font_size = g.FontSize;
5422 if (text == text_display_end)
5423 return ImVec2(0.0f, font_size);
5424 ImVec2 text_size = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width, text_begin: text, text_end: text_display_end, NULL);
5425
5426 // Round
5427 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5428 // FIXME: Investigate using ceilf or e.g.
5429 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5430 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5431 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5432
5433 return text_size;
5434}
5435
5436// Find window given position, search front-to-back
5437// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5438// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5439// called, aka before the next Begin(). Moving window isn't affected.
5440static void FindHoveredWindow()
5441{
5442 ImGuiContext& g = *GImGui;
5443
5444 // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5445 ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5446 if (g.MovingWindow)
5447 g.MovingWindow->Viewport = g.MouseViewport;
5448
5449 ImGuiWindow* hovered_window = NULL;
5450 ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5451 if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5452 hovered_window = g.MovingWindow;
5453
5454 ImVec2 padding_regular = g.Style.TouchExtraPadding;
5455 ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5456 for (int i = g.Windows.Size - 1; i >= 0; i--)
5457 {
5458 ImGuiWindow* window = g.Windows[i];
5459 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5460 if (!window->Active || window->Hidden)
5461 continue;
5462 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5463 continue;
5464 IM_ASSERT(window->Viewport);
5465 if (window->Viewport != g.MouseViewport)
5466 continue;
5467
5468 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5469 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5470 if (!window->OuterRectClipped.ContainsWithPad(p: g.IO.MousePos, pad: hit_padding))
5471 continue;
5472
5473 // Support for one rectangular hole in any given window
5474 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5475 if (window->HitTestHoleSize.x != 0)
5476 {
5477 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5478 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5479 if (ImRect(hole_pos, hole_pos + hole_size).Contains(p: g.IO.MousePos))
5480 continue;
5481 }
5482
5483 if (hovered_window == NULL)
5484 hovered_window = window;
5485 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5486 if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5487 hovered_window_ignoring_moving_window = window;
5488 if (hovered_window && hovered_window_ignoring_moving_window)
5489 break;
5490 }
5491
5492 g.HoveredWindow = hovered_window;
5493 g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5494
5495 if (g.MovingWindow)
5496 g.MovingWindow->Viewport = moving_window_viewport;
5497}
5498
5499bool ImGui::IsItemActive()
5500{
5501 ImGuiContext& g = *GImGui;
5502 if (g.ActiveId)
5503 return g.ActiveId == g.LastItemData.ID;
5504 return false;
5505}
5506
5507bool ImGui::IsItemActivated()
5508{
5509 ImGuiContext& g = *GImGui;
5510 if (g.ActiveId)
5511 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5512 return true;
5513 return false;
5514}
5515
5516bool ImGui::IsItemDeactivated()
5517{
5518 ImGuiContext& g = *GImGui;
5519 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5520 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5521 return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5522}
5523
5524bool ImGui::IsItemDeactivatedAfterEdit()
5525{
5526 ImGuiContext& g = *GImGui;
5527 return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5528}
5529
5530// == GetItemID() == GetFocusID()
5531bool ImGui::IsItemFocused()
5532{
5533 ImGuiContext& g = *GImGui;
5534 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5535 return false;
5536
5537 // Special handling for the dummy item after Begin() which represent the title bar or tab.
5538 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5539 ImGuiWindow* window = g.CurrentWindow;
5540 if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5541 return false;
5542
5543 return true;
5544}
5545
5546// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5547// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5548bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5549{
5550 return IsMouseClicked(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_None);
5551}
5552
5553bool ImGui::IsItemToggledOpen()
5554{
5555 ImGuiContext& g = *GImGui;
5556 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5557}
5558
5559bool ImGui::IsItemToggledSelection()
5560{
5561 ImGuiContext& g = *GImGui;
5562 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5563}
5564
5565// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5566// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5567// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5568bool ImGui::IsAnyItemHovered()
5569{
5570 ImGuiContext& g = *GImGui;
5571 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5572}
5573
5574bool ImGui::IsAnyItemActive()
5575{
5576 ImGuiContext& g = *GImGui;
5577 return g.ActiveId != 0;
5578}
5579
5580bool ImGui::IsAnyItemFocused()
5581{
5582 ImGuiContext& g = *GImGui;
5583 return g.NavId != 0 && !g.NavDisableHighlight;
5584}
5585
5586bool ImGui::IsItemVisible()
5587{
5588 ImGuiContext& g = *GImGui;
5589 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5590}
5591
5592bool ImGui::IsItemEdited()
5593{
5594 ImGuiContext& g = *GImGui;
5595 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5596}
5597
5598// Allow next item to be overlapped by subsequent items.
5599// This works by requiring HoveredId to match for two subsequent frames,
5600// so if a following items overwrite it our interactions will naturally be disabled.
5601void ImGui::SetNextItemAllowOverlap()
5602{
5603 ImGuiContext& g = *GImGui;
5604 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5605}
5606
5607#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5608// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5609// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5610void ImGui::SetItemAllowOverlap()
5611{
5612 ImGuiContext& g = *GImGui;
5613 ImGuiID id = g.LastItemData.ID;
5614 if (g.HoveredId == id)
5615 g.HoveredIdAllowOverlap = true;
5616 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5617 g.ActiveIdAllowOverlap = true;
5618}
5619#endif
5620
5621// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5622void ImGui::SetActiveIdUsingAllKeyboardKeys()
5623{
5624 ImGuiContext& g = *GImGui;
5625 IM_ASSERT(g.ActiveId != 0);
5626 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5627 g.ActiveIdUsingAllKeyboardKeys = true;
5628 NavMoveRequestCancel();
5629}
5630
5631ImGuiID ImGui::GetItemID()
5632{
5633 ImGuiContext& g = *GImGui;
5634 return g.LastItemData.ID;
5635}
5636
5637ImVec2 ImGui::GetItemRectMin()
5638{
5639 ImGuiContext& g = *GImGui;
5640 return g.LastItemData.Rect.Min;
5641}
5642
5643ImVec2 ImGui::GetItemRectMax()
5644{
5645 ImGuiContext& g = *GImGui;
5646 return g.LastItemData.Rect.Max;
5647}
5648
5649ImVec2 ImGui::GetItemRectSize()
5650{
5651 ImGuiContext& g = *GImGui;
5652 return g.LastItemData.Rect.GetSize();
5653}
5654
5655// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5656// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5657bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5658{
5659 ImGuiID id = GetCurrentWindow()->GetID(str: str_id);
5660 return BeginChildEx(name: str_id, id, size_arg, child_flags, window_flags);
5661}
5662
5663bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5664{
5665 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5666}
5667
5668bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5669{
5670 ImGuiContext& g = *GImGui;
5671 ImGuiWindow* parent_window = g.CurrentWindow;
5672 IM_ASSERT(id != 0);
5673
5674 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5675 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle;
5676 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5677 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5678 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5679 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5680 {
5681 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5682 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5683 }
5684#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5685 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5686 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5687#endif
5688 if (child_flags & ImGuiChildFlags_AutoResizeX)
5689 child_flags &= ~ImGuiChildFlags_ResizeX;
5690 if (child_flags & ImGuiChildFlags_AutoResizeY)
5691 child_flags &= ~ImGuiChildFlags_ResizeY;
5692
5693 // Set window flags
5694 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5695 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5696 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5697 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5698 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5699 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5700
5701 // Special framed style
5702 if (child_flags & ImGuiChildFlags_FrameStyle)
5703 {
5704 PushStyleColor(idx: ImGuiCol_ChildBg, col: g.Style.Colors[ImGuiCol_FrameBg]);
5705 PushStyleVar(idx: ImGuiStyleVar_ChildRounding, val: g.Style.FrameRounding);
5706 PushStyleVar(idx: ImGuiStyleVar_ChildBorderSize, val: g.Style.FrameBorderSize);
5707 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.FramePadding);
5708 child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5709 window_flags |= ImGuiWindowFlags_NoMove;
5710 }
5711
5712 // Forward child flags
5713 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5714 g.NextWindowData.ChildFlags = child_flags;
5715
5716 // Forward size
5717 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5718 // (the alternative would to store conditional flags per axis, which is possible but more code)
5719 const ImVec2 size_avail = GetContentRegionAvail();
5720 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5721 const ImVec2 size = CalcItemSize(size: size_arg, default_w: size_default.x, default_h: size_default.y);
5722 SetNextWindowSize(size);
5723
5724 // 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.
5725 // 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.
5726 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5727 const char* temp_window_name;
5728 /*if (name && parent_window->IDStack.back() == parent_window->ID)
5729 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5730 else*/
5731 if (name)
5732 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%s_%08X", parent_window->Name, name, id);
5733 else
5734 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%08X", parent_window->Name, id);
5735
5736 // Set style
5737 const float backup_border_size = g.Style.ChildBorderSize;
5738 if ((child_flags & ImGuiChildFlags_Border) == 0)
5739 g.Style.ChildBorderSize = 0.0f;
5740
5741 // Begin into window
5742 const bool ret = Begin(name: temp_window_name, NULL, flags: window_flags);
5743
5744 // Restore style
5745 g.Style.ChildBorderSize = backup_border_size;
5746 if (child_flags & ImGuiChildFlags_FrameStyle)
5747 {
5748 PopStyleVar(count: 3);
5749 PopStyleColor();
5750 }
5751
5752 ImGuiWindow* child_window = g.CurrentWindow;
5753 child_window->ChildId = id;
5754
5755 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5756 // While this is not really documented/defined, it seems that the expected thing to do.
5757 if (child_window->BeginCount == 1)
5758 parent_window->DC.CursorPos = child_window->Pos;
5759
5760 // Process navigation-in immediately so NavInit can run on first frame
5761 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5762 const ImGuiID temp_id_for_activation = ImHashStr(data_p: "##Child", data_size: 0, seed: id);
5763 if (g.ActiveId == temp_id_for_activation)
5764 ClearActiveID();
5765 if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5766 {
5767 FocusWindow(window: child_window);
5768 NavInitWindow(window: child_window, force_reinit: false);
5769 SetActiveID(id: temp_id_for_activation, window: child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5770 g.ActiveIdSource = g.NavInputSource;
5771 }
5772 return ret;
5773}
5774
5775void ImGui::EndChild()
5776{
5777 ImGuiContext& g = *GImGui;
5778 ImGuiWindow* child_window = g.CurrentWindow;
5779
5780 IM_ASSERT(g.WithinEndChild == false);
5781 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
5782
5783 g.WithinEndChild = true;
5784 ImVec2 child_size = child_window->Size;
5785 End();
5786 if (child_window->BeginCount == 1)
5787 {
5788 ImGuiWindow* parent_window = g.CurrentWindow;
5789 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5790 ItemSize(size: child_size);
5791 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5792 {
5793 ItemAdd(bb, id: child_window->ChildId);
5794 RenderNavHighlight(bb, id: child_window->ChildId);
5795
5796 // 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)
5797 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5798 RenderNavHighlight(bb: ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), id: g.NavId, flags: ImGuiNavHighlightFlags_Compact);
5799 }
5800 else
5801 {
5802 // Not navigable into
5803 ItemAdd(bb, id: 0);
5804
5805 // But when flattened we directly reach items, adjust active layer mask accordingly
5806 if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5807 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5808 }
5809 if (g.HoveredWindow == child_window)
5810 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5811 }
5812 g.WithinEndChild = false;
5813 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5814}
5815
5816static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5817{
5818 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
5819 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
5820 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5821 window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
5822}
5823
5824ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5825{
5826 ImGuiContext& g = *GImGui;
5827 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(key: id);
5828}
5829
5830ImGuiWindow* ImGui::FindWindowByName(const char* name)
5831{
5832 ImGuiID id = ImHashStr(data_p: name);
5833 return FindWindowByID(id);
5834}
5835
5836static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5837{
5838 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5839 window->ViewportPos = main_viewport->Pos;
5840 if (settings->ViewportId)
5841 {
5842 window->ViewportId = settings->ViewportId;
5843 window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5844 }
5845 window->Pos = ImTrunc(v: ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5846 if (settings->Size.x > 0 && settings->Size.y > 0)
5847 window->Size = window->SizeFull = ImTrunc(v: ImVec2(settings->Size.x, settings->Size.y));
5848 window->Collapsed = settings->Collapsed;
5849 window->DockId = settings->DockId;
5850 window->DockOrder = settings->DockOrder;
5851}
5852
5853static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5854{
5855 ImGuiContext& g = *GImGui;
5856
5857 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5858 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5859 if ((just_created || child_flag_changed) && !new_is_explicit_child)
5860 {
5861 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5862 g.WindowsFocusOrder.push_back(v: window);
5863 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5864 }
5865 else if (!just_created && child_flag_changed && new_is_explicit_child)
5866 {
5867 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5868 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5869 g.WindowsFocusOrder[n]->FocusOrder--;
5870 g.WindowsFocusOrder.erase(it: g.WindowsFocusOrder.Data + window->FocusOrder);
5871 window->FocusOrder = -1;
5872 }
5873 window->IsExplicitChild = new_is_explicit_child;
5874}
5875
5876static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5877{
5878 // Initial window state with e.g. default/arbitrary window position
5879 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5880 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5881 window->Pos = main_viewport->Pos + ImVec2(60, 60);
5882 window->Size = window->SizeFull = ImVec2(0, 0);
5883 window->ViewportPos = main_viewport->Pos;
5884 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5885
5886 if (settings != NULL)
5887 {
5888 SetWindowConditionAllowFlags(window, flags: ImGuiCond_FirstUseEver, enabled: false);
5889 ApplyWindowSettings(window, settings);
5890 }
5891 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5892
5893 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5894 {
5895 window->AutoFitFramesX = window->AutoFitFramesY = 2;
5896 window->AutoFitOnlyGrows = false;
5897 }
5898 else
5899 {
5900 if (window->Size.x <= 0.0f)
5901 window->AutoFitFramesX = 2;
5902 if (window->Size.y <= 0.0f)
5903 window->AutoFitFramesY = 2;
5904 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5905 }
5906}
5907
5908static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5909{
5910 // Create window the first time
5911 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5912 ImGuiContext& g = *GImGui;
5913 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5914 window->Flags = flags;
5915 g.WindowsById.SetVoidPtr(key: window->ID, val: window);
5916
5917 ImGuiWindowSettings* settings = NULL;
5918 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5919 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5920 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
5921
5922 InitOrLoadWindowSettings(window, settings);
5923
5924 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5925 g.Windows.push_front(v: window); // Quite slow but rare and only once
5926 else
5927 g.Windows.push_back(v: window);
5928
5929 return window;
5930}
5931
5932static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5933{
5934 return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5935}
5936
5937static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5938{
5939 return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5940}
5941
5942static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5943{
5944 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5945 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
5946 // Perhaps should tend further a neater test for this.
5947 ImGuiContext& g = *GImGui;
5948 ImVec2 size_min;
5949 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
5950 {
5951 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5952 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5953 }
5954 else
5955 {
5956 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
5957 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
5958 }
5959
5960 // Reduce artifacts with very small windows
5961 ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5962 size_min.y = ImMax(lhs: size_min.y, rhs: window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(lhs: 0.0f, rhs: g.Style.WindowRounding - 1.0f));
5963 return size_min;
5964}
5965
5966static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5967{
5968 ImGuiContext& g = *GImGui;
5969 ImVec2 new_size = size_desired;
5970 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5971 {
5972 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
5973 ImRect cr = g.NextWindowData.SizeConstraintRect;
5974 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(v: new_size.x, mn: cr.Min.x, mx: cr.Max.x) : window->SizeFull.x;
5975 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(v: new_size.y, mn: cr.Min.y, mx: cr.Max.y) : window->SizeFull.y;
5976 if (g.NextWindowData.SizeCallback)
5977 {
5978 ImGuiSizeCallbackData data;
5979 data.UserData = g.NextWindowData.SizeCallbackUserData;
5980 data.Pos = window->Pos;
5981 data.CurrentSize = window->SizeFull;
5982 data.DesiredSize = new_size;
5983 g.NextWindowData.SizeCallback(&data);
5984 new_size = data.DesiredSize;
5985 }
5986 new_size.x = IM_TRUNC(new_size.x);
5987 new_size.y = IM_TRUNC(new_size.y);
5988 }
5989
5990 // Minimum size
5991 ImVec2 size_min = CalcWindowMinSize(window);
5992 return ImMax(lhs: new_size, rhs: size_min);
5993}
5994
5995static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5996{
5997 bool preserve_old_content_sizes = false;
5998 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5999 preserve_old_content_sizes = true;
6000 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6001 preserve_old_content_sizes = true;
6002 if (preserve_old_content_sizes)
6003 {
6004 *content_size_current = window->ContentSize;
6005 *content_size_ideal = window->ContentSizeIdeal;
6006 return;
6007 }
6008
6009 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6010 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6011 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6012 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6013}
6014
6015static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6016{
6017 ImGuiContext& g = *GImGui;
6018 ImGuiStyle& style = g.Style;
6019 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6020 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6021 ImVec2 size_pad = window->WindowPadding * 2.0f;
6022 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6023 if (window->Flags & ImGuiWindowFlags_Tooltip)
6024 {
6025 // Tooltip always resize
6026 return size_desired;
6027 }
6028 else
6029 {
6030 // Maximum window size is determined by the viewport size or monitor size
6031 ImVec2 size_min = CalcWindowMinSize(window);
6032 ImVec2 size_max = (window->ViewportOwned || ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6033 const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6034 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0)
6035 size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6036 ImVec2 size_auto_fit = ImClamp(v: size_desired, mn: size_min, mx: ImMax(lhs: size_min, rhs: size_max));
6037
6038 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6039 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6040 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6041 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);
6042 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);
6043 if (will_have_scrollbar_x)
6044 size_auto_fit.y += style.ScrollbarSize;
6045 if (will_have_scrollbar_y)
6046 size_auto_fit.x += style.ScrollbarSize;
6047 return size_auto_fit;
6048 }
6049}
6050
6051ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6052{
6053 ImVec2 size_contents_current;
6054 ImVec2 size_contents_ideal;
6055 CalcWindowContentSizes(window, content_size_current: &size_contents_current, content_size_ideal: &size_contents_ideal);
6056 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: size_contents_ideal);
6057 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6058 return size_final;
6059}
6060
6061static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6062{
6063 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6064 return ImGuiCol_PopupBg;
6065 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6066 return ImGuiCol_ChildBg;
6067 return ImGuiCol_WindowBg;
6068}
6069
6070static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6071{
6072 ImVec2 pos_min = ImLerp(a: corner_target, b: window->Pos, t: corner_norm); // Expected window upper-left
6073 ImVec2 pos_max = ImLerp(a: window->Pos + window->Size, b: corner_target, t: corner_norm); // Expected window lower-right
6074 ImVec2 size_expected = pos_max - pos_min;
6075 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_desired: size_expected);
6076 *out_pos = pos_min;
6077 if (corner_norm.x == 0.0f)
6078 out_pos->x -= (size_constrained.x - size_expected.x);
6079 if (corner_norm.y == 0.0f)
6080 out_pos->y -= (size_constrained.y - size_expected.y);
6081 *out_size = size_constrained;
6082}
6083
6084// Data for resizing from resize grip / corner
6085struct ImGuiResizeGripDef
6086{
6087 ImVec2 CornerPosN;
6088 ImVec2 InnerDir;
6089 int AngleMin12, AngleMax12;
6090};
6091static const ImGuiResizeGripDef resize_grip_def[4] =
6092{
6093 { .CornerPosN: ImVec2(1, 1), .InnerDir: ImVec2(-1, -1), .AngleMin12: 0, .AngleMax12: 3 }, // Lower-right
6094 { .CornerPosN: ImVec2(0, 1), .InnerDir: ImVec2(+1, -1), .AngleMin12: 3, .AngleMax12: 6 }, // Lower-left
6095 { .CornerPosN: ImVec2(0, 0), .InnerDir: ImVec2(+1, +1), .AngleMin12: 6, .AngleMax12: 9 }, // Upper-left (Unused)
6096 { .CornerPosN: ImVec2(1, 0), .InnerDir: ImVec2(-1, +1), .AngleMin12: 9, .AngleMax12: 12 } // Upper-right (Unused)
6097};
6098
6099// Data for resizing from borders
6100struct ImGuiResizeBorderDef
6101{
6102 ImVec2 InnerDir; // Normal toward inside
6103 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6104 float OuterAngle; // Angle toward outside
6105};
6106static const ImGuiResizeBorderDef resize_border_def[4] =
6107{
6108 { .InnerDir: ImVec2(+1, 0), .SegmentN1: ImVec2(0, 1), .SegmentN2: ImVec2(0, 0), IM_PI * 1.00f }, // Left
6109 { .InnerDir: ImVec2(-1, 0), .SegmentN1: ImVec2(1, 0), .SegmentN2: ImVec2(1, 1), IM_PI * 0.00f }, // Right
6110 { .InnerDir: ImVec2(0, +1), .SegmentN1: ImVec2(0, 0), .SegmentN2: ImVec2(1, 0), IM_PI * 1.50f }, // Up
6111 { .InnerDir: ImVec2(0, -1), .SegmentN1: ImVec2(1, 1), .SegmentN2: ImVec2(0, 1), IM_PI * 0.50f } // Down
6112};
6113
6114static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6115{
6116 ImRect rect = window->Rect();
6117 if (thickness == 0.0f)
6118 rect.Max -= ImVec2(1, 1);
6119 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); }
6120 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); }
6121 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); }
6122 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); }
6123 IM_ASSERT(0);
6124 return ImRect();
6125}
6126
6127// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6128ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6129{
6130 IM_ASSERT(n >= 0 && n < 4);
6131 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6132 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
6133 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
6134 return id;
6135}
6136
6137// Borders (Left, Right, Up, Down)
6138ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6139{
6140 IM_ASSERT(dir >= 0 && dir < 4);
6141 int n = (int)dir + 4;
6142 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6143 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
6144 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
6145 return id;
6146}
6147
6148// Handle resize for: Resize Grips, Borders, Gamepad
6149// Return true when using auto-fit (double-click on resize grip)
6150static 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)
6151{
6152 ImGuiContext& g = *GImGui;
6153 ImGuiWindowFlags flags = window->Flags;
6154
6155 if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6156 return false;
6157 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6158 return false;
6159
6160 int ret_auto_fit_mask = 0x00;
6161 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6162 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6163 const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6164
6165 ImRect clamp_rect = visibility_rect;
6166 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6167 if (window_move_from_title_bar)
6168 clamp_rect.Min.y -= window->TitleBarHeight();
6169
6170 ImVec2 pos_target(FLT_MAX, FLT_MAX);
6171 ImVec2 size_target(FLT_MAX, FLT_MAX);
6172
6173 // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6174 // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6175 // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6176 // - 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.
6177 // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6178 // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6179 const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6180 if (clip_with_viewport_rect)
6181 window->ClipRect = window->Viewport->GetMainRect();
6182
6183 // Resize grips and borders are on layer 1
6184 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6185
6186 // Manual resize grips
6187 PushID(str_id: "#RESIZE");
6188 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6189 {
6190 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6191 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: def.CornerPosN);
6192
6193 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6194 bool hovered, held;
6195 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6196 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(a&: resize_rect.Min.x, b&: resize_rect.Max.x);
6197 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(a&: resize_rect.Min.y, b&: resize_rect.Max.y);
6198 ImGuiID resize_grip_id = window->GetID(n: resize_grip_n); // == GetWindowResizeCornerID()
6199 ItemAdd(bb: resize_rect, id: resize_grip_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
6200 ButtonBehavior(bb: resize_rect, id: resize_grip_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6201 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6202 if (hovered || held)
6203 g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6204
6205 if (held && g.IO.MouseDoubleClicked[0])
6206 {
6207 // Auto-fit when double-clicking
6208 size_target = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6209 ret_auto_fit_mask = 0x03; // Both axises
6210 ClearActiveID();
6211 }
6212 else if (held)
6213 {
6214 // Resize from any of the four corners
6215 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6216 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);
6217 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);
6218 ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(a: def.InnerDir * grip_hover_outer_size, b: def.InnerDir * -grip_hover_inner_size, t: def.CornerPosN); // Corner of the window corresponding to our corner grip
6219 corner_target = ImClamp(v: corner_target, mn: clamp_min, mx: clamp_max);
6220 CalcResizePosSizeFromAnyCorner(window, corner_target, corner_norm: def.CornerPosN, out_pos: &pos_target, out_size: &size_target);
6221 }
6222
6223 // Only lower-left grip is visible before hovering/activating
6224 if (resize_grip_n == 0 || held || hovered)
6225 resize_grip_col[resize_grip_n] = GetColorU32(idx: held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6226 }
6227
6228 int resize_border_mask = 0x00;
6229 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6230 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6231 else
6232 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6233 for (int border_n = 0; border_n < 4; border_n++)
6234 {
6235 if ((resize_border_mask & (1 << border_n)) == 0)
6236 continue;
6237 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6238 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6239
6240 bool hovered, held;
6241 ImRect border_rect = GetResizeBorderRect(window, border_n, perp_padding: grip_hover_inner_size, thickness: WINDOWS_HOVER_PADDING);
6242 ImGuiID border_id = window->GetID(n: border_n + 4); // == GetWindowResizeBorderID()
6243 ItemAdd(bb: border_rect, id: border_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
6244 ButtonBehavior(bb: border_rect, id: border_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6245 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6246 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6247 hovered = false;
6248 if (hovered || held)
6249 g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6250 if (held && g.IO.MouseDoubleClicked[0])
6251 {
6252 // Double-clicking bottom or right border auto-fit on this axis
6253 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6254 if (border_n == 1 || border_n == 3) // Right and bottom border
6255 {
6256 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit)[axis];
6257 ret_auto_fit_mask |= (1 << axis);
6258 hovered = held = false; // So border doesn't show highlighted at new position
6259 }
6260 ClearActiveID();
6261 }
6262 else if (held)
6263 {
6264 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6265 // 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.
6266 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6267 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, potential_parent: g.WheelingWindow, popup_hierarchy: false, dock_hierarchy: true));
6268 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6269 {
6270 g.WindowResizeBorderExpectedRect = border_rect;
6271 g.WindowResizeRelativeMode = false;
6272 }
6273 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(s1: &g.WindowResizeBorderExpectedRect, s2: &border_rect, n: sizeof(ImRect)) != 0)
6274 g.WindowResizeRelativeMode = true;
6275
6276 const ImVec2 border_curr = (window->Pos + ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2) * window->Size);
6277 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6278 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6279
6280 // Use absolute mode position
6281 ImVec2 border_target = window->Pos;
6282 border_target[axis] = border_target_abs_mode_for_axis;
6283
6284 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6285 bool ignore_resize = false;
6286 if (g.WindowResizeRelativeMode)
6287 {
6288 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6289 border_target[axis] = border_target_rel_mode_for_axis;
6290 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))
6291 ignore_resize = true;
6292 }
6293
6294 // Clamp, apply
6295 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);
6296 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6297 border_target = ImClamp(v: border_target, mn: clamp_min, mx: clamp_max);
6298 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6299 {
6300 ImGuiWindowFlags parent_flags = window->ParentWindow->Flags;
6301 ImRect border_limit_rect = window->ParentWindow->InnerRect;
6302 border_limit_rect.Expand(amount: ImVec2(-ImMax(lhs: window->WindowPadding.x, rhs: window->WindowBorderSize), -ImMax(lhs: window->WindowPadding.y, rhs: window->WindowBorderSize)));
6303 if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar))
6304 border_target.x = ImClamp(v: border_target.x, mn: border_limit_rect.Min.x, mx: border_limit_rect.Max.x);
6305 if (parent_flags & ImGuiWindowFlags_NoScrollbar)
6306 border_target.y = ImClamp(v: border_target.y, mn: border_limit_rect.Min.y, mx: border_limit_rect.Max.y);
6307 }
6308 if (!ignore_resize)
6309 CalcResizePosSizeFromAnyCorner(window, corner_target: border_target, corner_norm: ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2), out_pos: &pos_target, out_size: &size_target);
6310 }
6311 if (hovered)
6312 *border_hovered = border_n;
6313 if (held)
6314 *border_held = border_n;
6315 }
6316 PopID();
6317
6318 // Restore nav layer
6319 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6320
6321 // Navigation resize (keyboard/gamepad)
6322 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6323 // Not even sure the callback works here.
6324 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6325 {
6326 ImVec2 nav_resize_dir;
6327 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6328 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
6329 if (g.NavInputSource == ImGuiInputSource_Gamepad)
6330 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadDpadLeft, key_right: ImGuiKey_GamepadDpadRight, key_up: ImGuiKey_GamepadDpadUp, key_down: ImGuiKey_GamepadDpadDown);
6331 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6332 {
6333 const float NAV_RESIZE_SPEED = 600.0f;
6334 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(lhs: g.IO.DisplayFramebufferScale.x, rhs: g.IO.DisplayFramebufferScale.y);
6335 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6336 g.NavWindowingAccumDeltaSize = ImMax(lhs: g.NavWindowingAccumDeltaSize, rhs: clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6337 g.NavWindowingToggleLayer = false;
6338 g.NavDisableMouseHover = true;
6339 resize_grip_col[0] = GetColorU32(idx: ImGuiCol_ResizeGripActive);
6340 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaSize);
6341 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6342 {
6343 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6344 size_target = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull + accum_floored);
6345 g.NavWindowingAccumDeltaSize -= accum_floored;
6346 }
6347 }
6348 }
6349
6350 // Apply back modified position/size to window
6351 const ImVec2 curr_pos = window->Pos;
6352 const ImVec2 curr_size = window->SizeFull;
6353 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6354 window->Size.x = window->SizeFull.x = size_target.x;
6355 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6356 window->Size.y = window->SizeFull.y = size_target.y;
6357 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(f: pos_target.x))
6358 window->Pos.x = ImTrunc(f: pos_target.x);
6359 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(f: pos_target.y))
6360 window->Pos.y = ImTrunc(f: pos_target.y);
6361 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)
6362 MarkIniSettingsDirty(window);
6363
6364 // Recalculate next expected border expected coordinates
6365 if (*border_held != -1)
6366 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_n: *border_held, perp_padding: grip_hover_inner_size, thickness: WINDOWS_HOVER_PADDING);
6367
6368 return ret_auto_fit_mask;
6369}
6370
6371static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6372{
6373 ImGuiContext& g = *GImGui;
6374 ImVec2 size_for_clamping = window->Size;
6375 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6376 size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6377 window->Pos = ImClamp(v: window->Pos, mn: visibility_rect.Min - size_for_clamping, mx: visibility_rect.Max);
6378}
6379
6380static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6381{
6382 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6383 const float rounding = window->WindowRounding;
6384 const ImRect border_r = GetResizeBorderRect(window, border_n, perp_padding: rounding, thickness: 0.0f);
6385 window->DrawList->PathArcTo(center: ImLerp(a: border_r.Min, b: border_r.Max, t: def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, radius: rounding, a_min: def.OuterAngle - IM_PI * 0.25f, a_max: def.OuterAngle);
6386 window->DrawList->PathArcTo(center: ImLerp(a: border_r.Min, b: border_r.Max, t: def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, radius: rounding, a_min: def.OuterAngle, a_max: def.OuterAngle + IM_PI * 0.25f);
6387 window->DrawList->PathStroke(col: border_col, flags: ImDrawFlags_None, thickness: border_size);
6388}
6389
6390static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6391{
6392 ImGuiContext& g = *GImGui;
6393 const float border_size = window->WindowBorderSize;
6394 const ImU32 border_col = GetColorU32(idx: ImGuiCol_Border);
6395 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6396 window->DrawList->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, col: border_col, rounding: window->WindowRounding, flags: 0, thickness: window->WindowBorderSize);
6397 else if (border_size > 0.0f)
6398 {
6399 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6400 RenderWindowOuterSingleBorder(window, border_n: 1, border_col, border_size);
6401 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6402 RenderWindowOuterSingleBorder(window, border_n: 3, border_col, border_size);
6403 }
6404 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6405 {
6406 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6407 const ImU32 border_col_resizing = GetColorU32(idx: (window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6408 RenderWindowOuterSingleBorder(window, border_n, border_col: border_col_resizing, border_size: ImMax(lhs: 2.0f, rhs: window->WindowBorderSize)); // Thicker than usual
6409 }
6410 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6411 {
6412 float y = window->Pos.y + window->TitleBarHeight() - 1;
6413 window->DrawList->AddLine(p1: ImVec2(window->Pos.x + border_size, y), p2: ImVec2(window->Pos.x + window->Size.x - border_size, y), col: border_col, thickness: g.Style.FrameBorderSize);
6414 }
6415}
6416
6417// Draw background and borders
6418// Draw and handle scrollbars
6419void 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)
6420{
6421 ImGuiContext& g = *GImGui;
6422 ImGuiStyle& style = g.Style;
6423 ImGuiWindowFlags flags = window->Flags;
6424
6425 // Ensure that ScrollBar doesn't read last frame's SkipItems
6426 IM_ASSERT(window->BeginCount == 0);
6427 window->SkipItems = false;
6428
6429 // Draw window + handle manual resize
6430 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6431 const float window_rounding = window->WindowRounding;
6432 const float window_border_size = window->WindowBorderSize;
6433 if (window->Collapsed)
6434 {
6435 // Title bar only
6436 const float backup_border_size = style.FrameBorderSize;
6437 g.Style.FrameBorderSize = window->WindowBorderSize;
6438 ImU32 title_bar_col = GetColorU32(idx: (title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6439 if (window->ViewportOwned)
6440 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)
6441 RenderFrame(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, fill_col: title_bar_col, border: true, rounding: window_rounding);
6442 g.Style.FrameBorderSize = backup_border_size;
6443 }
6444 else
6445 {
6446 // Window background
6447 if (!(flags & ImGuiWindowFlags_NoBackground))
6448 {
6449 bool is_docking_transparent_payload = false;
6450 if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6451 if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6452 is_docking_transparent_payload = true;
6453
6454 ImU32 bg_col = GetColorU32(idx: GetWindowBgColorIdx(window));
6455 if (window->ViewportOwned)
6456 {
6457 bg_col |= IM_COL32_A_MASK; // No alpha
6458 if (is_docking_transparent_payload)
6459 window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6460 }
6461 else
6462 {
6463 // Adjust alpha. For docking
6464 bool override_alpha = false;
6465 float alpha = 1.0f;
6466 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6467 {
6468 alpha = g.NextWindowData.BgAlphaVal;
6469 override_alpha = true;
6470 }
6471 if (is_docking_transparent_payload)
6472 {
6473 alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6474 override_alpha = true;
6475 }
6476 if (override_alpha)
6477 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6478 }
6479
6480 // Render, for docked windows and host windows we ensure bg goes before decorations
6481 if (window->DockIsActive)
6482 window->DockNode->LastBgColor = bg_col;
6483 ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6484 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6485 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6486 bg_draw_list->AddRectFilled(p_min: window->Pos + ImVec2(0, window->TitleBarHeight()), p_max: window->Pos + window->Size, col: bg_col, rounding: window_rounding, flags: (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6487 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6488 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6489 }
6490 if (window->DockIsActive)
6491 window->DockNode->IsBgDrawnThisFrame = true;
6492
6493 // Title bar
6494 // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6495 // in order for their pos/size to be matching their undocking state.)
6496 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6497 {
6498 ImU32 title_bar_col = GetColorU32(idx: title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6499 if (window->ViewportOwned)
6500 title_bar_col |= IM_COL32_A_MASK; // No alpha
6501 window->DrawList->AddRectFilled(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, col: title_bar_col, rounding: window_rounding, flags: ImDrawFlags_RoundCornersTop);
6502 }
6503
6504 // Menu bar
6505 if (flags & ImGuiWindowFlags_MenuBar)
6506 {
6507 ImRect menu_bar_rect = window->MenuBarRect();
6508 menu_bar_rect.ClipWith(r: window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6509 window->DrawList->AddRectFilled(p_min: menu_bar_rect.Min + ImVec2(window_border_size, 0), p_max: menu_bar_rect.Max - ImVec2(window_border_size, 0), col: GetColorU32(idx: ImGuiCol_MenuBarBg), rounding: (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, flags: ImDrawFlags_RoundCornersTop);
6510 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6511 window->DrawList->AddLine(p1: menu_bar_rect.GetBL(), p2: menu_bar_rect.GetBR(), col: GetColorU32(idx: ImGuiCol_Border), thickness: style.FrameBorderSize);
6512 }
6513
6514 // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6515 ImGuiDockNode* node = window->DockNode;
6516 if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6517 {
6518 float unhide_sz_draw = ImTrunc(f: g.FontSize * 0.70f);
6519 float unhide_sz_hit = ImTrunc(f: g.FontSize * 0.55f);
6520 ImVec2 p = node->Pos;
6521 ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6522 ImGuiID unhide_id = window->GetID(str: "#UNHIDE");
6523 KeepAliveID(id: unhide_id);
6524 bool hovered, held;
6525 if (ButtonBehavior(bb: r, id: unhide_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren))
6526 node->WantHiddenTabBarToggle = true;
6527 else if (held && IsMouseDragging(button: 0))
6528 StartMouseMovingWindowOrNode(window, node, undock: true); // Undock from tab-bar triangle = same as window/collapse menu button
6529
6530 // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6531 ImU32 col = GetColorU32(idx: ((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6532 window->DrawList->AddTriangleFilled(p1: p, p2: p + ImVec2(unhide_sz_draw, 0.0f), p3: p + ImVec2(0.0f, unhide_sz_draw), col);
6533 }
6534
6535 // Scrollbars
6536 if (window->ScrollbarX)
6537 Scrollbar(axis: ImGuiAxis_X);
6538 if (window->ScrollbarY)
6539 Scrollbar(axis: ImGuiAxis_Y);
6540
6541 // Render resize grips (after their input handling so we don't have a frame of latency)
6542 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6543 {
6544 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6545 {
6546 const ImU32 col = resize_grip_col[resize_grip_n];
6547 if ((col & IM_COL32_A_MASK) == 0)
6548 continue;
6549 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6550 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: grip.CornerPosN);
6551 window->DrawList->PathLineTo(pos: corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6552 window->DrawList->PathLineTo(pos: corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6553 window->DrawList->PathArcToFast(center: ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), radius: window_rounding, a_min_of_12: grip.AngleMin12, a_max_of_12: grip.AngleMax12);
6554 window->DrawList->PathFillConvex(col);
6555 }
6556 }
6557
6558 // Borders (for dock node host they will be rendered over after the tab bar)
6559 if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6560 RenderWindowOuterBorders(window);
6561 }
6562}
6563
6564// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6565// Render title text, collapse button, close button
6566void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6567{
6568 ImGuiContext& g = *GImGui;
6569 ImGuiStyle& style = g.Style;
6570 ImGuiWindowFlags flags = window->Flags;
6571
6572 const bool has_close_button = (p_open != NULL);
6573 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6574
6575 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6576 // 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?
6577 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6578 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6579 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6580
6581 // Layout buttons
6582 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6583 float pad_l = style.FramePadding.x;
6584 float pad_r = style.FramePadding.x;
6585 float button_sz = g.FontSize;
6586 ImVec2 close_button_pos;
6587 ImVec2 collapse_button_pos;
6588 if (has_close_button)
6589 {
6590 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6591 pad_r += button_sz + style.ItemInnerSpacing.x;
6592 }
6593 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6594 {
6595 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6596 pad_r += button_sz + style.ItemInnerSpacing.x;
6597 }
6598 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6599 {
6600 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6601 pad_l += button_sz + style.ItemInnerSpacing.x;
6602 }
6603
6604 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6605 if (has_collapse_button)
6606 if (CollapseButton(id: window->GetID(str: "#COLLAPSE"), pos: collapse_button_pos, NULL))
6607 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6608
6609 // Close button
6610 if (has_close_button)
6611 if (CloseButton(id: window->GetID(str: "#CLOSE"), pos: close_button_pos))
6612 *p_open = false;
6613
6614 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6615 g.CurrentItemFlags = item_flags_backup;
6616
6617 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6618 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6619 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6620 const ImVec2 text_size = CalcTextSize(text: name, NULL, hide_text_after_double_hash: true) + ImVec2(marker_size_x, 0.0f);
6621
6622 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6623 // while uncentered title text will still reach edges correctly.
6624 if (pad_l > style.FramePadding.x)
6625 pad_l += g.Style.ItemInnerSpacing.x;
6626 if (pad_r > style.FramePadding.x)
6627 pad_r += g.Style.ItemInnerSpacing.x;
6628 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6629 {
6630 float centerness = ImSaturate(f: 1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6631 float pad_extend = ImMin(lhs: ImMax(lhs: pad_l, rhs: pad_r), rhs: title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6632 pad_l = ImMax(lhs: pad_l, rhs: pad_extend * centerness);
6633 pad_r = ImMax(lhs: pad_r, rhs: pad_extend * centerness);
6634 }
6635
6636 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);
6637 ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(lhs: layout_r.Max.x + g.Style.ItemInnerSpacing.x, rhs: title_bar_rect.Max.x), layout_r.Max.y);
6638 if (flags & ImGuiWindowFlags_UnsavedDocument)
6639 {
6640 ImVec2 marker_pos;
6641 marker_pos.x = ImClamp(v: layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, mn: layout_r.Min.x, mx: layout_r.Max.x);
6642 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6643 if (marker_pos.x > layout_r.Min.x)
6644 {
6645 RenderBullet(draw_list: window->DrawList, pos: marker_pos, col: GetColorU32(idx: ImGuiCol_Text));
6646 clip_r.Max.x = ImMin(lhs: clip_r.Max.x, rhs: marker_pos.x - (int)(marker_size_x * 0.5f));
6647 }
6648 }
6649 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6650 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6651 RenderTextClipped(pos_min: layout_r.Min, pos_max: layout_r.Max, text: name, NULL, text_size_if_known: &text_size, align: style.WindowTitleAlign, clip_rect: &clip_r);
6652}
6653
6654void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6655{
6656 window->ParentWindow = parent_window;
6657 window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6658 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6659 {
6660 window->RootWindowDockTree = parent_window->RootWindowDockTree;
6661 if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6662 window->RootWindow = parent_window->RootWindow;
6663 }
6664 if (parent_window && (flags & ImGuiWindowFlags_Popup))
6665 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6666 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6667 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6668 while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6669 {
6670 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6671 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6672 }
6673}
6674
6675// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6676// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6677// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6678// - WindowA // FindBlockingModal() returns Modal1
6679// - WindowB // .. returns Modal1
6680// - Modal1 // .. returns Modal2
6681// - WindowC // .. returns Modal2
6682// - WindowD // .. returns Modal2
6683// - Modal2 // .. returns Modal2
6684// - WindowE // .. returns NULL
6685// Notes:
6686// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6687// Only difference is here we check for ->Active/WasActive but it may be unecessary.
6688ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6689{
6690 ImGuiContext& g = *GImGui;
6691 if (g.OpenPopupStack.Size <= 0)
6692 return NULL;
6693
6694 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6695 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6696 {
6697 ImGuiWindow* popup_window = popup_data.Window;
6698 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6699 continue;
6700 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.
6701 continue;
6702 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6703 return popup_window;
6704 if (IsWindowWithinBeginStackOf(window, potential_parent: popup_window)) // Window may be over modal
6705 continue;
6706 return popup_window; // Place window right below first block modal
6707 }
6708 return NULL;
6709}
6710
6711// Push a new Dear ImGui window to add widgets to.
6712// - 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.
6713// - Begin/End can be called multiple times during the frame with the same window name to append content.
6714// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6715// 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.
6716// - 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.
6717// - 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.
6718bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6719{
6720 ImGuiContext& g = *GImGui;
6721 const ImGuiStyle& style = g.Style;
6722 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
6723 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
6724 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6725
6726 // Find or create
6727 ImGuiWindow* window = FindWindowByName(name);
6728 const bool window_just_created = (window == NULL);
6729 if (window_just_created)
6730 window = CreateNewWindow(name, flags);
6731
6732 // [DEBUG] Debug break requested by user
6733 if (g.DebugBreakInWindow == window->ID)
6734 IM_DEBUG_BREAK();
6735
6736 // Automatically disable manual moving/resizing when NoInputs is set
6737 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6738 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6739
6740 if (flags & ImGuiWindowFlags_NavFlattened)
6741 IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6742
6743 const int current_frame = g.FrameCount;
6744 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6745 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6746
6747 // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6748 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6749 if (flags & ImGuiWindowFlags_Popup)
6750 {
6751 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6752 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6753 window_just_activated_by_user |= (window != popup_ref.Window);
6754 }
6755
6756 // Update Flags, LastFrameActive, BeginOrderXXX fields
6757 const bool window_was_appearing = window->Appearing;
6758 if (first_begin_of_the_frame)
6759 {
6760 UpdateWindowInFocusOrderList(window, just_created: window_just_created, new_flags: flags);
6761 window->Appearing = window_just_activated_by_user;
6762 if (window->Appearing)
6763 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
6764 window->FlagsPreviousFrame = window->Flags;
6765 window->Flags = (ImGuiWindowFlags)flags;
6766 window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6767 window->LastFrameActive = current_frame;
6768 window->LastTimeActive = (float)g.Time;
6769 window->BeginOrderWithinParent = 0;
6770 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6771 }
6772 else
6773 {
6774 flags = window->Flags;
6775 }
6776
6777 // Docking
6778 // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6779 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6780 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6781 SetWindowDock(window, dock_id: g.NextWindowData.DockId, cond: g.NextWindowData.DockCond);
6782 if (first_begin_of_the_frame)
6783 {
6784 bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6785 bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6786 bool dock_node_was_visible = window->DockNodeIsVisible;
6787 bool dock_tab_was_visible = window->DockTabIsVisible;
6788 if (has_dock_node || new_auto_dock_node)
6789 {
6790 BeginDocked(window, p_open);
6791 flags = window->Flags;
6792 if (window->DockIsActive)
6793 {
6794 IM_ASSERT(window->DockNode != NULL);
6795 g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6796 }
6797
6798 // Amend the Appearing flag
6799 if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6800 {
6801 window->Appearing = true;
6802 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
6803 }
6804 }
6805 else
6806 {
6807 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6808 }
6809 }
6810
6811 // 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
6812 ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6813 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6814 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6815
6816 // We allow window memory to be compacted so recreate the base stack when needed.
6817 if (window->IDStack.Size == 0)
6818 window->IDStack.push_back(v: window->ID);
6819
6820 // Add to stack
6821 g.CurrentWindow = window;
6822 ImGuiWindowStackData window_stack_data;
6823 window_stack_data.Window = window;
6824 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6825 window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6826 g.CurrentWindowStack.push_back(v: window_stack_data);
6827 if (flags & ImGuiWindowFlags_ChildMenu)
6828 g.BeginMenuDepth++;
6829
6830 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6831 if (first_begin_of_the_frame)
6832 {
6833 UpdateWindowParentAndRootLinks(window, flags, parent_window);
6834 window->ParentWindowInBeginStack = parent_window_in_stack;
6835
6836 // Focus route
6837 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
6838 // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
6839 window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
6840 if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
6841 if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
6842 window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
6843
6844 // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
6845 if (window->WindowClass.FocusRouteParentWindowId != 0)
6846 {
6847 window->ParentWindowForFocusRoute = FindWindowByID(id: window->WindowClass.FocusRouteParentWindowId);
6848 IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
6849 }
6850 }
6851
6852 // Add to focus scope stack
6853 PushFocusScope(id: (flags & ImGuiWindowFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
6854 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6855
6856 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
6857 if (flags & ImGuiWindowFlags_Popup)
6858 {
6859 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6860 popup_ref.Window = window;
6861 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6862 g.BeginPopupStack.push_back(v: popup_ref);
6863 window->PopupId = popup_ref.PopupId;
6864 }
6865
6866 // Process SetNextWindow***() calls
6867 // (FIXME: Consider splitting the HasXXX flags into X/Y components
6868 bool window_pos_set_by_api = false;
6869 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6870 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6871 {
6872 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6873 if (window_pos_set_by_api && ImLengthSqr(lhs: g.NextWindowData.PosPivotVal) > 0.00001f)
6874 {
6875 // May be processed on the next frame if this is our first frame and we are measuring size
6876 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6877 window->SetWindowPosVal = g.NextWindowData.PosVal;
6878 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6879 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6880 }
6881 else
6882 {
6883 SetWindowPos(window, pos: g.NextWindowData.PosVal, cond: g.NextWindowData.PosCond);
6884 }
6885 }
6886 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6887 {
6888 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6889 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6890 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6891 g.NextWindowData.SizeVal.x = window->SizeFull.x;
6892 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6893 g.NextWindowData.SizeVal.y = window->SizeFull.y;
6894 SetWindowSize(window, size: g.NextWindowData.SizeVal, cond: g.NextWindowData.SizeCond);
6895 }
6896 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6897 {
6898 if (g.NextWindowData.ScrollVal.x >= 0.0f)
6899 {
6900 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6901 window->ScrollTargetCenterRatio.x = 0.0f;
6902 }
6903 if (g.NextWindowData.ScrollVal.y >= 0.0f)
6904 {
6905 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6906 window->ScrollTargetCenterRatio.y = 0.0f;
6907 }
6908 }
6909 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6910 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6911 else if (first_begin_of_the_frame)
6912 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6913 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6914 window->WindowClass = g.NextWindowData.WindowClass;
6915 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6916 SetWindowCollapsed(window, collapsed: g.NextWindowData.CollapsedVal, cond: g.NextWindowData.CollapsedCond);
6917 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6918 FocusWindow(window);
6919 if (window->Appearing)
6920 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: false);
6921
6922 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6923 g.CurrentWindow = NULL;
6924
6925 // When reusing window again multiple times a frame, just append content (don't need to setup again)
6926 if (first_begin_of_the_frame)
6927 {
6928 // Initialize
6929 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6930 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6931 window->Active = true;
6932 window->HasCloseButton = (p_open != NULL);
6933 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6934 window->IDStack.resize(new_size: 1);
6935 window->DrawList->_ResetForNewFrame();
6936 window->DC.CurrentTableIdx = -1;
6937 if (flags & ImGuiWindowFlags_DockNodeHost)
6938 {
6939 window->DrawList->ChannelsSplit(count: 2);
6940 window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6941 }
6942
6943 // Restore buffer capacity when woken from a compacted state, to avoid
6944 if (window->MemoryCompacted)
6945 GcAwakeTransientWindowBuffers(window);
6946
6947 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6948 // 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.
6949 bool window_title_visible_elsewhere = false;
6950 if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6951 window_title_visible_elsewhere = true;
6952 else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
6953 window_title_visible_elsewhere = true;
6954 if (window_title_visible_elsewhere && !window_just_created && strcmp(s1: name, s2: window->Name) != 0)
6955 {
6956 size_t buf_len = (size_t)window->NameBufLen;
6957 window->Name = ImStrdupcpy(dst: window->Name, p_dst_size: &buf_len, src: name);
6958 window->NameBufLen = (int)buf_len;
6959 }
6960
6961 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6962
6963 // Update contents size from last frame for auto-fitting (or use explicit size)
6964 CalcWindowContentSizes(window, content_size_current: &window->ContentSize, content_size_ideal: &window->ContentSizeIdeal);
6965
6966 // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6967 // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6968 // it has a single usage before this code block and may be set below before it is finally checked.
6969 if (window->HiddenFramesCanSkipItems > 0)
6970 window->HiddenFramesCanSkipItems--;
6971 if (window->HiddenFramesCannotSkipItems > 0)
6972 window->HiddenFramesCannotSkipItems--;
6973 if (window->HiddenFramesForRenderOnly > 0)
6974 window->HiddenFramesForRenderOnly--;
6975
6976 // Hide new windows for one frame until they calculate their size
6977 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6978 window->HiddenFramesCannotSkipItems = 1;
6979
6980 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6981 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6982 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6983 {
6984 window->HiddenFramesCannotSkipItems = 1;
6985 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6986 {
6987 if (!window_size_x_set_by_api)
6988 window->Size.x = window->SizeFull.x = 0.f;
6989 if (!window_size_y_set_by_api)
6990 window->Size.y = window->SizeFull.y = 0.f;
6991 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6992 }
6993 }
6994
6995 // SELECT VIEWPORT
6996 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6997
6998 WindowSelectViewport(window);
6999 SetCurrentViewport(window, viewport: window->Viewport);
7000 window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7001 SetCurrentWindow(window);
7002 flags = window->Flags;
7003
7004 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7005 // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7006
7007 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7008 window->WindowBorderSize = style.ChildBorderSize;
7009 else
7010 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7011 window->WindowPadding = style.WindowPadding;
7012 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7013 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7014
7015 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7016 window->DC.MenuBarOffset.x = ImMax(lhs: ImMax(lhs: window->WindowPadding.x, rhs: style.ItemSpacing.x), rhs: g.NextWindowData.MenuBarOffsetMinVal.x);
7017 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7018
7019 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7020 // Those flags will be altered further down in the function depending on more conditions.
7021 bool use_current_size_for_scrollbar_x = window_just_created;
7022 bool use_current_size_for_scrollbar_y = window_just_created;
7023 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7024 use_current_size_for_scrollbar_x = true;
7025 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7026 use_current_size_for_scrollbar_y = true;
7027
7028 // Collapse window by double-clicking on title bar
7029 // 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
7030 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7031 {
7032 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7033 ImRect title_bar_rect = window->TitleBarRect();
7034 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max))
7035 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(key: ImGuiKey_MouseLeft) == ImGuiKeyOwner_None)
7036 window->WantCollapseToggle = true;
7037 if (window->WantCollapseToggle)
7038 {
7039 window->Collapsed = !window->Collapsed;
7040 if (!window->Collapsed)
7041 use_current_size_for_scrollbar_y = true;
7042 MarkIniSettingsDirty(window);
7043 }
7044 }
7045 else
7046 {
7047 window->Collapsed = false;
7048 }
7049 window->WantCollapseToggle = false;
7050
7051 // SIZE
7052
7053 // Outer Decoration Sizes
7054 // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7055 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7056 window->DecoOuterSizeX1 = 0.0f;
7057 window->DecoOuterSizeX2 = 0.0f;
7058 window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7059 window->DecoOuterSizeY2 = 0.0f;
7060 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7061
7062 // Calculate auto-fit size, handle automatic resize
7063 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: window->ContentSizeIdeal);
7064 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7065 {
7066 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7067 if (!window_size_x_set_by_api)
7068 {
7069 window->SizeFull.x = size_auto_fit.x;
7070 use_current_size_for_scrollbar_x = true;
7071 }
7072 if (!window_size_y_set_by_api)
7073 {
7074 window->SizeFull.y = size_auto_fit.y;
7075 use_current_size_for_scrollbar_y = true;
7076 }
7077 }
7078 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7079 {
7080 // Auto-fit may only grow window during the first few frames
7081 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7082 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7083 {
7084 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.x, rhs: size_auto_fit.x) : size_auto_fit.x;
7085 use_current_size_for_scrollbar_x = true;
7086 }
7087 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7088 {
7089 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.y, rhs: size_auto_fit.y) : size_auto_fit.y;
7090 use_current_size_for_scrollbar_y = true;
7091 }
7092 if (!window->Collapsed)
7093 MarkIniSettingsDirty(window);
7094 }
7095
7096 // Apply minimum/maximum window size constraints and final size
7097 window->SizeFull = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull);
7098 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7099
7100 // POSITION
7101
7102 // Popup latch its initial position, will position itself when it appears next frame
7103 if (window_just_activated_by_user)
7104 {
7105 window->AutoPosLastDirection = ImGuiDir_None;
7106 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7107 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7108 }
7109
7110 // Position child window
7111 if (flags & ImGuiWindowFlags_ChildWindow)
7112 {
7113 IM_ASSERT(parent_window && parent_window->Active);
7114 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7115 parent_window->DC.ChildWindows.push_back(v: window);
7116 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7117 window->Pos = parent_window->DC.CursorPos;
7118 }
7119
7120 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7121 if (window_pos_with_pivot)
7122 SetWindowPos(window, pos: window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, cond: 0); // Position given a pivot (e.g. for centering)
7123 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7124 window->Pos = FindBestWindowPosForPopup(window);
7125 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7126 window->Pos = FindBestWindowPosForPopup(window);
7127 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7128 window->Pos = FindBestWindowPosForPopup(window);
7129
7130 // Late create viewport if we don't fit within our current host viewport.
7131 if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7132 if (!window->Viewport->GetMainRect().Contains(r: window->Rect()))
7133 {
7134 // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7135 //ImGuiViewport* old_viewport = window->Viewport;
7136 window->Viewport = AddUpdateViewport(window, id: window->ID, platform_pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_NoFocusOnAppearing);
7137
7138 // FIXME-DPI
7139 //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7140 SetCurrentViewport(window, viewport: window->Viewport);
7141 window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7142 SetCurrentWindow(window);
7143 }
7144
7145 if (window->ViewportOwned)
7146 WindowSyncOwnedViewport(window, parent_window_in_stack);
7147
7148 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7149 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7150 ImRect viewport_rect(window->Viewport->GetMainRect());
7151 ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7152 ImVec2 visibility_padding = ImMax(lhs: style.DisplayWindowPadding, rhs: style.DisplaySafeAreaPadding);
7153 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7154
7155 // Clamp position/size so window stays visible within its viewport or monitor
7156 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7157 // FIXME: Similar to code in GetWindowAllowedExtentRect()
7158 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7159 {
7160 if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7161 {
7162 ClampWindowPos(window, visibility_rect);
7163 }
7164 else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7165 {
7166 if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7167 {
7168 // While moving windows we allow them to straddle monitors (#7299, #3071)
7169 visibility_rect = g.PlatformMonitorsFullWorkRect;
7170 }
7171 else
7172 {
7173 // When not moving ensure visible in its monitor
7174 // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7175 const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(viewport: window->Viewport);
7176 visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7177 }
7178 visibility_rect.Expand(amount: -visibility_padding);
7179 ClampWindowPos(window, visibility_rect);
7180 }
7181 }
7182 window->Pos = ImTrunc(v: window->Pos);
7183
7184 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7185 // Large values tend to lead to variety of artifacts and are not recommended.
7186 if (window->ViewportOwned || window->DockIsActive)
7187 window->WindowRounding = 0.0f;
7188 else
7189 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7190
7191 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7192 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7193 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7194
7195 // Apply window focus (new and reactivated windows are moved to front)
7196 bool want_focus = false;
7197 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7198 {
7199 if (flags & ImGuiWindowFlags_Popup)
7200 want_focus = true;
7201 else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7202 want_focus = true;
7203 }
7204
7205 // [Test Engine] Register whole window in the item system (before submitting further decorations)
7206#ifdef IMGUI_ENABLE_TEST_ENGINE
7207 if (g.TestEngineHookItems)
7208 {
7209 IM_ASSERT(window->IDStack.Size == 1);
7210 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7211 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7212 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7213 window->IDStack.Size = 1;
7214 }
7215#endif
7216
7217 // Decide if we are going to handle borders and resize grips
7218 const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7219
7220 // Handle manual resize: Resize Grips, Borders, Gamepad
7221 int border_hovered = -1, border_held = -1;
7222 ImU32 resize_grip_col[4] = {};
7223 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.
7224 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7225 if (handle_borders_and_resize_grips && !window->Collapsed)
7226 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, border_hovered: &border_hovered, border_held: &border_held, resize_grip_count, resize_grip_col: &resize_grip_col[0], visibility_rect))
7227 {
7228 if (auto_fit_mask & (1 << ImGuiAxis_X))
7229 use_current_size_for_scrollbar_x = true;
7230 if (auto_fit_mask & (1 << ImGuiAxis_Y))
7231 use_current_size_for_scrollbar_y = true;
7232 }
7233 window->ResizeBorderHovered = (signed char)border_hovered;
7234 window->ResizeBorderHeld = (signed char)border_held;
7235
7236 // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7237 if (window->ViewportOwned)
7238 {
7239 if (!window->Viewport->PlatformRequestMove)
7240 window->Viewport->Pos = window->Pos;
7241 if (!window->Viewport->PlatformRequestResize)
7242 window->Viewport->Size = window->Size;
7243 window->Viewport->UpdateWorkRect();
7244 viewport_rect = window->Viewport->GetMainRect();
7245 }
7246
7247 // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7248 window->ViewportPos = window->Viewport->Pos;
7249
7250 // SCROLLBAR VISIBILITY
7251
7252 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7253 if (!window->Collapsed)
7254 {
7255 // When reading the current size we need to read it after size constraints have been applied.
7256 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7257 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7258 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7259 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7260 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7261 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7262 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7263 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7264 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7265 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));
7266 if (window->ScrollbarX && !window->ScrollbarY)
7267 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7268 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7269
7270 // Amend the partially filled window->DecorationXXX values.
7271 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7272 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7273 }
7274
7275 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7276 // Update various regions. Variables they depend on should be set above in this function.
7277 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7278
7279 // Outer rectangle
7280 // Not affected by window border size. Used by:
7281 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7282 // - Begin() initial clipping rect for drawing window background and borders.
7283 // - Begin() clipping whole child
7284 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7285 const ImRect outer_rect = window->Rect();
7286 const ImRect title_bar_rect = window->TitleBarRect();
7287 window->OuterRectClipped = outer_rect;
7288 if (window->DockIsActive)
7289 window->OuterRectClipped.Min.y += window->TitleBarHeight();
7290 window->OuterRectClipped.ClipWith(r: host_rect);
7291
7292 // Inner rectangle
7293 // Not affected by window border size. Used by:
7294 // - InnerClipRect
7295 // - ScrollToRectEx()
7296 // - NavUpdatePageUpPageDown()
7297 // - Scrollbar()
7298 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7299 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7300 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7301 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7302
7303 // Inner clipping rectangle.
7304 // Will extend a little bit outside the normal work region.
7305 // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7306 // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7307 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7308 // Affected by window/frame border size. Used by:
7309 // - Begin() initial clip rect
7310 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7311 window->InnerClipRect.Min.x = ImFloor(f: 0.5f + window->InnerRect.Min.x + ImMax(lhs: ImTrunc(f: window->WindowPadding.x * 0.5f), rhs: window->WindowBorderSize));
7312 window->InnerClipRect.Min.y = ImFloor(f: 0.5f + window->InnerRect.Min.y + top_border_size);
7313 window->InnerClipRect.Max.x = ImFloor(f: 0.5f + window->InnerRect.Max.x - ImMax(lhs: ImTrunc(f: window->WindowPadding.x * 0.5f), rhs: window->WindowBorderSize));
7314 window->InnerClipRect.Max.y = ImFloor(f: 0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7315 window->InnerClipRect.ClipWithFull(r: host_rect);
7316
7317 // Default item width. Make it proportional to window size if window manually resizes
7318 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7319 window->ItemWidthDefault = ImTrunc(f: window->Size.x * 0.65f);
7320 else
7321 window->ItemWidthDefault = ImTrunc(f: g.FontSize * 16.0f);
7322
7323 // SCROLLING
7324
7325 // Lock down maximum scrolling
7326 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7327 // for right/bottom aligned items without creating a scrollbar.
7328 window->ScrollMax.x = ImMax(lhs: 0.0f, rhs: window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7329 window->ScrollMax.y = ImMax(lhs: 0.0f, rhs: window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7330
7331 // Apply scrolling
7332 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7333 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7334 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7335
7336 // DRAWING
7337
7338 // Setup draw list and outer clipping rectangle
7339 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7340 window->DrawList->PushTextureID(texture_id: g.Font->ContainerAtlas->TexID);
7341 PushClipRect(clip_rect_min: host_rect.Min, clip_rect_max: host_rect.Max, intersect_with_current_clip_rect: false);
7342
7343 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7344 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7345 // 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)
7346 const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7347 if (is_undocked_or_docked_visible)
7348 {
7349 bool render_decorations_in_parent = false;
7350 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7351 {
7352 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7353 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7354 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7355 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(r: window->Rect()) : false;
7356 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7357 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7358 render_decorations_in_parent = true;
7359 }
7360 if (render_decorations_in_parent)
7361 window->DrawList = parent_window->DrawList;
7362
7363 // Handle title bar, scrollbar, resize grips and resize borders
7364 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7365 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)));
7366 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7367
7368 if (render_decorations_in_parent)
7369 window->DrawList = &window->DrawListInst;
7370 }
7371
7372 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7373
7374 // Work rectangle.
7375 // Affected by window padding and border size. Used by:
7376 // - Columns() for right-most edge
7377 // - TreeNode(), CollapsingHeader() for right-most edge
7378 // - BeginTabBar() for right-most edge
7379 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7380 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7381 const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(lhs: allow_scrollbar_x ? window->ContentSize.x : 0.0f, rhs: window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7382 const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(lhs: allow_scrollbar_y ? window->ContentSize.y : 0.0f, rhs: window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7383 window->WorkRect.Min.x = ImTrunc(f: window->InnerRect.Min.x - window->Scroll.x + ImMax(lhs: window->WindowPadding.x, rhs: window->WindowBorderSize));
7384 window->WorkRect.Min.y = ImTrunc(f: window->InnerRect.Min.y - window->Scroll.y + ImMax(lhs: window->WindowPadding.y, rhs: window->WindowBorderSize));
7385 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7386 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7387 window->ParentWorkRect = window->WorkRect;
7388
7389 // [LEGACY] Content Region
7390 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7391 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7392 // Used by:
7393 // - Mouse wheel scrolling + many other things
7394 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7395 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7396 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)));
7397 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)));
7398
7399 // Setup drawing context
7400 // (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.)
7401 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7402 window->DC.GroupOffset.x = 0.0f;
7403 window->DC.ColumnsOffset.x = 0.0f;
7404
7405 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7406 // 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.
7407 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7408 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7409 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7410 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7411 window->DC.CursorPos = window->DC.CursorStartPos;
7412 window->DC.CursorPosPrevLine = window->DC.CursorPos;
7413 window->DC.CursorMaxPos = window->DC.CursorStartPos;
7414 window->DC.IdealMaxPos = window->DC.CursorStartPos;
7415 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7416 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7417 window->DC.IsSameLine = window->DC.IsSetPos = false;
7418
7419 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7420 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7421 window->DC.NavLayersActiveMaskNext = 0x00;
7422 window->DC.NavIsScrollPushableX = true;
7423 window->DC.NavHideHighlightOneFrame = false;
7424 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7425
7426 window->DC.MenuBarAppending = false;
7427 window->DC.MenuColumns.Update(spacing: style.ItemSpacing.x, window_reappearing: window_just_activated_by_user);
7428 window->DC.TreeDepth = 0;
7429 window->DC.TreeJumpToParentOnPopMask = 0x00;
7430 window->DC.ChildWindows.resize(new_size: 0);
7431 window->DC.StateStorage = &window->StateStorage;
7432 window->DC.CurrentColumns = NULL;
7433 window->DC.LayoutType = ImGuiLayoutType_Vertical;
7434 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7435
7436 window->DC.ItemWidth = window->ItemWidthDefault;
7437 window->DC.TextWrapPos = -1.0f; // disabled
7438 window->DC.ItemWidthStack.resize(new_size: 0);
7439 window->DC.TextWrapPosStack.resize(new_size: 0);
7440 if (flags & ImGuiWindowFlags_Modal)
7441 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(in: GetStyleColorVec4(idx: ImGuiCol_ModalWindowDimBg));
7442
7443 if (window->AutoFitFramesX > 0)
7444 window->AutoFitFramesX--;
7445 if (window->AutoFitFramesY > 0)
7446 window->AutoFitFramesY--;
7447
7448 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7449 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7450 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7451 // - Position window behind the modal that is not a begin-parent of this window.
7452 if (want_focus)
7453 FocusWindow(window, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
7454 if (want_focus && window == g.NavWindow)
7455 NavInitWindow(window, force_reinit: false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7456
7457 // Close requested by platform window (apply to all windows in this viewport)
7458 if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7459 {
7460 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7461 *p_open = false;
7462 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.
7463 }
7464
7465 // Title bar
7466 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7467 RenderWindowTitleBarContents(window, title_bar_rect: ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7468
7469 // Clear hit test shape every frame
7470 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7471
7472 // Pressing CTRL+C while holding on a window copy its content to the clipboard
7473 // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7474 // Maybe we can support CTRL+C on every element?
7475 /*
7476 //if (g.NavWindow == window && g.ActiveId == 0)
7477 if (g.ActiveId == window->MoveId)
7478 if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7479 LogToClipboard();
7480 */
7481
7482 if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7483 {
7484 // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7485 // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7486 if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7487 BeginDockableDragDropSource(window);
7488
7489 // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7490 if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7491 if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7492 if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7493 BeginDockableDragDropTarget(window);
7494 }
7495
7496 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7497 // This is useful to allow creating context menus on title bar only, etc.
7498 if (window->DockIsActive)
7499 SetLastItemData(item_id: window->MoveId, in_flags: g.CurrentItemFlags, item_flags: window->DockTabItemStatusFlags, item_rect: window->DockTabItemRect);
7500 else
7501 SetLastItemData(item_id: window->MoveId, in_flags: g.CurrentItemFlags, item_flags: IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max, clip: false) ? ImGuiItemStatusFlags_HoveredRect : 0, item_rect: title_bar_rect);
7502
7503 // [DEBUG]
7504#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7505 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7506 DebugLocateItemResolveWithLastItem();
7507#endif
7508
7509 // [Test Engine] Register title bar / tab with MoveId.
7510#ifdef IMGUI_ENABLE_TEST_ENGINE
7511 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7512 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7513#endif
7514 }
7515 else
7516 {
7517 // Append
7518 SetCurrentViewport(window, viewport: window->Viewport);
7519 SetCurrentWindow(window);
7520 }
7521
7522 if (!(flags & ImGuiWindowFlags_DockNodeHost))
7523 PushClipRect(clip_rect_min: window->InnerClipRect.Min, clip_rect_max: window->InnerClipRect.Max, intersect_with_current_clip_rect: true);
7524
7525 // 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)
7526 window->WriteAccessed = false;
7527 window->BeginCount++;
7528 g.NextWindowData.ClearFlags();
7529
7530 // Update visibility
7531 if (first_begin_of_the_frame)
7532 {
7533 // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7534 // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7535 // This is analogous to regular windows being hidden from one frame.
7536 // 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.
7537 if (window->DockIsActive && !window->DockTabIsVisible)
7538 {
7539 if (window->LastFrameJustFocused == g.FrameCount)
7540 window->HiddenFramesCannotSkipItems = 1;
7541 else
7542 window->HiddenFramesCanSkipItems = 1;
7543 }
7544
7545 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7546 {
7547 // Child window can be out of sight and have "negative" clip windows.
7548 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7549 IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7550 const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7551 if (!g.LogEnabled && !nav_request)
7552 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7553 {
7554 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7555 window->HiddenFramesCannotSkipItems = 1;
7556 else
7557 window->HiddenFramesCanSkipItems = 1;
7558 }
7559
7560 // Hide along with parent or if parent is collapsed
7561 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7562 window->HiddenFramesCanSkipItems = 1;
7563 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7564 window->HiddenFramesCannotSkipItems = 1;
7565 }
7566
7567 // 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)
7568 if (style.Alpha <= 0.0f)
7569 window->HiddenFramesCanSkipItems = 1;
7570
7571 // Update the Hidden flag
7572 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7573 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7574
7575 // Disable inputs for requested number of frames
7576 if (window->DisableInputsFrames > 0)
7577 {
7578 window->DisableInputsFrames--;
7579 window->Flags |= ImGuiWindowFlags_NoInputs;
7580 }
7581
7582 // Update the SkipItems flag, used to early out of all items functions (no layout required)
7583 bool skip_items = false;
7584 if (window->Collapsed || !window->Active || hidden_regular)
7585 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7586 skip_items = true;
7587 window->SkipItems = skip_items;
7588
7589 // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7590 if (window->SkipItems)
7591 window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7592
7593 // Sanity check: there are two spots which can set Appearing = true
7594 // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7595 // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7596 if (window->SkipItems && !window->Appearing)
7597 IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7598 }
7599
7600 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7601 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7602#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7603 if (!window->IsFallbackWindow)
7604 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7605 {
7606 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7607 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7608 return false;
7609 }
7610#endif
7611
7612 return !window->SkipItems;
7613}
7614
7615void ImGui::End()
7616{
7617 ImGuiContext& g = *GImGui;
7618 ImGuiWindow* window = g.CurrentWindow;
7619
7620 // Error checking: verify that user hasn't called End() too many times!
7621 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7622 {
7623 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7624 return;
7625 }
7626 IM_ASSERT(g.CurrentWindowStack.Size > 0);
7627
7628 // Error checking: verify that user doesn't directly call End() on a child window.
7629 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7630 IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7631
7632 // Close anything that is open
7633 if (window->DC.CurrentColumns)
7634 EndColumns();
7635 if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle
7636 PopClipRect();
7637 PopFocusScope();
7638
7639 // Stop logging
7640 if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
7641 LogFinish();
7642
7643 if (window->DC.IsSetPos)
7644 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7645
7646 // Docking: report contents sizes to parent to allow for auto-resize
7647 if (window->DockNode && window->DockTabIsVisible)
7648 if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
7649 host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7650
7651 // Pop from window stack
7652 g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7653 if (window->Flags & ImGuiWindowFlags_ChildMenu)
7654 g.BeginMenuDepth--;
7655 if (window->Flags & ImGuiWindowFlags_Popup)
7656 g.BeginPopupStack.pop_back();
7657 g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(ctx: &g);
7658 g.CurrentWindowStack.pop_back();
7659 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7660 if (g.CurrentWindow)
7661 SetCurrentViewport(window: g.CurrentWindow, viewport: g.CurrentWindow->Viewport);
7662}
7663
7664void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7665{
7666 ImGuiContext& g = *GImGui;
7667 IM_ASSERT(window == window->RootWindow);
7668
7669 const int cur_order = window->FocusOrder;
7670 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7671 if (g.WindowsFocusOrder.back() == window)
7672 return;
7673
7674 const int new_order = g.WindowsFocusOrder.Size - 1;
7675 for (int n = cur_order; n < new_order; n++)
7676 {
7677 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7678 g.WindowsFocusOrder[n]->FocusOrder--;
7679 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7680 }
7681 g.WindowsFocusOrder[new_order] = window;
7682 window->FocusOrder = (short)new_order;
7683}
7684
7685void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7686{
7687 ImGuiContext& g = *GImGui;
7688 ImGuiWindow* current_front_window = g.Windows.back();
7689 if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7690 return;
7691 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7692 if (g.Windows[i] == window)
7693 {
7694 memmove(dest: &g.Windows[i], src: &g.Windows[i + 1], n: (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7695 g.Windows[g.Windows.Size - 1] = window;
7696 break;
7697 }
7698}
7699
7700void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7701{
7702 ImGuiContext& g = *GImGui;
7703 if (g.Windows[0] == window)
7704 return;
7705 for (int i = 0; i < g.Windows.Size; i++)
7706 if (g.Windows[i] == window)
7707 {
7708 memmove(dest: &g.Windows[1], src: &g.Windows[0], n: (size_t)i * sizeof(ImGuiWindow*));
7709 g.Windows[0] = window;
7710 break;
7711 }
7712}
7713
7714void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7715{
7716 IM_ASSERT(window != NULL && behind_window != NULL);
7717 ImGuiContext& g = *GImGui;
7718 window = window->RootWindow;
7719 behind_window = behind_window->RootWindow;
7720 int pos_wnd = FindWindowDisplayIndex(window);
7721 int pos_beh = FindWindowDisplayIndex(window: behind_window);
7722 if (pos_wnd < pos_beh)
7723 {
7724 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7725 memmove(dest: &g.Windows.Data[pos_wnd], src: &g.Windows.Data[pos_wnd + 1], n: copy_bytes);
7726 g.Windows[pos_beh - 1] = window;
7727 }
7728 else
7729 {
7730 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7731 memmove(dest: &g.Windows.Data[pos_beh + 1], src: &g.Windows.Data[pos_beh], n: copy_bytes);
7732 g.Windows[pos_beh] = window;
7733 }
7734}
7735
7736int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7737{
7738 ImGuiContext& g = *GImGui;
7739 return g.Windows.index_from_ptr(it: g.Windows.find(v: window));
7740}
7741
7742// Moving window to front of display and set focus (which happens to be back of our sorted list)
7743void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7744{
7745 ImGuiContext& g = *GImGui;
7746
7747 // Modal check?
7748 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7749 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7750 {
7751 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7752 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7753 BringWindowToDisplayBehind(window, behind_window: blocking_modal); // Still bring to right below modal.
7754 return;
7755 }
7756
7757 // Find last focused child (if any) and focus it instead.
7758 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7759 window = NavRestoreLastChildNavWindow(window);
7760
7761 // Apply focus
7762 if (g.NavWindow != window)
7763 {
7764 SetNavWindow(window);
7765 if (window && g.NavDisableMouseHover)
7766 g.NavMousePosDirty = true;
7767 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7768 g.NavLayer = ImGuiNavLayer_Main;
7769 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7770 g.NavIdIsAlive = false;
7771 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7772
7773 // Close popups if any
7774 ClosePopupsOverWindow(ref_window: window, restore_focus_to_window_under_popup: false);
7775 }
7776
7777 // Move the root window to the top of the pile
7778 IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7779 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7780 ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7781 ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7782 bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7783
7784 // Steal active widgets. Some of the cases it triggers includes:
7785 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7786 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7787 // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7788 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7789 if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7790 ClearActiveID();
7791
7792 // Passing NULL allow to disable keyboard focus
7793 if (!window)
7794 return;
7795 window->LastFrameJustFocused = g.FrameCount;
7796
7797 // Select in dock node
7798 // For #2304 we avoid applying focus immediately before the tabbar is visible.
7799 //if (dock_node && dock_node->TabBar)
7800 // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7801
7802 // Bring to front
7803 BringWindowToFocusFront(window: focus_front_window);
7804 if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7805 BringWindowToDisplayFront(window: display_front_window);
7806}
7807
7808void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7809{
7810 ImGuiContext& g = *GImGui;
7811 int start_idx = g.WindowsFocusOrder.Size - 1;
7812 if (under_this_window != NULL)
7813 {
7814 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7815 int offset = -1;
7816 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7817 {
7818 under_this_window = under_this_window->ParentWindow;
7819 offset = 0;
7820 }
7821 start_idx = FindWindowFocusIndex(window: under_this_window) + offset;
7822 }
7823 for (int i = start_idx; i >= 0; i--)
7824 {
7825 // 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.
7826 ImGuiWindow* window = g.WindowsFocusOrder[i];
7827 if (window == ignore_window || !window->WasActive)
7828 continue;
7829 if (filter_viewport != NULL && window->Viewport != filter_viewport)
7830 continue;
7831 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7832 {
7833 // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7834 // This is failing (lagging by one frame) for docked windows.
7835 // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7836 // 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)
7837 // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7838 FocusWindow(window, flags);
7839 return;
7840 }
7841 }
7842 FocusWindow(NULL, flags);
7843}
7844
7845// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7846void ImGui::SetCurrentFont(ImFont* font)
7847{
7848 ImGuiContext& g = *GImGui;
7849 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7850 IM_ASSERT(font->Scale > 0.0f);
7851 g.Font = font;
7852 g.FontBaseSize = ImMax(lhs: 1.0f, rhs: g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7853 g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7854
7855 ImFontAtlas* atlas = g.Font->ContainerAtlas;
7856 g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7857 g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7858 g.DrawListSharedData.Font = g.Font;
7859 g.DrawListSharedData.FontSize = g.FontSize;
7860}
7861
7862void ImGui::PushFont(ImFont* font)
7863{
7864 ImGuiContext& g = *GImGui;
7865 if (!font)
7866 font = GetDefaultFont();
7867 SetCurrentFont(font);
7868 g.FontStack.push_back(v: font);
7869 g.CurrentWindow->DrawList->PushTextureID(texture_id: font->ContainerAtlas->TexID);
7870}
7871
7872void ImGui::PopFont()
7873{
7874 ImGuiContext& g = *GImGui;
7875 g.CurrentWindow->DrawList->PopTextureID();
7876 g.FontStack.pop_back();
7877 SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7878}
7879
7880void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7881{
7882 ImGuiContext& g = *GImGui;
7883 ImGuiItemFlags item_flags = g.CurrentItemFlags;
7884 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7885 if (enabled)
7886 item_flags |= option;
7887 else
7888 item_flags &= ~option;
7889 g.CurrentItemFlags = item_flags;
7890 g.ItemFlagsStack.push_back(v: item_flags);
7891}
7892
7893void ImGui::PopItemFlag()
7894{
7895 ImGuiContext& g = *GImGui;
7896 IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7897 g.ItemFlagsStack.pop_back();
7898 g.CurrentItemFlags = g.ItemFlagsStack.back();
7899}
7900
7901// BeginDisabled()/EndDisabled()
7902// - 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)
7903// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7904// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7905// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7906// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7907void ImGui::BeginDisabled(bool disabled)
7908{
7909 ImGuiContext& g = *GImGui;
7910 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7911 if (!was_disabled && disabled)
7912 {
7913 g.DisabledAlphaBackup = g.Style.Alpha;
7914 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7915 }
7916 if (was_disabled || disabled)
7917 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7918 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags);
7919 g.DisabledStackSize++;
7920}
7921
7922void ImGui::EndDisabled()
7923{
7924 ImGuiContext& g = *GImGui;
7925 IM_ASSERT(g.DisabledStackSize > 0);
7926 g.DisabledStackSize--;
7927 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7928 //PopItemFlag();
7929 g.ItemFlagsStack.pop_back();
7930 g.CurrentItemFlags = g.ItemFlagsStack.back();
7931 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7932 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7933}
7934
7935void ImGui::PushTabStop(bool tab_stop)
7936{
7937 PushItemFlag(option: ImGuiItemFlags_NoTabStop, enabled: !tab_stop);
7938}
7939
7940void ImGui::PopTabStop()
7941{
7942 PopItemFlag();
7943}
7944
7945void ImGui::PushButtonRepeat(bool repeat)
7946{
7947 PushItemFlag(option: ImGuiItemFlags_ButtonRepeat, enabled: repeat);
7948}
7949
7950void ImGui::PopButtonRepeat()
7951{
7952 PopItemFlag();
7953}
7954
7955void ImGui::PushTextWrapPos(float wrap_pos_x)
7956{
7957 ImGuiWindow* window = GetCurrentWindow();
7958 window->DC.TextWrapPosStack.push_back(v: window->DC.TextWrapPos);
7959 window->DC.TextWrapPos = wrap_pos_x;
7960}
7961
7962void ImGui::PopTextWrapPos()
7963{
7964 ImGuiWindow* window = GetCurrentWindow();
7965 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7966 window->DC.TextWrapPosStack.pop_back();
7967}
7968
7969static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7970{
7971 ImGuiWindow* last_window = NULL;
7972 while (last_window != window)
7973 {
7974 last_window = window;
7975 window = window->RootWindow;
7976 if (popup_hierarchy)
7977 window = window->RootWindowPopupTree;
7978 if (dock_hierarchy)
7979 window = window->RootWindowDockTree;
7980 }
7981 return window;
7982}
7983
7984bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7985{
7986 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7987 if (window_root == potential_parent)
7988 return true;
7989 while (window != NULL)
7990 {
7991 if (window == potential_parent)
7992 return true;
7993 if (window == window_root) // end of chain
7994 return false;
7995 window = window->ParentWindow;
7996 }
7997 return false;
7998}
7999
8000bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8001{
8002 if (window->RootWindow == potential_parent)
8003 return true;
8004 while (window != NULL)
8005 {
8006 if (window == potential_parent)
8007 return true;
8008 window = window->ParentWindowInBeginStack;
8009 }
8010 return false;
8011}
8012
8013bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8014{
8015 ImGuiContext& g = *GImGui;
8016
8017 // 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
8018 const int display_layer_delta = GetWindowDisplayLayer(window: potential_above) - GetWindowDisplayLayer(window: potential_below);
8019 if (display_layer_delta != 0)
8020 return display_layer_delta > 0;
8021
8022 for (int i = g.Windows.Size - 1; i >= 0; i--)
8023 {
8024 ImGuiWindow* candidate_window = g.Windows[i];
8025 if (candidate_window == potential_above)
8026 return true;
8027 if (candidate_window == potential_below)
8028 return false;
8029 }
8030 return false;
8031}
8032
8033// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8034// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8035// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8036// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8037bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8038{
8039 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8040
8041 ImGuiContext& g = *GImGui;
8042 ImGuiWindow* ref_window = g.HoveredWindow;
8043 ImGuiWindow* cur_window = g.CurrentWindow;
8044 if (ref_window == NULL)
8045 return false;
8046
8047 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8048 {
8049 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8050 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8051 const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8052 if (flags & ImGuiHoveredFlags_RootWindow)
8053 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy, dock_hierarchy);
8054
8055 bool result;
8056 if (flags & ImGuiHoveredFlags_ChildWindows)
8057 result = IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy, dock_hierarchy);
8058 else
8059 result = (ref_window == cur_window);
8060 if (!result)
8061 return false;
8062 }
8063
8064 if (!IsWindowContentHoverable(window: ref_window, flags))
8065 return false;
8066 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8067 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8068 return false;
8069
8070 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8071 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8072 // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8073 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8074 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8075 if (flags & ImGuiHoveredFlags_ForTooltip)
8076 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
8077 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8078 return false;
8079
8080 return true;
8081}
8082
8083bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8084{
8085 ImGuiContext& g = *GImGui;
8086 ImGuiWindow* ref_window = g.NavWindow;
8087 ImGuiWindow* cur_window = g.CurrentWindow;
8088
8089 if (ref_window == NULL)
8090 return false;
8091 if (flags & ImGuiFocusedFlags_AnyWindow)
8092 return true;
8093
8094 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8095 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8096 const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8097 if (flags & ImGuiHoveredFlags_RootWindow)
8098 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy, dock_hierarchy);
8099
8100 if (flags & ImGuiHoveredFlags_ChildWindows)
8101 return IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy, dock_hierarchy);
8102 else
8103 return (ref_window == cur_window);
8104}
8105
8106ImGuiID ImGui::GetWindowDockID()
8107{
8108 ImGuiContext& g = *GImGui;
8109 return g.CurrentWindow->DockId;
8110}
8111
8112bool ImGui::IsWindowDocked()
8113{
8114 ImGuiContext& g = *GImGui;
8115 return g.CurrentWindow->DockIsActive;
8116}
8117
8118// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8119// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8120// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8121bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8122{
8123 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8124}
8125
8126float ImGui::GetWindowWidth()
8127{
8128 ImGuiWindow* window = GImGui->CurrentWindow;
8129 return window->Size.x;
8130}
8131
8132float ImGui::GetWindowHeight()
8133{
8134 ImGuiWindow* window = GImGui->CurrentWindow;
8135 return window->Size.y;
8136}
8137
8138ImVec2 ImGui::GetWindowPos()
8139{
8140 ImGuiContext& g = *GImGui;
8141 ImGuiWindow* window = g.CurrentWindow;
8142 return window->Pos;
8143}
8144
8145void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8146{
8147 // Test condition (NB: bit 0 is always true) and clear flags for next time
8148 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8149 return;
8150
8151 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8152 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8153 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8154
8155 // Set
8156 const ImVec2 old_pos = window->Pos;
8157 window->Pos = ImTrunc(v: pos);
8158 ImVec2 offset = window->Pos - old_pos;
8159 if (offset.x == 0.0f && offset.y == 0.0f)
8160 return;
8161 MarkIniSettingsDirty(window);
8162 // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8163 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
8164 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8165 window->DC.IdealMaxPos += offset;
8166 window->DC.CursorStartPos += offset;
8167}
8168
8169void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8170{
8171 ImGuiWindow* window = GetCurrentWindowRead();
8172 SetWindowPos(window, pos, cond);
8173}
8174
8175void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8176{
8177 if (ImGuiWindow* window = FindWindowByName(name))
8178 SetWindowPos(window, pos, cond);
8179}
8180
8181ImVec2 ImGui::GetWindowSize()
8182{
8183 ImGuiWindow* window = GetCurrentWindowRead();
8184 return window->Size;
8185}
8186
8187void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8188{
8189 // Test condition (NB: bit 0 is always true) and clear flags for next time
8190 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8191 return;
8192
8193 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8194 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8195
8196 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8197 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8198 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8199 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8200 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8201
8202 // Set
8203 ImVec2 old_size = window->SizeFull;
8204 if (size.x <= 0.0f)
8205 window->AutoFitOnlyGrows = false;
8206 else
8207 window->SizeFull.x = IM_TRUNC(size.x);
8208 if (size.y <= 0.0f)
8209 window->AutoFitOnlyGrows = false;
8210 else
8211 window->SizeFull.y = IM_TRUNC(size.y);
8212 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8213 MarkIniSettingsDirty(window);
8214}
8215
8216void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8217{
8218 SetWindowSize(window: GImGui->CurrentWindow, size, cond);
8219}
8220
8221void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8222{
8223 if (ImGuiWindow* window = FindWindowByName(name))
8224 SetWindowSize(window, size, cond);
8225}
8226
8227void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8228{
8229 // Test condition (NB: bit 0 is always true) and clear flags for next time
8230 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8231 return;
8232 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8233
8234 // Set
8235 window->Collapsed = collapsed;
8236}
8237
8238void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8239{
8240 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8241 window->HitTestHoleSize = ImVec2ih(size);
8242 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8243}
8244
8245void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8246{
8247 window->Hidden = window->SkipItems = true;
8248 window->HiddenFramesCanSkipItems = 1;
8249}
8250
8251void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8252{
8253 SetWindowCollapsed(window: GImGui->CurrentWindow, collapsed, cond);
8254}
8255
8256bool ImGui::IsWindowCollapsed()
8257{
8258 ImGuiWindow* window = GetCurrentWindowRead();
8259 return window->Collapsed;
8260}
8261
8262bool ImGui::IsWindowAppearing()
8263{
8264 ImGuiWindow* window = GetCurrentWindowRead();
8265 return window->Appearing;
8266}
8267
8268void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8269{
8270 if (ImGuiWindow* window = FindWindowByName(name))
8271 SetWindowCollapsed(window, collapsed, cond);
8272}
8273
8274void ImGui::SetWindowFocus()
8275{
8276 FocusWindow(window: GImGui->CurrentWindow);
8277}
8278
8279void ImGui::SetWindowFocus(const char* name)
8280{
8281 if (name)
8282 {
8283 if (ImGuiWindow* window = FindWindowByName(name))
8284 FocusWindow(window);
8285 }
8286 else
8287 {
8288 FocusWindow(NULL);
8289 }
8290}
8291
8292void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8293{
8294 ImGuiContext& g = *GImGui;
8295 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8296 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8297 g.NextWindowData.PosVal = pos;
8298 g.NextWindowData.PosPivotVal = pivot;
8299 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8300 g.NextWindowData.PosUndock = true;
8301}
8302
8303void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8304{
8305 ImGuiContext& g = *GImGui;
8306 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8307 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8308 g.NextWindowData.SizeVal = size;
8309 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8310}
8311
8312// For each axis:
8313// - 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.
8314// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8315// - See "Demo->Examples->Constrained-resizing window" for examples.
8316void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8317{
8318 ImGuiContext& g = *GImGui;
8319 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8320 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8321 g.NextWindowData.SizeCallback = custom_callback;
8322 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8323}
8324
8325// Content size = inner scrollable rectangle, padded with WindowPadding.
8326// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8327void ImGui::SetNextWindowContentSize(const ImVec2& size)
8328{
8329 ImGuiContext& g = *GImGui;
8330 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8331 g.NextWindowData.ContentSizeVal = ImTrunc(v: size);
8332}
8333
8334void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8335{
8336 ImGuiContext& g = *GImGui;
8337 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8338 g.NextWindowData.ScrollVal = scroll;
8339}
8340
8341void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8342{
8343 ImGuiContext& g = *GImGui;
8344 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8345 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8346 g.NextWindowData.CollapsedVal = collapsed;
8347 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8348}
8349
8350void ImGui::SetNextWindowFocus()
8351{
8352 ImGuiContext& g = *GImGui;
8353 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8354}
8355
8356void ImGui::SetNextWindowBgAlpha(float alpha)
8357{
8358 ImGuiContext& g = *GImGui;
8359 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8360 g.NextWindowData.BgAlphaVal = alpha;
8361}
8362
8363void ImGui::SetNextWindowViewport(ImGuiID id)
8364{
8365 ImGuiContext& g = *GImGui;
8366 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8367 g.NextWindowData.ViewportId = id;
8368}
8369
8370void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8371{
8372 ImGuiContext& g = *GImGui;
8373 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8374 g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8375 g.NextWindowData.DockId = id;
8376}
8377
8378void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8379{
8380 ImGuiContext& g = *GImGui;
8381 IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8382 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8383 g.NextWindowData.WindowClass = *window_class;
8384}
8385
8386ImDrawList* ImGui::GetWindowDrawList()
8387{
8388 ImGuiWindow* window = GetCurrentWindow();
8389 return window->DrawList;
8390}
8391
8392float ImGui::GetWindowDpiScale()
8393{
8394 ImGuiContext& g = *GImGui;
8395 return g.CurrentDpiScale;
8396}
8397
8398ImGuiViewport* ImGui::GetWindowViewport()
8399{
8400 ImGuiContext& g = *GImGui;
8401 IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8402 return g.CurrentViewport;
8403}
8404
8405ImFont* ImGui::GetFont()
8406{
8407 return GImGui->Font;
8408}
8409
8410float ImGui::GetFontSize()
8411{
8412 return GImGui->FontSize;
8413}
8414
8415ImVec2 ImGui::GetFontTexUvWhitePixel()
8416{
8417 return GImGui->DrawListSharedData.TexUvWhitePixel;
8418}
8419
8420void ImGui::SetWindowFontScale(float scale)
8421{
8422 IM_ASSERT(scale > 0.0f);
8423 ImGuiContext& g = *GImGui;
8424 ImGuiWindow* window = GetCurrentWindow();
8425 window->FontWindowScale = scale;
8426 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8427}
8428
8429void ImGui::PushFocusScope(ImGuiID id)
8430{
8431 ImGuiContext& g = *GImGui;
8432 ImGuiFocusScopeData data;
8433 data.ID = id;
8434 data.WindowID = g.CurrentWindow->ID;
8435 g.FocusScopeStack.push_back(v: data);
8436 g.CurrentFocusScopeId = id;
8437}
8438
8439void ImGui::PopFocusScope()
8440{
8441 ImGuiContext& g = *GImGui;
8442 if (g.FocusScopeStack.Size == 0)
8443 {
8444 IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8445 return;
8446 }
8447 g.FocusScopeStack.pop_back();
8448 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8449}
8450
8451void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8452{
8453 ImGuiContext& g = *GImGui;
8454 g.NavFocusScopeId = focus_scope_id;
8455 g.NavFocusRoute.resize(new_size: 0); // Invalidate
8456 if (focus_scope_id == 0)
8457 return;
8458 IM_ASSERT(g.NavWindow != NULL);
8459
8460 // Store current path (in reverse order)
8461 if (focus_scope_id == g.CurrentFocusScopeId)
8462 {
8463 // Top of focus stack contains local focus scopes inside current window
8464 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8465 g.NavFocusRoute.push_back(v: g.FocusScopeStack.Data[n]);
8466 }
8467 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8468 g.NavFocusRoute.push_back(v: { .ID: focus_scope_id, .WindowID: g.NavWindow->ID });
8469 else
8470 return;
8471
8472 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8473 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8474 g.NavFocusRoute.push_back(v: { .ID: window->NavRootFocusScopeId, .WindowID: window->ID });
8475 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8476}
8477
8478// Focus = move navigation cursor, set scrolling, set focus window.
8479void ImGui::FocusItem()
8480{
8481 ImGuiContext& g = *GImGui;
8482 ImGuiWindow* window = g.CurrentWindow;
8483 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8484 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8485 {
8486 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8487 return;
8488 }
8489
8490 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8491 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8492 SetNavWindow(window);
8493 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: ImGuiDir_Up, move_flags, scroll_flags);
8494 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
8495}
8496
8497void ImGui::ActivateItemByID(ImGuiID id)
8498{
8499 ImGuiContext& g = *GImGui;
8500 g.NavNextActivateId = id;
8501 g.NavNextActivateFlags = ImGuiActivateFlags_None;
8502}
8503
8504// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8505// But ActivateItem() should function without altering scroll/focus?
8506void ImGui::SetKeyboardFocusHere(int offset)
8507{
8508 ImGuiContext& g = *GImGui;
8509 ImGuiWindow* window = g.CurrentWindow;
8510 IM_ASSERT(offset >= -1); // -1 is allowed but not below
8511 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8512
8513 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8514 // When we refactor this function into ActivateItem() we may want to make this an option.
8515 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8516 // is also automatically dropped in the event g.ActiveId is stolen.
8517 if (g.DragDropActive || g.MovingWindow != NULL)
8518 {
8519 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8520 return;
8521 }
8522
8523 SetNavWindow(window);
8524
8525 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8526 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8527 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8528 if (offset == -1)
8529 {
8530 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
8531 }
8532 else
8533 {
8534 g.NavTabbingDir = 1;
8535 g.NavTabbingCounter = offset + 1;
8536 }
8537}
8538
8539void ImGui::SetItemDefaultFocus()
8540{
8541 ImGuiContext& g = *GImGui;
8542 ImGuiWindow* window = g.CurrentWindow;
8543 if (!window->Appearing)
8544 return;
8545 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8546 return;
8547
8548 g.NavInitRequest = false;
8549 NavApplyItemToResult(result: &g.NavInitResult);
8550 NavUpdateAnyRequestFlag();
8551
8552 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8553 if (!window->ClipRect.Contains(r: g.LastItemData.Rect))
8554 ScrollToRectEx(window, rect: g.LastItemData.Rect, flags: ImGuiScrollFlags_None);
8555}
8556
8557void ImGui::SetStateStorage(ImGuiStorage* tree)
8558{
8559 ImGuiWindow* window = GImGui->CurrentWindow;
8560 window->DC.StateStorage = tree ? tree : &window->StateStorage;
8561}
8562
8563ImGuiStorage* ImGui::GetStateStorage()
8564{
8565 ImGuiWindow* window = GImGui->CurrentWindow;
8566 return window->DC.StateStorage;
8567}
8568
8569bool ImGui::IsRectVisible(const ImVec2& size)
8570{
8571 ImGuiWindow* window = GImGui->CurrentWindow;
8572 return window->ClipRect.Overlaps(r: ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8573}
8574
8575bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8576{
8577 ImGuiWindow* window = GImGui->CurrentWindow;
8578 return window->ClipRect.Overlaps(r: ImRect(rect_min, rect_max));
8579}
8580
8581//-----------------------------------------------------------------------------
8582// [SECTION] ID STACK
8583//-----------------------------------------------------------------------------
8584
8585// This is one of the very rare legacy case where we use ImGuiWindow methods,
8586// it should ideally be flattened at some point but it's been used a lots by widgets.
8587ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8588{
8589 ImGuiID seed = IDStack.back();
8590 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
8591#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8592 ImGuiContext& g = *Ctx;
8593 if (g.DebugHookIdInfo == id)
8594 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
8595#endif
8596 return id;
8597}
8598
8599ImGuiID ImGuiWindow::GetID(const void* ptr)
8600{
8601 ImGuiID seed = IDStack.back();
8602 ImGuiID id = ImHashData(data_p: &ptr, data_size: sizeof(void*), seed);
8603#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8604 ImGuiContext& g = *Ctx;
8605 if (g.DebugHookIdInfo == id)
8606 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_Pointer, data_id: ptr, NULL);
8607#endif
8608 return id;
8609}
8610
8611ImGuiID ImGuiWindow::GetID(int n)
8612{
8613 ImGuiID seed = IDStack.back();
8614 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
8615#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8616 ImGuiContext& g = *Ctx;
8617 if (g.DebugHookIdInfo == id)
8618 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
8619#endif
8620 return id;
8621}
8622
8623// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8624ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8625{
8626 ImGuiID seed = IDStack.back();
8627 ImRect r_rel = ImGui::WindowRectAbsToRel(window: this, r: r_abs);
8628 ImGuiID id = ImHashData(data_p: &r_rel, data_size: sizeof(r_rel), seed);
8629 return id;
8630}
8631
8632void ImGui::PushID(const char* str_id)
8633{
8634 ImGuiContext& g = *GImGui;
8635 ImGuiWindow* window = g.CurrentWindow;
8636 ImGuiID id = window->GetID(str: str_id);
8637 window->IDStack.push_back(v: id);
8638}
8639
8640void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8641{
8642 ImGuiContext& g = *GImGui;
8643 ImGuiWindow* window = g.CurrentWindow;
8644 ImGuiID id = window->GetID(str: str_id_begin, str_end: str_id_end);
8645 window->IDStack.push_back(v: id);
8646}
8647
8648void ImGui::PushID(const void* ptr_id)
8649{
8650 ImGuiContext& g = *GImGui;
8651 ImGuiWindow* window = g.CurrentWindow;
8652 ImGuiID id = window->GetID(ptr: ptr_id);
8653 window->IDStack.push_back(v: id);
8654}
8655
8656void ImGui::PushID(int int_id)
8657{
8658 ImGuiContext& g = *GImGui;
8659 ImGuiWindow* window = g.CurrentWindow;
8660 ImGuiID id = window->GetID(n: int_id);
8661 window->IDStack.push_back(v: id);
8662}
8663
8664// Push a given id value ignoring the ID stack as a seed.
8665void ImGui::PushOverrideID(ImGuiID id)
8666{
8667 ImGuiContext& g = *GImGui;
8668 ImGuiWindow* window = g.CurrentWindow;
8669#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8670 if (g.DebugHookIdInfo == id)
8671 DebugHookIdInfo(id, data_type: ImGuiDataType_ID, NULL, NULL);
8672#endif
8673 window->IDStack.push_back(v: id);
8674}
8675
8676// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8677// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8678// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8679ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8680{
8681 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
8682#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8683 ImGuiContext& g = *GImGui;
8684 if (g.DebugHookIdInfo == id)
8685 DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
8686#endif
8687 return id;
8688}
8689
8690ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8691{
8692 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
8693#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8694 ImGuiContext& g = *GImGui;
8695 if (g.DebugHookIdInfo == id)
8696 DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
8697#endif
8698 return id;
8699}
8700
8701void ImGui::PopID()
8702{
8703 ImGuiWindow* window = GImGui->CurrentWindow;
8704 IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8705 window->IDStack.pop_back();
8706}
8707
8708ImGuiID ImGui::GetID(const char* str_id)
8709{
8710 ImGuiWindow* window = GImGui->CurrentWindow;
8711 return window->GetID(str: str_id);
8712}
8713
8714ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8715{
8716 ImGuiWindow* window = GImGui->CurrentWindow;
8717 return window->GetID(str: str_id_begin, str_end: str_id_end);
8718}
8719
8720ImGuiID ImGui::GetID(const void* ptr_id)
8721{
8722 ImGuiWindow* window = GImGui->CurrentWindow;
8723 return window->GetID(ptr: ptr_id);
8724}
8725
8726//-----------------------------------------------------------------------------
8727// [SECTION] INPUTS
8728//-----------------------------------------------------------------------------
8729// - GetKeyData() [Internal]
8730// - GetKeyIndex() [Internal]
8731// - GetKeyName()
8732// - GetKeyChordName() [Internal]
8733// - CalcTypematicRepeatAmount() [Internal]
8734// - GetTypematicRepeatRate() [Internal]
8735// - GetKeyPressedAmount() [Internal]
8736// - GetKeyMagnitude2d() [Internal]
8737//-----------------------------------------------------------------------------
8738// - UpdateKeyRoutingTable() [Internal]
8739// - GetRoutingIdFromOwnerId() [Internal]
8740// - GetShortcutRoutingData() [Internal]
8741// - CalcRoutingScore() [Internal]
8742// - SetShortcutRouting() [Internal]
8743// - TestShortcutRouting() [Internal]
8744//-----------------------------------------------------------------------------
8745// - IsKeyDown()
8746// - IsKeyPressed()
8747// - IsKeyReleased()
8748//-----------------------------------------------------------------------------
8749// - IsMouseDown()
8750// - IsMouseClicked()
8751// - IsMouseReleased()
8752// - IsMouseDoubleClicked()
8753// - GetMouseClickedCount()
8754// - IsMouseHoveringRect() [Internal]
8755// - IsMouseDragPastThreshold() [Internal]
8756// - IsMouseDragging()
8757// - GetMousePos()
8758// - SetMousePos() [Internal]
8759// - GetMousePosOnOpeningCurrentPopup()
8760// - IsMousePosValid()
8761// - IsAnyMouseDown()
8762// - GetMouseDragDelta()
8763// - ResetMouseDragDelta()
8764// - GetMouseCursor()
8765// - SetMouseCursor()
8766//-----------------------------------------------------------------------------
8767// - UpdateAliasKey()
8768// - GetMergedModsFromKeys()
8769// - UpdateKeyboardInputs()
8770// - UpdateMouseInputs()
8771//-----------------------------------------------------------------------------
8772// - LockWheelingWindow [Internal]
8773// - FindBestWheelingWindow [Internal]
8774// - UpdateMouseWheel() [Internal]
8775//-----------------------------------------------------------------------------
8776// - SetNextFrameWantCaptureKeyboard()
8777// - SetNextFrameWantCaptureMouse()
8778//-----------------------------------------------------------------------------
8779// - GetInputSourceName() [Internal]
8780// - DebugPrintInputEvent() [Internal]
8781// - UpdateInputEvents() [Internal]
8782//-----------------------------------------------------------------------------
8783// - GetKeyOwner() [Internal]
8784// - TestKeyOwner() [Internal]
8785// - SetKeyOwner() [Internal]
8786// - SetItemKeyOwner() [Internal]
8787// - Shortcut() [Internal]
8788//-----------------------------------------------------------------------------
8789
8790ImGuiKeyChord ImGui::FixupKeyChord(ImGuiContext* ctx, ImGuiKeyChord key_chord)
8791{
8792 // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8793 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8794 if (IsModKey(key))
8795 {
8796 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
8797 key_chord |= ImGuiMod_Ctrl;
8798 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
8799 key_chord |= ImGuiMod_Shift;
8800 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
8801 key_chord |= ImGuiMod_Alt;
8802 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
8803 key_chord |= ImGuiMod_Super;
8804 }
8805 if (key_chord & ImGuiMod_Shortcut)
8806 return (key_chord & ~ImGuiMod_Shortcut) | (ctx->IO.ConfigMacOSXBehaviors ? ImGuiMod_Super : ImGuiMod_Ctrl);
8807 return key_chord;
8808}
8809
8810ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8811{
8812 ImGuiContext& g = *ctx;
8813
8814 // Special storage location for mods
8815 if (key & ImGuiMod_Mask_)
8816 key = ConvertSingleModFlagToKey(ctx, key);
8817
8818#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8819 IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8820 if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8821 key = (ImGuiKey)g.IO.KeyMap[key]; // Remap native->imgui or imgui->native
8822#else
8823 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8824#endif
8825 return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8826}
8827
8828#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8829ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8830{
8831 ImGuiContext& g = *GImGui;
8832 IM_ASSERT(IsNamedKey(key));
8833 const ImGuiKeyData* key_data = GetKeyData(key);
8834 return (ImGuiKey)(key_data - g.IO.KeysData);
8835}
8836#endif
8837
8838// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8839static const char* const GKeyNames[] =
8840{
8841 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8842 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8843 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8844 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8845 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8846 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8847 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8848 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8849 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8850 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8851 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8852 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8853 "AppBack", "AppForward",
8854 "GamepadStart", "GamepadBack",
8855 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8856 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8857 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8858 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8859 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8860 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8861 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8862};
8863IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8864
8865const char* ImGui::GetKeyName(ImGuiKey key)
8866{
8867 ImGuiContext& g = *GImGui;
8868#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8869 IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8870#else
8871 if (IsLegacyKey(key))
8872 {
8873 if (g.IO.KeyMap[key] == -1)
8874 return "N/A";
8875 IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8876 key = (ImGuiKey)g.IO.KeyMap[key];
8877 }
8878#endif
8879 if (key == ImGuiKey_None)
8880 return "None";
8881 if (key & ImGuiMod_Mask_)
8882 key = ConvertSingleModFlagToKey(ctx: &g, key);
8883 if (!IsNamedKey(key))
8884 return "Unknown";
8885
8886 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8887}
8888
8889// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8890const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
8891{
8892 ImGuiContext& g = *GImGui;
8893 key_chord = FixupKeyChord(ctx: &g, key_chord);
8894 ImFormatString(buf: g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), fmt: "%s%s%s%s%s",
8895 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8896 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8897 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8898 (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8899 GetKeyName(key: (ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8900 return g.TempKeychordName;
8901}
8902
8903// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8904// t1 = current time (e.g.: g.Time)
8905// An event is triggered at:
8906// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
8907int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8908{
8909 if (t1 == 0.0f)
8910 return 1;
8911 if (t0 >= t1)
8912 return 0;
8913 if (repeat_rate <= 0.0f)
8914 return (t0 < repeat_delay) && (t1 >= repeat_delay);
8915 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8916 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8917 const int count = count_t1 - count_t0;
8918 return count;
8919}
8920
8921void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8922{
8923 ImGuiContext& g = *GImGui;
8924 switch (flags & ImGuiInputFlags_RepeatRateMask_)
8925 {
8926 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8927 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8928 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8929 }
8930}
8931
8932// Return value representing the number of presses in the last time period, for the given repeat rate
8933// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8934int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8935{
8936 ImGuiContext& g = *GImGui;
8937 const ImGuiKeyData* key_data = GetKeyData(key);
8938 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)
8939 return 0;
8940 const float t = key_data->DownDuration;
8941 return CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay, repeat_rate);
8942}
8943
8944// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8945ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8946{
8947 return ImVec2(
8948 GetKeyData(key: key_right)->AnalogValue - GetKeyData(key: key_left)->AnalogValue,
8949 GetKeyData(key: key_down)->AnalogValue - GetKeyData(key: key_up)->AnalogValue);
8950}
8951
8952// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8953// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
8954// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
8955// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8956static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8957{
8958 ImGuiContext& g = *GImGui;
8959 rt->EntriesNext.resize(new_size: 0);
8960 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8961 {
8962 const int new_routing_start_idx = rt->EntriesNext.Size;
8963 ImGuiKeyRoutingData* routing_entry;
8964 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8965 {
8966 routing_entry = &rt->Entries[old_routing_idx];
8967 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
8968 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8969 routing_entry->RoutingNext = ImGuiKeyOwner_None;
8970 routing_entry->RoutingNextScore = 255;
8971 if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8972 continue;
8973 rt->EntriesNext.push_back(v: *routing_entry); // Write alive ones into new buffer
8974
8975 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8976 // This is the result of previous frame's SetShortcutRouting() call.
8977 if (routing_entry->Mods == g.IO.KeyMods)
8978 {
8979 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
8980 if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8981 {
8982 owner_data->OwnerCurr = routing_entry->RoutingCurr;
8983 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
8984 }
8985 }
8986 }
8987
8988 // Rewrite linked-list
8989 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8990 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8991 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8992 }
8993 rt->Entries.swap(rhs&: rt->EntriesNext); // Swap new and old indexes
8994}
8995
8996// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8997static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8998{
8999 ImGuiContext& g = *GImGui;
9000 return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9001}
9002
9003ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9004{
9005 // Majority of shortcuts will be Key + any number of Mods
9006 // We accept _Single_ mod with ImGuiKey_None.
9007 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
9008 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
9009 // - Shortcut(ImGuiMod_Ctrl); // Legal
9010 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
9011 ImGuiContext& g = *GImGui;
9012 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9013 ImGuiKeyRoutingData* routing_data;
9014 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9015 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9016 if (key == ImGuiKey_None)
9017 key = ConvertSingleModFlagToKey(ctx: &g, key: mods);
9018 IM_ASSERT(IsNamedKey(key) && (key_chord & ImGuiMod_Shortcut) == 0); // Please call ConvertShortcutMod() in calling function.
9019
9020 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9021 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9022 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9023 {
9024 routing_data = &rt->Entries[idx];
9025 if (routing_data->Mods == mods)
9026 return routing_data;
9027 }
9028
9029 // Add to linked-list
9030 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9031 rt->Entries.push_back(v: ImGuiKeyRoutingData());
9032 routing_data = &rt->Entries[routing_data_idx];
9033 routing_data->Mods = (ImU16)mods;
9034 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9035 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9036 return routing_data;
9037}
9038
9039// Current score encoding (lower is highest priority):
9040// - 0: ImGuiInputFlags_RouteGlobalHigh
9041// - 1: ImGuiInputFlags_RouteFocused (if item active)
9042// - 2: ImGuiInputFlags_RouteGlobal
9043// - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9044// - 254: ImGuiInputFlags_RouteGlobalLow
9045// - 255: never route
9046// 'flags' should include an explicit routing policy
9047static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9048{
9049 if (flags & ImGuiInputFlags_RouteFocused)
9050 {
9051 ImGuiContext& g = *GImGui;
9052
9053 // ActiveID gets top priority
9054 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9055 if (owner_id != 0 && g.ActiveId == owner_id)
9056 return 1;
9057
9058 // Score based on distance to focused window (lower is better)
9059 // Assuming both windows are submitting a routing request,
9060 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9061 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
9062 // Assuming only WindowA is submitting a routing request,
9063 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9064 // This essentially follow the window->ParentWindowForFocusRoute chain.
9065 if (focus_scope_id == 0)
9066 return 255;
9067 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9068 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9069 return 3 + index_in_focus_path;
9070
9071 return 255;
9072 }
9073
9074 // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
9075 if (flags & ImGuiInputFlags_RouteGlobal)
9076 return 2;
9077 if (flags & ImGuiInputFlags_RouteGlobalLow)
9078 return 254;
9079 return 0;
9080}
9081
9082// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9083// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9084static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9085{
9086 // Mimic 'ignore_char_inputs' logic in InputText()
9087 ImGuiContext& g = *GImGui;
9088
9089 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9090 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9091 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Super));
9092 if (ignore_char_inputs)
9093 return false;
9094
9095 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9096 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9097 return g.KeysMayBeCharInput.TestBit(n: key);
9098}
9099
9100// Request a desired route for an input chord (key + mods).
9101// Return true if the route is available this frame.
9102// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9103// (Conceptually this does a "Submit for next frame" + "Test for current frame".
9104// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9105bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9106{
9107 ImGuiContext& g = *GImGui;
9108 if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9109 flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9110 else
9111 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
9112 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_None);
9113
9114 // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9115 key_chord = FixupKeyChord(ctx: &g, key_chord);
9116
9117 // [DEBUG] Debug break requested by user
9118 if (g.DebugBreakInShortcutRouting == key_chord)
9119 IM_DEBUG_BREAK();
9120
9121 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9122 if (g.NavWindow == NULL)
9123 return false;
9124
9125 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9126 if (flags & ImGuiInputFlags_RouteAlways)
9127 {
9128 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> always\n", GetKeyChordName(key_chord), owner_id, flags);
9129 return true;
9130 }
9131
9132 // Specific culling when there's an active.
9133 if (g.ActiveId != 0 && g.ActiveId != owner_id)
9134 {
9135 // Cull shortcuts with no modifiers when it could generate a character.
9136 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9137 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9138 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9139 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9140 if ((flags & ImGuiInputFlags_RouteFocused) && g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9141 {
9142 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> filtered as potential char input\n", GetKeyChordName(key_chord), owner_id, flags);
9143 return false;
9144 }
9145
9146 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9147 if ((flags & ImGuiInputFlags_RouteGlobalHigh) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9148 {
9149 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9150 if (key == ImGuiKey_None)
9151 key = ConvertSingleModFlagToKey(ctx: &g, key: (ImGuiKey)(key_chord & ImGuiMod_Mask_));
9152 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9153 return false;
9154 }
9155 }
9156
9157 // FIXME-SHORTCUT: A way to configure the location/focus-scope to test would render this more flexible.
9158 const int score = CalcRoutingScore(focus_scope_id: g.CurrentFocusScopeId, owner_id, flags);
9159 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> score %d\n", GetKeyChordName(key_chord), owner_id, flags, score);
9160 if (score == 255)
9161 return false;
9162
9163 // Submit routing for NEXT frame (assuming score is sufficient)
9164 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9165 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9166 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9167 if (score < routing_data->RoutingNextScore)
9168 {
9169 routing_data->RoutingNext = owner_id;
9170 routing_data->RoutingNextScore = (ImU8)score;
9171 }
9172
9173 // Return routing state for CURRENT frame
9174 if (routing_data->RoutingCurr == owner_id)
9175 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9176 return routing_data->RoutingCurr == owner_id;
9177}
9178
9179// Currently unused by core (but used by tests)
9180// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9181bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9182{
9183 ImGuiContext& g = *GImGui;
9184 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9185 key_chord = FixupKeyChord(ctx: &g, key_chord);
9186 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9187 return routing_data->RoutingCurr == routing_id;
9188}
9189
9190// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9191// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9192bool ImGui::IsKeyDown(ImGuiKey key)
9193{
9194 return IsKeyDown(key, ImGuiKeyOwner_Any);
9195}
9196
9197bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9198{
9199 const ImGuiKeyData* key_data = GetKeyData(key);
9200 if (!key_data->Down)
9201 return false;
9202 if (!TestKeyOwner(key, owner_id))
9203 return false;
9204 return true;
9205}
9206
9207bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9208{
9209 return IsKeyPressed(key, ImGuiKeyOwner_Any, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9210}
9211
9212// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9213bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9214{
9215 const ImGuiKeyData* key_data = GetKeyData(key);
9216 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)
9217 return false;
9218 const float t = key_data->DownDuration;
9219 if (t < 0.0f)
9220 return false;
9221 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9222 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9223 flags |= ImGuiInputFlags_Repeat;
9224
9225 bool pressed = (t == 0.0f);
9226 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9227 {
9228 float repeat_delay, repeat_rate;
9229 GetTypematicRepeatRate(flags, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
9230 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9231 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9232 {
9233 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9234 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9235 ImGuiContext& g = *GImGui;
9236 double key_pressed_time = g.Time - t + 0.00001f;
9237 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9238 pressed = false;
9239 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9240 pressed = false;
9241 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9242 pressed = false;
9243 }
9244 }
9245 if (!pressed)
9246 return false;
9247 if (!TestKeyOwner(key, owner_id))
9248 return false;
9249 return true;
9250}
9251
9252bool ImGui::IsKeyReleased(ImGuiKey key)
9253{
9254 return IsKeyReleased(key, ImGuiKeyOwner_Any);
9255}
9256
9257bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9258{
9259 const ImGuiKeyData* key_data = GetKeyData(key);
9260 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9261 return false;
9262 if (!TestKeyOwner(key, owner_id))
9263 return false;
9264 return true;
9265}
9266
9267bool ImGui::IsMouseDown(ImGuiMouseButton button)
9268{
9269 ImGuiContext& g = *GImGui;
9270 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9271 return g.IO.MouseDown[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9272}
9273
9274bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9275{
9276 ImGuiContext& g = *GImGui;
9277 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9278 return g.IO.MouseDown[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9279}
9280
9281bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9282{
9283 return IsMouseClicked(button, ImGuiKeyOwner_Any, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9284}
9285
9286bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9287{
9288 ImGuiContext& g = *GImGui;
9289 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9290 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)
9291 return false;
9292 const float t = g.IO.MouseDownDuration[button];
9293 if (t < 0.0f)
9294 return false;
9295 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9296
9297 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9298 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay: g.IO.KeyRepeatDelay, repeat_rate: g.IO.KeyRepeatRate) > 0);
9299 if (!pressed)
9300 return false;
9301
9302 if (!TestKeyOwner(key: MouseButtonToKey(button), owner_id))
9303 return false;
9304
9305 return true;
9306}
9307
9308bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9309{
9310 ImGuiContext& g = *GImGui;
9311 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9312 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9313}
9314
9315bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9316{
9317 ImGuiContext& g = *GImGui;
9318 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9319 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9320}
9321
9322bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9323{
9324 ImGuiContext& g = *GImGui;
9325 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9326 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any);
9327}
9328
9329bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9330{
9331 ImGuiContext& g = *GImGui;
9332 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9333 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), owner_id);
9334}
9335
9336int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9337{
9338 ImGuiContext& g = *GImGui;
9339 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9340 return g.IO.MouseClickedCount[button];
9341}
9342
9343// Test if mouse cursor is hovering given rectangle
9344// NB- Rectangle is clipped by our current clip setting
9345// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9346bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9347{
9348 ImGuiContext& g = *GImGui;
9349
9350 // Clip
9351 ImRect rect_clipped(r_min, r_max);
9352 if (clip)
9353 rect_clipped.ClipWith(r: g.CurrentWindow->ClipRect);
9354
9355 // Hit testing, expanded for touch input
9356 if (!rect_clipped.ContainsWithPad(p: g.IO.MousePos, pad: g.Style.TouchExtraPadding))
9357 return false;
9358 if (!g.MouseViewport->GetMainRect().Overlaps(r: rect_clipped))
9359 return false;
9360 return true;
9361}
9362
9363// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9364// [Internal] This doesn't test if the button is pressed
9365bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9366{
9367 ImGuiContext& g = *GImGui;
9368 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9369 if (lock_threshold < 0.0f)
9370 lock_threshold = g.IO.MouseDragThreshold;
9371 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9372}
9373
9374bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9375{
9376 ImGuiContext& g = *GImGui;
9377 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9378 if (!g.IO.MouseDown[button])
9379 return false;
9380 return IsMouseDragPastThreshold(button, lock_threshold);
9381}
9382
9383ImVec2 ImGui::GetMousePos()
9384{
9385 ImGuiContext& g = *GImGui;
9386 return g.IO.MousePos;
9387}
9388
9389// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9390// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9391void ImGui::TeleportMousePos(const ImVec2& pos)
9392{
9393 ImGuiContext& g = *GImGui;
9394 g.IO.MousePos = g.IO.MousePosPrev = pos;
9395 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9396 g.IO.WantSetMousePos = true;
9397 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9398}
9399
9400// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9401ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9402{
9403 ImGuiContext& g = *GImGui;
9404 if (g.BeginPopupStack.Size > 0)
9405 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9406 return g.IO.MousePos;
9407}
9408
9409// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9410bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9411{
9412 // The assert is only to silence a false-positive in XCode Static Analysis.
9413 // 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).
9414 IM_ASSERT(GImGui != NULL);
9415 const float MOUSE_INVALID = -256000.0f;
9416 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9417 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9418}
9419
9420// [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.
9421bool ImGui::IsAnyMouseDown()
9422{
9423 ImGuiContext& g = *GImGui;
9424 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9425 if (g.IO.MouseDown[n])
9426 return true;
9427 return false;
9428}
9429
9430// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9431// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9432// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9433ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9434{
9435 ImGuiContext& g = *GImGui;
9436 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9437 if (lock_threshold < 0.0f)
9438 lock_threshold = g.IO.MouseDragThreshold;
9439 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9440 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9441 if (IsMousePosValid(mouse_pos: &g.IO.MousePos) && IsMousePosValid(mouse_pos: &g.IO.MouseClickedPos[button]))
9442 return g.IO.MousePos - g.IO.MouseClickedPos[button];
9443 return ImVec2(0.0f, 0.0f);
9444}
9445
9446void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9447{
9448 ImGuiContext& g = *GImGui;
9449 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9450 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9451 g.IO.MouseClickedPos[button] = g.IO.MousePos;
9452}
9453
9454// Get desired mouse cursor shape.
9455// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9456// updated during the frame, and locked in EndFrame()/Render().
9457// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9458ImGuiMouseCursor ImGui::GetMouseCursor()
9459{
9460 ImGuiContext& g = *GImGui;
9461 return g.MouseCursor;
9462}
9463
9464void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9465{
9466 ImGuiContext& g = *GImGui;
9467 g.MouseCursor = cursor_type;
9468}
9469
9470static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9471{
9472 IM_ASSERT(ImGui::IsAliasKey(key));
9473 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9474 key_data->Down = v;
9475 key_data->AnalogValue = analog_value;
9476}
9477
9478// [Internal] Do not use directly
9479static ImGuiKeyChord GetMergedModsFromKeys()
9480{
9481 ImGuiKeyChord mods = 0;
9482 if (ImGui::IsKeyDown(key: ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
9483 if (ImGui::IsKeyDown(key: ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
9484 if (ImGui::IsKeyDown(key: ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
9485 if (ImGui::IsKeyDown(key: ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
9486 return mods;
9487}
9488
9489static void ImGui::UpdateKeyboardInputs()
9490{
9491 ImGuiContext& g = *GImGui;
9492 ImGuiIO& io = g.IO;
9493
9494 // Import legacy keys or verify they are not used
9495#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9496 if (io.BackendUsingLegacyKeyArrays == 0)
9497 {
9498 // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9499 for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9500 IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9501 }
9502 else
9503 {
9504 if (g.FrameCount == 0)
9505 for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9506 IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9507
9508 // Build reverse KeyMap (Named -> Legacy)
9509 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9510 if (io.KeyMap[n] != -1)
9511 {
9512 IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9513 io.KeyMap[io.KeyMap[n]] = n;
9514 }
9515
9516 // Import legacy keys into new ones
9517 for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9518 if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9519 {
9520 const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9521 IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9522 io.KeysData[key].Down = io.KeysDown[n];
9523 if (key != n)
9524 io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9525 io.BackendUsingLegacyKeyArrays = 1;
9526 }
9527 if (io.BackendUsingLegacyKeyArrays == 1)
9528 {
9529 GetKeyData(key: ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9530 GetKeyData(key: ImGuiMod_Shift)->Down = io.KeyShift;
9531 GetKeyData(key: ImGuiMod_Alt)->Down = io.KeyAlt;
9532 GetKeyData(key: ImGuiMod_Super)->Down = io.KeySuper;
9533 }
9534 }
9535#endif
9536
9537 // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9538#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9539 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9540 if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9541 {
9542 #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9543 #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9544 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9545 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9546 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9547 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9548 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9549 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9550 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9551 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9552 MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9553 MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9554 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9555 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9556 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9557 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9558 #undef NAV_MAP_KEY
9559 }
9560#endif
9561
9562 // Update aliases
9563 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9564 UpdateAliasKey(key: MouseButtonToKey(button: n), v: io.MouseDown[n], analog_value: io.MouseDown[n] ? 1.0f : 0.0f);
9565 UpdateAliasKey(key: ImGuiKey_MouseWheelX, v: io.MouseWheelH != 0.0f, analog_value: io.MouseWheelH);
9566 UpdateAliasKey(key: ImGuiKey_MouseWheelY, v: io.MouseWheel != 0.0f, analog_value: io.MouseWheel);
9567
9568 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9569 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9570 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9571 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9572 const ImGuiKeyChord prev_key_mods = io.KeyMods;
9573 io.KeyMods = GetMergedModsFromKeys();
9574 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9575 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9576 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9577 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9578 if (prev_key_mods != io.KeyMods)
9579 g.LastKeyModsChangeTime = g.Time;
9580 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9581 g.LastKeyModsChangeFromNoneTime = g.Time;
9582
9583 // Clear gamepad data if disabled
9584 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9585 for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9586 {
9587 io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9588 io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9589 }
9590
9591 // Update keys
9592 for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9593 {
9594 ImGuiKeyData* key_data = &io.KeysData[i];
9595 key_data->DownDurationPrev = key_data->DownDuration;
9596 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9597 if (key_data->DownDuration == 0.0f)
9598 {
9599 ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9600 if (IsKeyboardKey(key))
9601 g.LastKeyboardKeyPressTime = g.Time;
9602 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9603 g.LastKeyboardKeyPressTime = g.Time;
9604 }
9605 }
9606
9607 // Update keys/input owner (named keys only): one entry per key
9608 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9609 {
9610 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9611 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9612 owner_data->OwnerCurr = owner_data->OwnerNext;
9613 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.
9614 owner_data->OwnerNext = ImGuiKeyOwner_None;
9615 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
9616 }
9617
9618 // Update key routing (for e.g. shortcuts)
9619 UpdateKeyRoutingTable(rt: &g.KeysRoutingTable);
9620}
9621
9622static void ImGui::UpdateMouseInputs()
9623{
9624 ImGuiContext& g = *GImGui;
9625 ImGuiIO& io = g.IO;
9626
9627 // Mouse Wheel swapping flag
9628 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9629 // - We avoid doing it on OSX as it the OS input layer handles this already.
9630 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9631 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9632 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9633
9634 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9635 if (IsMousePosValid(mouse_pos: &io.MousePos))
9636 io.MousePos = g.MouseLastValidPos = ImFloor(v: io.MousePos);
9637
9638 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9639 if (IsMousePosValid(mouse_pos: &io.MousePos) && IsMousePosValid(mouse_pos: &io.MousePosPrev))
9640 io.MouseDelta = io.MousePos - io.MousePosPrev;
9641 else
9642 io.MouseDelta = ImVec2(0.0f, 0.0f);
9643
9644 // Update stationary timer.
9645 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9646 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9647 const bool mouse_stationary = (ImLengthSqr(lhs: io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9648 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9649 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9650
9651 // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9652 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9653 g.NavDisableMouseHover = false;
9654
9655 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9656 {
9657 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9658 io.MouseClickedCount[i] = 0; // Will be filled below
9659 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9660 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9661 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9662 if (io.MouseClicked[i])
9663 {
9664 bool is_repeated_click = false;
9665 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9666 {
9667 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9668 if (ImLengthSqr(lhs: delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9669 is_repeated_click = true;
9670 }
9671 if (is_repeated_click)
9672 io.MouseClickedLastCount[i]++;
9673 else
9674 io.MouseClickedLastCount[i] = 1;
9675 io.MouseClickedTime[i] = g.Time;
9676 io.MouseClickedPos[i] = io.MousePos;
9677 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9678 io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9679 io.MouseDragMaxDistanceSqr[i] = 0.0f;
9680 }
9681 else if (io.MouseDown[i])
9682 {
9683 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9684 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9685 io.MouseDragMaxDistanceSqr[i] = ImMax(lhs: io.MouseDragMaxDistanceSqr[i], rhs: ImLengthSqr(lhs: delta_from_click_pos));
9686 io.MouseDragMaxDistanceAbs[i].x = ImMax(lhs: io.MouseDragMaxDistanceAbs[i].x, rhs: delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9687 io.MouseDragMaxDistanceAbs[i].y = ImMax(lhs: io.MouseDragMaxDistanceAbs[i].y, rhs: delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9688 }
9689
9690 // We provide io.MouseDoubleClicked[] as a legacy service
9691 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9692
9693 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9694 if (io.MouseClicked[i])
9695 g.NavDisableMouseHover = false;
9696 }
9697}
9698
9699static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9700{
9701 ImGuiContext& g = *GImGui;
9702 if (window)
9703 g.WheelingWindowReleaseTimer = ImMin(lhs: g.WheelingWindowReleaseTimer + ImAbs(x: wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, rhs: WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9704 else
9705 g.WheelingWindowReleaseTimer = 0.0f;
9706 if (g.WheelingWindow == window)
9707 return;
9708 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9709 g.WheelingWindow = window;
9710 g.WheelingWindowRefMousePos = g.IO.MousePos;
9711 if (window == NULL)
9712 {
9713 g.WheelingWindowStartFrame = -1;
9714 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9715 }
9716}
9717
9718static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9719{
9720 // For each axis, find window in the hierarchy that may want to use scrolling
9721 ImGuiContext& g = *GImGui;
9722 ImGuiWindow* windows[2] = { NULL, NULL };
9723 for (int axis = 0; axis < 2; axis++)
9724 if (wheel[axis] != 0.0f)
9725 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9726 {
9727 // Bubble up into parent window if:
9728 // - a child window doesn't allow any scrolling.
9729 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9730 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9731 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9732 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9733 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9734 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9735 break; // select this window
9736 }
9737 if (windows[0] == NULL && windows[1] == NULL)
9738 return NULL;
9739
9740 // If there's only one window or only one axis then there's no ambiguity
9741 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9742 return windows[1] ? windows[1] : windows[0];
9743
9744 // If candidate are different windows we need to decide which one to prioritize
9745 // - First frame: only find a winner if one axis is zero.
9746 // - Subsequent frames: only find a winner when one is more than the other.
9747 if (g.WheelingWindowStartFrame == -1)
9748 g.WheelingWindowStartFrame = g.FrameCount;
9749 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9750 {
9751 g.WheelingWindowWheelRemainder = wheel;
9752 return NULL;
9753 }
9754 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9755}
9756
9757// Called by NewFrame()
9758void ImGui::UpdateMouseWheel()
9759{
9760 // Reset the locked window if we move the mouse or after the timer elapses.
9761 // 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)
9762 ImGuiContext& g = *GImGui;
9763 if (g.WheelingWindow != NULL)
9764 {
9765 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9766 if (IsMousePosValid() && ImLengthSqr(lhs: g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9767 g.WheelingWindowReleaseTimer = 0.0f;
9768 if (g.WheelingWindowReleaseTimer <= 0.0f)
9769 LockWheelingWindow(NULL, wheel_amount: 0.0f);
9770 }
9771
9772 ImVec2 wheel;
9773 wheel.x = TestKeyOwner(key: ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9774 wheel.y = TestKeyOwner(key: ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9775
9776 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9777 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9778 if (!mouse_window || mouse_window->Collapsed)
9779 return;
9780
9781 // Zoom / Scale window
9782 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9783 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9784 {
9785 LockWheelingWindow(window: mouse_window, wheel_amount: wheel.y);
9786 ImGuiWindow* window = mouse_window;
9787 const float new_font_scale = ImClamp(v: window->FontWindowScale + g.IO.MouseWheel * 0.10f, mn: 0.50f, mx: 2.50f);
9788 const float scale = new_font_scale / window->FontWindowScale;
9789 window->FontWindowScale = new_font_scale;
9790 if (window == window->RootWindow)
9791 {
9792 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9793 SetWindowPos(window, pos: window->Pos + offset, cond: 0);
9794 window->Size = ImTrunc(v: window->Size * scale);
9795 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
9796 }
9797 return;
9798 }
9799 if (g.IO.KeyCtrl)
9800 return;
9801
9802 // Mouse wheel scrolling
9803 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9804 if (g.IO.MouseWheelRequestAxisSwap)
9805 wheel = ImVec2(wheel.y, 0.0f);
9806
9807 // Maintain a rough average of moving magnitude on both axises
9808 // FIXME: should by based on wall clock time rather than frame-counter
9809 g.WheelingAxisAvg.x = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.x, sample: ImAbs(x: wheel.x), n: 30);
9810 g.WheelingAxisAvg.y = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.y, sample: ImAbs(x: wheel.y), n: 30);
9811
9812 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9813 wheel += g.WheelingWindowWheelRemainder;
9814 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9815 if (wheel.x == 0.0f && wheel.y == 0.0f)
9816 return;
9817
9818 // Mouse wheel scrolling: find target and apply
9819 // - don't renew lock if axis doesn't apply on the window.
9820 // - select a main axis when both axises are being moved.
9821 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9822 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9823 {
9824 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9825 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9826 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9827 if (do_scroll[ImGuiAxis_X])
9828 {
9829 LockWheelingWindow(window, wheel_amount: wheel.x);
9830 float max_step = window->InnerRect.GetWidth() * 0.67f;
9831 float scroll_step = ImTrunc(f: ImMin(lhs: 2 * window->CalcFontSize(), rhs: max_step));
9832 SetScrollX(window, scroll_x: window->Scroll.x - wheel.x * scroll_step);
9833 g.WheelingWindowScrolledFrame = g.FrameCount;
9834 }
9835 if (do_scroll[ImGuiAxis_Y])
9836 {
9837 LockWheelingWindow(window, wheel_amount: wheel.y);
9838 float max_step = window->InnerRect.GetHeight() * 0.67f;
9839 float scroll_step = ImTrunc(f: ImMin(lhs: 5 * window->CalcFontSize(), rhs: max_step));
9840 SetScrollY(window, scroll_y: window->Scroll.y - wheel.y * scroll_step);
9841 g.WheelingWindowScrolledFrame = g.FrameCount;
9842 }
9843 }
9844}
9845
9846void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9847{
9848 ImGuiContext& g = *GImGui;
9849 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9850}
9851
9852void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9853{
9854 ImGuiContext& g = *GImGui;
9855 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9856}
9857
9858#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9859static const char* GetInputSourceName(ImGuiInputSource source)
9860{
9861 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
9862 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9863 return input_source_names[source];
9864}
9865static const char* GetMouseSourceName(ImGuiMouseSource source)
9866{
9867 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9868 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9869 return mouse_source_names[source];
9870}
9871static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9872{
9873 ImGuiContext& g = *GImGui;
9874 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; }
9875 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; }
9876 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; }
9877 if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9878 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; }
9879 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9880 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9881}
9882#endif
9883
9884// Process input queue
9885// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9886// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9887// - 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)
9888void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9889{
9890 ImGuiContext& g = *GImGui;
9891 ImGuiIO& io = g.IO;
9892
9893 // Only trickle chars<>key when working with InputText()
9894 // FIXME: InputText() could parse event trail?
9895 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9896 const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9897
9898 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9899 int mouse_button_changed = 0x00;
9900 ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9901
9902 int event_n = 0;
9903 for (; event_n < g.InputEventsQueue.Size; event_n++)
9904 {
9905 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9906 if (e->Type == ImGuiInputEventType_MousePos)
9907 {
9908 if (g.IO.WantSetMousePos)
9909 continue;
9910 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9911 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9912 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9913 break;
9914 io.MousePos = event_pos;
9915 io.MouseSource = e->MousePos.MouseSource;
9916 mouse_moved = true;
9917 }
9918 else if (e->Type == ImGuiInputEventType_MouseButton)
9919 {
9920 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9921 const ImGuiMouseButton button = e->MouseButton.Button;
9922 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9923 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9924 break;
9925 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9926 break;
9927 io.MouseDown[button] = e->MouseButton.Down;
9928 io.MouseSource = e->MouseButton.MouseSource;
9929 mouse_button_changed |= (1 << button);
9930 }
9931 else if (e->Type == ImGuiInputEventType_MouseWheel)
9932 {
9933 // Trickling Rule: Stop processing queued events if we got multiple action on the event
9934 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9935 break;
9936 io.MouseWheelH += e->MouseWheel.WheelX;
9937 io.MouseWheel += e->MouseWheel.WheelY;
9938 io.MouseSource = e->MouseWheel.MouseSource;
9939 mouse_wheeled = true;
9940 }
9941 else if (e->Type == ImGuiInputEventType_MouseViewport)
9942 {
9943 io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9944 }
9945 else if (e->Type == ImGuiInputEventType_Key)
9946 {
9947 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9948 ImGuiKey key = e->Key.Key;
9949 IM_ASSERT(key != ImGuiKey_None);
9950 ImGuiKeyData* key_data = GetKeyData(key);
9951 const int key_data_index = (int)(key_data - g.IO.KeysData);
9952 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(n: key_data_index) || text_inputted || mouse_button_changed != 0))
9953 break;
9954 key_data->Down = e->Key.Down;
9955 key_data->AnalogValue = e->Key.AnalogValue;
9956 key_changed = true;
9957 key_changed_mask.SetBit(key_data_index);
9958
9959 // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9960#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9961 io.KeysDown[key_data_index] = key_data->Down;
9962 if (io.KeyMap[key_data_index] != -1)
9963 io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9964#endif
9965 }
9966 else if (e->Type == ImGuiInputEventType_Text)
9967 {
9968 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9969 if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9970 break;
9971 unsigned int c = e->Text.Char;
9972 io.InputQueueCharacters.push_back(v: c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9973 if (trickle_interleaved_keys_and_text)
9974 text_inputted = true;
9975 }
9976 else if (e->Type == ImGuiInputEventType_Focus)
9977 {
9978 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9979 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9980 const bool focus_lost = !e->AppFocused.Focused;
9981 io.AppFocusLost = focus_lost;
9982 }
9983 else
9984 {
9985 IM_ASSERT(0 && "Unknown event!");
9986 }
9987 }
9988
9989 // Record trail (for domain-specific applications wanting to access a precise trail)
9990 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9991 for (int n = 0; n < event_n; n++)
9992 g.InputEventsTrail.push_back(v: g.InputEventsQueue[n]);
9993
9994 // [DEBUG]
9995#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9996 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9997 for (int n = 0; n < g.InputEventsQueue.Size; n++)
9998 DebugPrintInputEvent(prefix: n < event_n ? "Processed" : "Remaining", e: &g.InputEventsQueue[n]);
9999#endif
10000
10001 // Remaining events will be processed on the next frame
10002 if (event_n == g.InputEventsQueue.Size)
10003 g.InputEventsQueue.resize(new_size: 0);
10004 else
10005 g.InputEventsQueue.erase(it: g.InputEventsQueue.Data, it_last: g.InputEventsQueue.Data + event_n);
10006
10007 // Clear buttons state when focus is lost
10008 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10009 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10010 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10011 if (g.IO.AppFocusLost)
10012 g.IO.ClearInputKeys();
10013}
10014
10015ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10016{
10017 if (!IsNamedKeyOrModKey(key))
10018 return ImGuiKeyOwner_None;
10019
10020 ImGuiContext& g = *GImGui;
10021 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
10022 ImGuiID owner_id = owner_data->OwnerCurr;
10023
10024 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10025 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10026 return ImGuiKeyOwner_None;
10027
10028 return owner_id;
10029}
10030
10031// TestKeyOwner(..., ID) : (owner == None || owner == ID)
10032// TestKeyOwner(..., None) : (owner == None)
10033// TestKeyOwner(..., Any) : no owner test
10034// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10035bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10036{
10037 if (!IsNamedKeyOrModKey(key))
10038 return true;
10039
10040 ImGuiContext& g = *GImGui;
10041 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10042 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10043 return false;
10044
10045 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
10046 if (owner_id == ImGuiKeyOwner_Any)
10047 return (owner_data->LockThisFrame == false);
10048
10049 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10050 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10051 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10052 if (owner_data->OwnerCurr != owner_id)
10053 {
10054 if (owner_data->LockThisFrame)
10055 return false;
10056 if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
10057 return false;
10058 }
10059
10060 return true;
10061}
10062
10063// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10064// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10065// - SetKeyOwner(..., None) : clears owner
10066// - SetKeyOwner(..., Any, !Lock) : illegal (assert)
10067// - SetKeyOwner(..., Any or None, Lock) : set lock
10068void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10069{
10070 ImGuiContext& g = *GImGui;
10071 IM_ASSERT(IsNamedKeyOrModKey(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)
10072 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10073 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10074
10075 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
10076 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10077
10078 // We cannot lock by default as it would likely break lots of legacy code.
10079 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10080 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10081 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10082}
10083
10084// Rarely used helper
10085void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10086{
10087 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(key: ImGuiMod_Ctrl, owner_id, flags); }
10088 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(key: ImGuiMod_Shift, owner_id, flags); }
10089 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(key: ImGuiMod_Alt, owner_id, flags); }
10090 if (key_chord & ImGuiMod_Super) { SetKeyOwner(key: ImGuiMod_Super, owner_id, flags); }
10091 if (key_chord & ImGuiMod_Shortcut) { SetKeyOwner(key: ImGuiMod_Shortcut, owner_id, flags); }
10092 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner(key: (ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10093}
10094
10095// This is more or less equivalent to:
10096// if (IsItemHovered() || IsItemActive())
10097// SetKeyOwner(key, GetItemID());
10098// 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.
10099// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10100// 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.
10101void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10102{
10103 ImGuiContext& g = *GImGui;
10104 ImGuiID id = g.LastItemData.ID;
10105 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10106 return;
10107 if ((flags & ImGuiInputFlags_CondMask_) == 0)
10108 flags |= ImGuiInputFlags_CondDefault_;
10109 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10110 {
10111 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10112 SetKeyOwner(key, owner_id: id, flags: flags & ~ImGuiInputFlags_CondMask_);
10113 }
10114}
10115
10116// This is the only public API until we expose owner_id versions of the API as replacements.
10117bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10118{
10119 return IsKeyChordPressed(key_chord, owner_id: 0, flags: ImGuiInputFlags_None);
10120}
10121
10122// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10123bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10124{
10125 ImGuiContext& g = *GImGui;
10126 key_chord = FixupKeyChord(ctx: &g, key_chord);
10127 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10128 if (g.IO.KeyMods != mods)
10129 return false;
10130
10131 // Special storage location for mods
10132 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10133 if (key == ImGuiKey_None)
10134 key = ConvertSingleModFlagToKey(ctx: &g, key: mods);
10135 if (!IsKeyPressed(key, owner_id, flags: (flags & ImGuiInputFlags_RepeatMask_)))
10136 return false;
10137 return true;
10138}
10139
10140void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord)
10141{
10142 ImGuiContext& g = *GImGui;
10143 g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10144 g.NextItemData.Shortcut = key_chord;
10145}
10146
10147bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10148{
10149 //ImGuiContext& g = *GImGui;
10150 //IMGUI_DEBUG_LOG("Shortcut(%s, owner_id=0x%08X, flags=%X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), owner_id, flags);
10151
10152 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10153 if ((flags & ImGuiInputFlags_RouteMask_) == 0)
10154 flags |= ImGuiInputFlags_RouteFocused;
10155
10156 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10157 // Effectively makes Shortcut() always input-owner aware.
10158 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_None)
10159 owner_id = GetRoutingIdFromOwnerId(owner_id);
10160
10161 // Submit route
10162 if (!SetShortcutRouting(key_chord, owner_id, flags))
10163 return false;
10164
10165 // Default repeat behavior for Shortcut()
10166 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10167 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10168 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10169
10170 if (!IsKeyChordPressed(key_chord, owner_id, flags))
10171 return false;
10172 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10173 return true;
10174}
10175
10176
10177//-----------------------------------------------------------------------------
10178// [SECTION] ERROR CHECKING
10179//-----------------------------------------------------------------------------
10180
10181// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
10182// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10183// If this triggers you have an issue:
10184// - Most commonly: mismatched headers and compiled code version.
10185// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
10186// The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
10187// which is way it is required you put them in your imconfig file (and not just before including imgui.h).
10188// Otherwise it is possible that different compilation units would see different structure layout
10189bool 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)
10190{
10191 bool error = false;
10192 if (strcmp(s1: version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10193 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10194 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10195 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10196 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10197 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10198 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10199 return !error;
10200}
10201
10202// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10203// This is causing issues and ambiguity and we need to retire that.
10204// See https://github.com/ocornut/imgui/issues/5548 for more details.
10205// [Scenario 1]
10206// Previously this would make the window content size ~200x200:
10207// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK
10208// Instead, please submit an item:
10209// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10210// Alternative:
10211// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10212// [Scenario 2]
10213// For reference this is one of the issue what we aim to fix with this change:
10214// BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10215// The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10216// While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10217void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10218{
10219 ImGuiContext& g = *GImGui;
10220 ImGuiWindow* window = g.CurrentWindow;
10221 IM_ASSERT(window->DC.IsSetPos);
10222 window->DC.IsSetPos = false;
10223#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10224 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10225 return;
10226 if (window->SkipItems)
10227 return;
10228 IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10229#else
10230 window->DC.CursorMaxPos = ImMax(lhs: window->DC.CursorMaxPos, rhs: window->DC.CursorPos);
10231#endif
10232}
10233
10234static void ImGui::ErrorCheckNewFrameSanityChecks()
10235{
10236 ImGuiContext& g = *GImGui;
10237
10238 // Check user IM_ASSERT macro
10239 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10240 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10241 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10242 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
10243 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
10244 if (true) IM_ASSERT(1); else IM_ASSERT(0);
10245
10246 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10247 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10248#ifdef __EMSCRIPTEN__
10249 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10250 g.IO.DeltaTime = 0.00001f;
10251#endif
10252
10253 // Check user data
10254 // (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)
10255 IM_ASSERT(g.Initialized);
10256 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
10257 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10258 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
10259 IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10260 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
10261 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
10262 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
10263 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10264 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10265 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10266#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10267 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10268 IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10269
10270 // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10271 if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10272 IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10273#endif
10274
10275 // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
10276 if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10277 g.IO.ConfigWindowsResizeFromEdges = false;
10278
10279 // 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.
10280 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10281 IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10282 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10283 IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10284
10285 // Perform simple checks: multi-viewport and platform windows support
10286 if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10287 {
10288 if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10289 {
10290 IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10291 IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
10292 IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10293 IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
10294 IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
10295 IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10296 IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10297 IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10298 IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10299 if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10300 IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10301 }
10302 else
10303 {
10304 // Disable feature, our backends do not support it
10305 g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10306 }
10307
10308 // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10309 for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10310 {
10311 IM_UNUSED(mon);
10312 IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10313 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.");
10314 IM_ASSERT(mon.DpiScale != 0.0f);
10315 }
10316 }
10317}
10318
10319static void ImGui::ErrorCheckEndFrameSanityChecks()
10320{
10321 ImGuiContext& g = *GImGui;
10322
10323 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10324 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10325 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10326 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10327 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10328 // while still correctly asserting on mid-frame key press events.
10329 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10330 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10331 IM_UNUSED(key_mods);
10332
10333 // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10334 //ErrorCheckEndFrameRecover();
10335
10336 // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10337 // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10338 if (g.CurrentWindowStack.Size != 1)
10339 {
10340 if (g.CurrentWindowStack.Size > 1)
10341 {
10342 ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10343 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10344 IM_UNUSED(window);
10345 while (g.CurrentWindowStack.Size > 1)
10346 End();
10347 }
10348 else
10349 {
10350 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10351 }
10352 }
10353
10354 IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10355}
10356
10357// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10358// Must be called during or before EndFrame().
10359// This is generally flawed as we are not necessarily End/Popping things in the right order.
10360// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10361// FIXME: Can't recover from interleaved BeginTabBar/Begin
10362void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10363{
10364 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10365 ImGuiContext& g = *GImGui;
10366 while (g.CurrentWindowStack.Size > 0) //-V1044
10367 {
10368 ErrorCheckEndWindowRecover(log_callback, user_data);
10369 ImGuiWindow* window = g.CurrentWindow;
10370 if (g.CurrentWindowStack.Size == 1)
10371 {
10372 IM_ASSERT(window->IsFallbackWindow);
10373 break;
10374 }
10375 if (window->Flags & ImGuiWindowFlags_ChildWindow)
10376 {
10377 if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10378 EndChild();
10379 }
10380 else
10381 {
10382 if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10383 End();
10384 }
10385 }
10386}
10387
10388// Must be called before End()/EndChild()
10389void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10390{
10391 ImGuiContext& g = *GImGui;
10392 while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10393 {
10394 if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10395 EndTable();
10396 }
10397
10398 ImGuiWindow* window = g.CurrentWindow;
10399 ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10400 IM_ASSERT(window != NULL);
10401 while (g.CurrentTabBar != NULL) //-V1044
10402 {
10403 if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10404 EndTabBar();
10405 }
10406 while (window->DC.TreeDepth > 0)
10407 {
10408 if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10409 TreePop();
10410 }
10411 while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10412 {
10413 if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10414 EndGroup();
10415 }
10416 while (window->IDStack.Size > 1)
10417 {
10418 if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10419 PopID();
10420 }
10421 while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10422 {
10423 if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10424 EndDisabled();
10425 }
10426 while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10427 {
10428 if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(idx: g.ColorStack.back().Col));
10429 PopStyleColor();
10430 }
10431 while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10432 {
10433 if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10434 PopItemFlag();
10435 }
10436 while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10437 {
10438 if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10439 PopStyleVar();
10440 }
10441 while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10442 {
10443 if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10444 PopFont();
10445 }
10446 while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10447 {
10448 if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10449 PopFocusScope();
10450 }
10451}
10452
10453// Save current stack sizes for later compare
10454void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10455{
10456 ImGuiContext& g = *ctx;
10457 ImGuiWindow* window = g.CurrentWindow;
10458 SizeOfIDStack = (short)window->IDStack.Size;
10459 SizeOfColorStack = (short)g.ColorStack.Size;
10460 SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10461 SizeOfFontStack = (short)g.FontStack.Size;
10462 SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10463 SizeOfGroupStack = (short)g.GroupStack.Size;
10464 SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10465 SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10466 SizeOfDisabledStack = (short)g.DisabledStackSize;
10467}
10468
10469// Compare to detect usage errors
10470void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10471{
10472 ImGuiContext& g = *ctx;
10473 ImGuiWindow* window = g.CurrentWindow;
10474 IM_UNUSED(window);
10475
10476 // Window stacks
10477 // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10478 IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
10479
10480 // Global stacks
10481 // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10482 IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
10483 IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10484 IM_ASSERT(SizeOfDisabledStack == g.DisabledStackSize && "BeginDisabled/EndDisabled Mismatch!");
10485 IM_ASSERT(SizeOfItemFlagsStack >= g.ItemFlagsStack.Size && "PushItemFlag/PopItemFlag Mismatch!");
10486 IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
10487 IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
10488 IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
10489 IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
10490}
10491
10492//-----------------------------------------------------------------------------
10493// [SECTION] ITEM SUBMISSION
10494//-----------------------------------------------------------------------------
10495// - KeepAliveID()
10496// - ItemHandleShortcut() [Internal]
10497// - ItemAdd()
10498//-----------------------------------------------------------------------------
10499
10500// 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().
10501void ImGui::KeepAliveID(ImGuiID id)
10502{
10503 ImGuiContext& g = *GImGui;
10504 if (g.ActiveId == id)
10505 g.ActiveIdIsAlive = id;
10506 if (g.ActiveIdPreviousFrame == id)
10507 g.ActiveIdPreviousFrameIsAlive = true;
10508}
10509
10510static void ItemHandleShortcut(ImGuiID id)
10511{
10512 // FIXME: Generalize Activation queue?
10513 ImGuiContext& g = *GImGui;
10514 if (ImGui::Shortcut(key_chord: g.NextItemData.Shortcut, owner_id: id, flags: ImGuiInputFlags_None) && g.NavActivateId == 0)
10515 {
10516 g.NavActivateId = id; // Will effectively disable clipping.
10517 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10518 if (g.ActiveId == 0 || g.ActiveId == id)
10519 g.NavActivateDownId = g.NavActivatePressedId = id;
10520 ImGui::NavHighlightActivated(id);
10521 }
10522}
10523
10524// Declare item bounding box for clipping and interaction.
10525// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10526// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10527// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10528bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10529{
10530 ImGuiContext& g = *GImGui;
10531 ImGuiWindow* window = g.CurrentWindow;
10532
10533 // Set item data
10534 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10535 g.LastItemData.ID = id;
10536 g.LastItemData.Rect = bb;
10537 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10538 g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10539 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10540 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10541
10542 if (id != 0)
10543 {
10544 KeepAliveID(id);
10545
10546 // Directional navigation processing
10547 // Runs prior to clipping early-out
10548 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10549 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10550 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10551 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10552 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10553 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10554 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10555 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10556 if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10557 {
10558 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10559 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10560 if (g.NavId == id || g.NavAnyRequest)
10561 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10562 if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10563 NavProcessItem();
10564 }
10565
10566 if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10567 ItemHandleShortcut(id);
10568 }
10569
10570 // Lightweight clear of SetNextItemXXX data.
10571 g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10572 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10573
10574#ifdef IMGUI_ENABLE_TEST_ENGINE
10575 if (id != 0)
10576 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10577#endif
10578
10579 // Clipping test
10580 // (this is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10581 //const bool is_clipped = IsClippedEx(bb, id);
10582 //if (is_clipped)
10583 // return false;
10584 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10585 const bool is_rect_visible = bb.Overlaps(r: window->ClipRect);
10586 if (!is_rect_visible)
10587 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10588 if (!g.LogEnabled)
10589 return false;
10590
10591 // [DEBUG]
10592#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10593 if (id != 0)
10594 {
10595 if (id == g.DebugLocateId)
10596 DebugLocateItemResolveWithLastItem();
10597
10598 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10599 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10600 // READ THE FAQ: https://dearimgui.com/faq
10601 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!");
10602 }
10603 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10604 //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10605 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10606#endif
10607
10608 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10609 if (is_rect_visible)
10610 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10611 if (IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
10612 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10613 return true;
10614}
10615
10616
10617//-----------------------------------------------------------------------------
10618// [SECTION] LAYOUT
10619//-----------------------------------------------------------------------------
10620// - ItemSize()
10621// - SameLine()
10622// - GetCursorScreenPos()
10623// - SetCursorScreenPos()
10624// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10625// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10626// - GetCursorStartPos()
10627// - Indent()
10628// - Unindent()
10629// - SetNextItemWidth()
10630// - PushItemWidth()
10631// - PushMultiItemsWidths()
10632// - PopItemWidth()
10633// - CalcItemWidth()
10634// - CalcItemSize()
10635// - GetTextLineHeight()
10636// - GetTextLineHeightWithSpacing()
10637// - GetFrameHeight()
10638// - GetFrameHeightWithSpacing()
10639// - GetContentRegionMax()
10640// - GetContentRegionMaxAbs() [Internal]
10641// - GetContentRegionAvail(),
10642// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10643// - BeginGroup()
10644// - EndGroup()
10645// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10646//-----------------------------------------------------------------------------
10647
10648// Advance cursor given item size for layout.
10649// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10650// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10651// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10652void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10653{
10654 ImGuiContext& g = *GImGui;
10655 ImGuiWindow* window = g.CurrentWindow;
10656 if (window->SkipItems)
10657 return;
10658
10659 // We increase the height in this function to accommodate for baseline offset.
10660 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10661 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10662 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(lhs: 0.0f, rhs: window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10663
10664 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10665 const float line_height = ImMax(lhs: window->DC.CurrLineSize.y, /*ImMax(*/rhs: window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10666
10667 // Always align ourselves on pixel boundaries
10668 //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]
10669 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10670 window->DC.CursorPosPrevLine.y = line_y1;
10671 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
10672 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
10673 window->DC.CursorMaxPos.x = ImMax(lhs: window->DC.CursorMaxPos.x, rhs: window->DC.CursorPosPrevLine.x);
10674 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10675 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10676
10677 window->DC.PrevLineSize.y = line_height;
10678 window->DC.CurrLineSize.y = 0.0f;
10679 window->DC.PrevLineTextBaseOffset = ImMax(lhs: window->DC.CurrLineTextBaseOffset, rhs: text_baseline_y);
10680 window->DC.CurrLineTextBaseOffset = 0.0f;
10681 window->DC.IsSameLine = window->DC.IsSetPos = false;
10682
10683 // Horizontal layout mode
10684 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10685 SameLine();
10686}
10687
10688// Gets back to previous line and continue with horizontal layout
10689// offset_from_start_x == 0 : follow right after previous item
10690// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10691// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10692// spacing_w >= 0 : enforce spacing amount
10693void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10694{
10695 ImGuiContext& g = *GImGui;
10696 ImGuiWindow* window = g.CurrentWindow;
10697 if (window->SkipItems)
10698 return;
10699
10700 if (offset_from_start_x != 0.0f)
10701 {
10702 if (spacing_w < 0.0f)
10703 spacing_w = 0.0f;
10704 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10705 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10706 }
10707 else
10708 {
10709 if (spacing_w < 0.0f)
10710 spacing_w = g.Style.ItemSpacing.x;
10711 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10712 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10713 }
10714 window->DC.CurrLineSize = window->DC.PrevLineSize;
10715 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10716 window->DC.IsSameLine = true;
10717}
10718
10719ImVec2 ImGui::GetCursorScreenPos()
10720{
10721 ImGuiWindow* window = GetCurrentWindowRead();
10722 return window->DC.CursorPos;
10723}
10724
10725void ImGui::SetCursorScreenPos(const ImVec2& pos)
10726{
10727 ImGuiWindow* window = GetCurrentWindow();
10728 window->DC.CursorPos = pos;
10729 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10730 window->DC.IsSetPos = true;
10731}
10732
10733// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10734// 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'.
10735ImVec2 ImGui::GetCursorPos()
10736{
10737 ImGuiWindow* window = GetCurrentWindowRead();
10738 return window->DC.CursorPos - window->Pos + window->Scroll;
10739}
10740
10741float ImGui::GetCursorPosX()
10742{
10743 ImGuiWindow* window = GetCurrentWindowRead();
10744 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10745}
10746
10747float ImGui::GetCursorPosY()
10748{
10749 ImGuiWindow* window = GetCurrentWindowRead();
10750 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10751}
10752
10753void ImGui::SetCursorPos(const ImVec2& local_pos)
10754{
10755 ImGuiWindow* window = GetCurrentWindow();
10756 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10757 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10758 window->DC.IsSetPos = true;
10759}
10760
10761void ImGui::SetCursorPosX(float x)
10762{
10763 ImGuiWindow* window = GetCurrentWindow();
10764 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10765 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10766 window->DC.IsSetPos = true;
10767}
10768
10769void ImGui::SetCursorPosY(float y)
10770{
10771 ImGuiWindow* window = GetCurrentWindow();
10772 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10773 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10774 window->DC.IsSetPos = true;
10775}
10776
10777ImVec2 ImGui::GetCursorStartPos()
10778{
10779 ImGuiWindow* window = GetCurrentWindowRead();
10780 return window->DC.CursorStartPos - window->Pos;
10781}
10782
10783void ImGui::Indent(float indent_w)
10784{
10785 ImGuiContext& g = *GImGui;
10786 ImGuiWindow* window = GetCurrentWindow();
10787 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10788 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10789}
10790
10791void ImGui::Unindent(float indent_w)
10792{
10793 ImGuiContext& g = *GImGui;
10794 ImGuiWindow* window = GetCurrentWindow();
10795 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10796 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10797}
10798
10799// Affect large frame+labels widgets only.
10800void ImGui::SetNextItemWidth(float item_width)
10801{
10802 ImGuiContext& g = *GImGui;
10803 g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10804 g.NextItemData.Width = item_width;
10805}
10806
10807// FIXME: Remove the == 0.0f behavior?
10808void ImGui::PushItemWidth(float item_width)
10809{
10810 ImGuiContext& g = *GImGui;
10811 ImGuiWindow* window = g.CurrentWindow;
10812 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
10813 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10814 g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10815}
10816
10817void ImGui::PushMultiItemsWidths(int components, float w_full)
10818{
10819 ImGuiContext& g = *GImGui;
10820 ImGuiWindow* window = g.CurrentWindow;
10821 IM_ASSERT(components > 0);
10822 const ImGuiStyle& style = g.Style;
10823 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
10824 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
10825 float prev_split = w_items;
10826 for (int i = components - 1; i > 0; i--)
10827 {
10828 float next_split = IM_TRUNC(w_items * i / components);
10829 window->DC.ItemWidthStack.push_back(v: ImMax(lhs: prev_split - next_split, rhs: 1.0f));
10830 prev_split = next_split;
10831 }
10832 window->DC.ItemWidth = ImMax(lhs: prev_split, rhs: 1.0f);
10833 g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10834}
10835
10836void ImGui::PopItemWidth()
10837{
10838 ImGuiWindow* window = GetCurrentWindow();
10839 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10840 window->DC.ItemWidthStack.pop_back();
10841}
10842
10843// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10844// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10845float ImGui::CalcItemWidth()
10846{
10847 ImGuiContext& g = *GImGui;
10848 ImGuiWindow* window = g.CurrentWindow;
10849 float w;
10850 if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10851 w = g.NextItemData.Width;
10852 else
10853 w = window->DC.ItemWidth;
10854 if (w < 0.0f)
10855 {
10856 float region_max_x = GetContentRegionMaxAbs().x;
10857 w = ImMax(lhs: 1.0f, rhs: region_max_x - window->DC.CursorPos.x + w);
10858 }
10859 w = IM_TRUNC(w);
10860 return w;
10861}
10862
10863// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10864// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10865// Note that only CalcItemWidth() is publicly exposed.
10866// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10867ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10868{
10869 ImGuiContext& g = *GImGui;
10870 ImGuiWindow* window = g.CurrentWindow;
10871
10872 ImVec2 region_max;
10873 if (size.x < 0.0f || size.y < 0.0f)
10874 region_max = GetContentRegionMaxAbs();
10875
10876 if (size.x == 0.0f)
10877 size.x = default_w;
10878 else if (size.x < 0.0f)
10879 size.x = ImMax(lhs: 4.0f, rhs: region_max.x - window->DC.CursorPos.x + size.x);
10880
10881 if (size.y == 0.0f)
10882 size.y = default_h;
10883 else if (size.y < 0.0f)
10884 size.y = ImMax(lhs: 4.0f, rhs: region_max.y - window->DC.CursorPos.y + size.y);
10885
10886 return size;
10887}
10888
10889float ImGui::GetTextLineHeight()
10890{
10891 ImGuiContext& g = *GImGui;
10892 return g.FontSize;
10893}
10894
10895float ImGui::GetTextLineHeightWithSpacing()
10896{
10897 ImGuiContext& g = *GImGui;
10898 return g.FontSize + g.Style.ItemSpacing.y;
10899}
10900
10901float ImGui::GetFrameHeight()
10902{
10903 ImGuiContext& g = *GImGui;
10904 return g.FontSize + g.Style.FramePadding.y * 2.0f;
10905}
10906
10907float ImGui::GetFrameHeightWithSpacing()
10908{
10909 ImGuiContext& g = *GImGui;
10910 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10911}
10912
10913// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10914
10915// FIXME: This is in window space (not screen space!).
10916ImVec2 ImGui::GetContentRegionMax()
10917{
10918 ImGuiContext& g = *GImGui;
10919 ImGuiWindow* window = g.CurrentWindow;
10920 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10921 return mx - window->Pos;
10922}
10923
10924// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10925ImVec2 ImGui::GetContentRegionMaxAbs()
10926{
10927 ImGuiContext& g = *GImGui;
10928 ImGuiWindow* window = g.CurrentWindow;
10929 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10930 return mx;
10931}
10932
10933ImVec2 ImGui::GetContentRegionAvail()
10934{
10935 ImGuiWindow* window = GImGui->CurrentWindow;
10936 return GetContentRegionMaxAbs() - window->DC.CursorPos;
10937}
10938
10939// In window space (not screen space!)
10940ImVec2 ImGui::GetWindowContentRegionMin()
10941{
10942 ImGuiWindow* window = GImGui->CurrentWindow;
10943 return window->ContentRegionRect.Min - window->Pos;
10944}
10945
10946ImVec2 ImGui::GetWindowContentRegionMax()
10947{
10948 ImGuiWindow* window = GImGui->CurrentWindow;
10949 return window->ContentRegionRect.Max - window->Pos;
10950}
10951
10952// 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.)
10953// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10954// FIXME-OPT: Could we safely early out on ->SkipItems?
10955void ImGui::BeginGroup()
10956{
10957 ImGuiContext& g = *GImGui;
10958 ImGuiWindow* window = g.CurrentWindow;
10959
10960 g.GroupStack.resize(new_size: g.GroupStack.Size + 1);
10961 ImGuiGroupData& group_data = g.GroupStack.back();
10962 group_data.WindowID = window->ID;
10963 group_data.BackupCursorPos = window->DC.CursorPos;
10964 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10965 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10966 group_data.BackupIndent = window->DC.Indent;
10967 group_data.BackupGroupOffset = window->DC.GroupOffset;
10968 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10969 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10970 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10971 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10972 group_data.BackupIsSameLine = window->DC.IsSameLine;
10973 group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10974 group_data.EmitItem = true;
10975
10976 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10977 window->DC.Indent = window->DC.GroupOffset;
10978 window->DC.CursorMaxPos = window->DC.CursorPos;
10979 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10980 if (g.LogEnabled)
10981 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10982}
10983
10984void ImGui::EndGroup()
10985{
10986 ImGuiContext& g = *GImGui;
10987 ImGuiWindow* window = g.CurrentWindow;
10988 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10989
10990 ImGuiGroupData& group_data = g.GroupStack.back();
10991 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10992
10993 if (window->DC.IsSetPos)
10994 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10995
10996 ImRect group_bb(group_data.BackupCursorPos, ImMax(lhs: window->DC.CursorMaxPos, rhs: group_data.BackupCursorPos));
10997
10998 window->DC.CursorPos = group_data.BackupCursorPos;
10999 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11000 window->DC.CursorMaxPos = ImMax(lhs: group_data.BackupCursorMaxPos, rhs: window->DC.CursorMaxPos);
11001 window->DC.Indent = group_data.BackupIndent;
11002 window->DC.GroupOffset = group_data.BackupGroupOffset;
11003 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11004 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11005 window->DC.IsSameLine = group_data.BackupIsSameLine;
11006 if (g.LogEnabled)
11007 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11008
11009 if (!group_data.EmitItem)
11010 {
11011 g.GroupStack.pop_back();
11012 return;
11013 }
11014
11015 window->DC.CurrLineTextBaseOffset = ImMax(lhs: window->DC.PrevLineTextBaseOffset, rhs: group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11016 ItemSize(size: group_bb.GetSize());
11017 ItemAdd(bb: group_bb, id: 0, NULL, extra_flags: ImGuiItemFlags_NoTabStop);
11018
11019 // 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.
11020 // 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.
11021 // Also if you grep for LastItemId you'll notice it is only used in that context.
11022 // (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.)
11023 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11024 const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11025 if (group_contains_curr_active_id)
11026 g.LastItemData.ID = g.ActiveId;
11027 else if (group_contains_prev_active_id)
11028 g.LastItemData.ID = g.ActiveIdPreviousFrame;
11029 g.LastItemData.Rect = group_bb;
11030
11031 // Forward Hovered flag
11032 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11033 if (group_contains_curr_hovered_id)
11034 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11035
11036 // Forward Edited flag
11037 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11038 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11039
11040 // Forward Deactivated flag
11041 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11042 if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11043 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11044
11045 g.GroupStack.pop_back();
11046 if (g.DebugShowGroupRects)
11047 window->DrawList->AddRect(p_min: group_bb.Min, p_max: group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
11048}
11049
11050
11051//-----------------------------------------------------------------------------
11052// [SECTION] SCROLLING
11053//-----------------------------------------------------------------------------
11054
11055// Helper to snap on edges when aiming at an item very close to the edge,
11056// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11057// When we refactor the scrolling API this may be configurable with a flag?
11058// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11059static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11060{
11061 if (target <= snap_min + snap_threshold)
11062 return ImLerp(a: snap_min, b: target, t: center_ratio);
11063 if (target >= snap_max - snap_threshold)
11064 return ImLerp(a: target, b: snap_max, t: center_ratio);
11065 return target;
11066}
11067
11068static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11069{
11070 ImVec2 scroll = window->Scroll;
11071 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11072 for (int axis = 0; axis < 2; axis++)
11073 {
11074 if (window->ScrollTarget[axis] < FLT_MAX)
11075 {
11076 float center_ratio = window->ScrollTargetCenterRatio[axis];
11077 float scroll_target = window->ScrollTarget[axis];
11078 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11079 {
11080 float snap_min = 0.0f;
11081 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11082 scroll_target = CalcScrollEdgeSnap(target: scroll_target, snap_min, snap_max, snap_threshold: window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11083 }
11084 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11085 }
11086 scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11087 if (!window->Collapsed && !window->SkipItems)
11088 scroll[axis] = ImMin(lhs: scroll[axis], rhs: window->ScrollMax[axis]);
11089 }
11090 return scroll;
11091}
11092
11093void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11094{
11095 ImGuiContext& g = *GImGui;
11096 ImGuiWindow* window = g.CurrentWindow;
11097 ScrollToRectEx(window, rect: g.LastItemData.NavRect, flags);
11098}
11099
11100void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11101{
11102 ScrollToRectEx(window, rect: item_rect, flags);
11103}
11104
11105// Scroll to keep newly navigated item fully into view
11106ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11107{
11108 ImGuiContext& g = *GImGui;
11109 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11110 scroll_rect.Min.x = ImMin(lhs: scroll_rect.Min.x + window->DecoInnerSizeX1, rhs: scroll_rect.Max.x);
11111 scroll_rect.Min.y = ImMin(lhs: scroll_rect.Min.y + window->DecoInnerSizeY1, rhs: scroll_rect.Max.y);
11112 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11113 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11114
11115 // Check that only one behavior is selected per axis
11116 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11117 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11118
11119 // Defaults
11120 ImGuiScrollFlags in_flags = flags;
11121 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11122 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11123 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11124 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11125
11126 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11127 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11128 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;
11129 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;
11130
11131 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11132 {
11133 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11134 SetScrollFromPosX(window, local_x: item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 0.0f);
11135 else if (item_rect.Max.x >= scroll_rect.Max.x)
11136 SetScrollFromPosX(window, local_x: item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 1.0f);
11137 }
11138 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11139 {
11140 if (can_be_fully_visible_x)
11141 SetScrollFromPosX(window, local_x: ImTrunc(f: (item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, center_x_ratio: 0.5f);
11142 else
11143 SetScrollFromPosX(window, local_x: item_rect.Min.x - window->Pos.x, center_x_ratio: 0.0f);
11144 }
11145
11146 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11147 {
11148 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11149 SetScrollFromPosY(window, local_y: item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 0.0f);
11150 else if (item_rect.Max.y >= scroll_rect.Max.y)
11151 SetScrollFromPosY(window, local_y: item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 1.0f);
11152 }
11153 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11154 {
11155 if (can_be_fully_visible_y)
11156 SetScrollFromPosY(window, local_y: ImTrunc(f: (item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, center_y_ratio: 0.5f);
11157 else
11158 SetScrollFromPosY(window, local_y: item_rect.Min.y - window->Pos.y, center_y_ratio: 0.0f);
11159 }
11160
11161 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11162 ImVec2 delta_scroll = next_scroll - window->Scroll;
11163
11164 // Also scroll parent window to keep us into view if necessary
11165 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11166 {
11167 // FIXME-SCROLL: May be an option?
11168 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11169 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11170 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11171 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11172 delta_scroll += ScrollToRectEx(window: window->ParentWindow, item_rect: ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), flags: in_flags);
11173 }
11174
11175 return delta_scroll;
11176}
11177
11178float ImGui::GetScrollX()
11179{
11180 ImGuiWindow* window = GImGui->CurrentWindow;
11181 return window->Scroll.x;
11182}
11183
11184float ImGui::GetScrollY()
11185{
11186 ImGuiWindow* window = GImGui->CurrentWindow;
11187 return window->Scroll.y;
11188}
11189
11190float ImGui::GetScrollMaxX()
11191{
11192 ImGuiWindow* window = GImGui->CurrentWindow;
11193 return window->ScrollMax.x;
11194}
11195
11196float ImGui::GetScrollMaxY()
11197{
11198 ImGuiWindow* window = GImGui->CurrentWindow;
11199 return window->ScrollMax.y;
11200}
11201
11202void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11203{
11204 window->ScrollTarget.x = scroll_x;
11205 window->ScrollTargetCenterRatio.x = 0.0f;
11206 window->ScrollTargetEdgeSnapDist.x = 0.0f;
11207}
11208
11209void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11210{
11211 window->ScrollTarget.y = scroll_y;
11212 window->ScrollTargetCenterRatio.y = 0.0f;
11213 window->ScrollTargetEdgeSnapDist.y = 0.0f;
11214}
11215
11216void ImGui::SetScrollX(float scroll_x)
11217{
11218 ImGuiContext& g = *GImGui;
11219 SetScrollX(window: g.CurrentWindow, scroll_x);
11220}
11221
11222void ImGui::SetScrollY(float scroll_y)
11223{
11224 ImGuiContext& g = *GImGui;
11225 SetScrollY(window: g.CurrentWindow, scroll_y);
11226}
11227
11228// Note that a local position will vary depending on initial scroll value,
11229// This is a little bit confusing so bear with us:
11230// - local_pos = (absolution_pos - window->Pos)
11231// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11232// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11233// - They mostly exist because of legacy API.
11234// Following the rules above, when trying to work with scrolling code, consider that:
11235// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11236// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11237// 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
11238void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11239{
11240 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11241 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11242 window->ScrollTargetCenterRatio.x = center_x_ratio;
11243 window->ScrollTargetEdgeSnapDist.x = 0.0f;
11244}
11245
11246void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11247{
11248 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11249 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11250 window->ScrollTargetCenterRatio.y = center_y_ratio;
11251 window->ScrollTargetEdgeSnapDist.y = 0.0f;
11252}
11253
11254void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11255{
11256 ImGuiContext& g = *GImGui;
11257 SetScrollFromPosX(window: g.CurrentWindow, local_x, center_x_ratio);
11258}
11259
11260void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11261{
11262 ImGuiContext& g = *GImGui;
11263 SetScrollFromPosY(window: g.CurrentWindow, local_y, center_y_ratio);
11264}
11265
11266// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11267void ImGui::SetScrollHereX(float center_x_ratio)
11268{
11269 ImGuiContext& g = *GImGui;
11270 ImGuiWindow* window = g.CurrentWindow;
11271 float spacing_x = ImMax(lhs: window->WindowPadding.x, rhs: g.Style.ItemSpacing.x);
11272 float target_pos_x = ImLerp(a: g.LastItemData.Rect.Min.x - spacing_x, b: g.LastItemData.Rect.Max.x + spacing_x, t: center_x_ratio);
11273 SetScrollFromPosX(window, local_x: target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11274
11275 // Tweak: snap on edges when aiming at an item very close to the edge
11276 window->ScrollTargetEdgeSnapDist.x = ImMax(lhs: 0.0f, rhs: window->WindowPadding.x - spacing_x);
11277}
11278
11279// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11280void ImGui::SetScrollHereY(float center_y_ratio)
11281{
11282 ImGuiContext& g = *GImGui;
11283 ImGuiWindow* window = g.CurrentWindow;
11284 float spacing_y = ImMax(lhs: window->WindowPadding.y, rhs: g.Style.ItemSpacing.y);
11285 float target_pos_y = ImLerp(a: window->DC.CursorPosPrevLine.y - spacing_y, b: window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, t: center_y_ratio);
11286 SetScrollFromPosY(window, local_y: target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11287
11288 // Tweak: snap on edges when aiming at an item very close to the edge
11289 window->ScrollTargetEdgeSnapDist.y = ImMax(lhs: 0.0f, rhs: window->WindowPadding.y - spacing_y);
11290}
11291
11292//-----------------------------------------------------------------------------
11293// [SECTION] TOOLTIPS
11294//-----------------------------------------------------------------------------
11295
11296bool ImGui::BeginTooltip()
11297{
11298 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
11299}
11300
11301bool ImGui::BeginItemTooltip()
11302{
11303 if (!IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
11304 return false;
11305 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
11306}
11307
11308bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11309{
11310 ImGuiContext& g = *GImGui;
11311
11312 if (g.DragDropWithinSource || g.DragDropWithinTarget)
11313 {
11314 // Drag and Drop tooltips are positioning differently than other tooltips:
11315 // - offset visibility to increase visibility around mouse.
11316 // - never clamp within outer viewport boundary.
11317 // We call SetNextWindowPos() to enforce position and disable clamping.
11318 // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11319 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11320 ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11321 SetNextWindowPos(pos: tooltip_pos);
11322 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11323 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11324 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11325 }
11326
11327 char window_name[16];
11328 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: "##Tooltip_%02d", g.TooltipOverrideCount);
11329 if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11330 if (ImGuiWindow* window = FindWindowByName(name: window_name))
11331 if (window->Active)
11332 {
11333 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11334 SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11335 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: "##Tooltip_%02d", ++g.TooltipOverrideCount);
11336 }
11337 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11338 Begin(name: window_name, NULL, flags: flags | extra_window_flags);
11339 // 2023-03-09: Added bool return value to the API, but currently always returning true.
11340 // If this ever returns false we need to update BeginDragDropSource() accordingly.
11341 //if (!ret)
11342 // End();
11343 //return ret;
11344 return true;
11345}
11346
11347void ImGui::EndTooltip()
11348{
11349 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
11350 End();
11351}
11352
11353void ImGui::SetTooltip(const char* fmt, ...)
11354{
11355 va_list args;
11356 va_start(args, fmt);
11357 SetTooltipV(fmt, args);
11358 va_end(args);
11359}
11360
11361void ImGui::SetTooltipV(const char* fmt, va_list args)
11362{
11363 if (!BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_OverridePrevious, extra_window_flags: ImGuiWindowFlags_None))
11364 return;
11365 TextV(fmt, args);
11366 EndTooltip();
11367}
11368
11369// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11370// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11371void ImGui::SetItemTooltip(const char* fmt, ...)
11372{
11373 va_list args;
11374 va_start(args, fmt);
11375 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
11376 SetTooltipV(fmt, args);
11377 va_end(args);
11378}
11379
11380void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11381{
11382 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
11383 SetTooltipV(fmt, args);
11384}
11385
11386
11387//-----------------------------------------------------------------------------
11388// [SECTION] POPUPS
11389//-----------------------------------------------------------------------------
11390
11391// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11392bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11393{
11394 ImGuiContext& g = *GImGui;
11395 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11396 {
11397 // Return true if any popup is open at the current BeginPopup() level of the popup stack
11398 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11399 IM_ASSERT(id == 0);
11400 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11401 return g.OpenPopupStack.Size > 0;
11402 else
11403 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11404 }
11405 else
11406 {
11407 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11408 {
11409 // Return true if the popup is open anywhere in the popup stack
11410 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11411 if (popup_data.PopupId == id)
11412 return true;
11413 return false;
11414 }
11415 else
11416 {
11417 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11418 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11419 }
11420 }
11421}
11422
11423bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11424{
11425 ImGuiContext& g = *GImGui;
11426 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str: str_id);
11427 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11428 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11429 return IsPopupOpen(id, popup_flags);
11430}
11431
11432// Also see FindBlockingModal(NULL)
11433ImGuiWindow* ImGui::GetTopMostPopupModal()
11434{
11435 ImGuiContext& g = *GImGui;
11436 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11437 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11438 if (popup->Flags & ImGuiWindowFlags_Modal)
11439 return popup;
11440 return NULL;
11441}
11442
11443// See Demo->Stacked Modal to confirm what this is for.
11444ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11445{
11446 ImGuiContext& g = *GImGui;
11447 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11448 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11449 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(window: popup))
11450 return popup;
11451 return NULL;
11452}
11453
11454void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11455{
11456 ImGuiContext& g = *GImGui;
11457 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
11458 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11459 OpenPopupEx(id, popup_flags);
11460}
11461
11462void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11463{
11464 OpenPopupEx(id, popup_flags);
11465}
11466
11467// Mark popup as open (toggle toward open state).
11468// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11469// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11470// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11471void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11472{
11473 ImGuiContext& g = *GImGui;
11474 ImGuiWindow* parent_window = g.CurrentWindow;
11475 const int current_stack_size = g.BeginPopupStack.Size;
11476
11477 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11478 if (IsPopupOpen(id: (ImGuiID)0, popup_flags: ImGuiPopupFlags_AnyPopupId))
11479 return;
11480
11481 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11482 popup_ref.PopupId = id;
11483 popup_ref.Window = NULL;
11484 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
11485 popup_ref.OpenFrameCount = g.FrameCount;
11486 popup_ref.OpenParentId = parent_window->IDStack.back();
11487 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11488 popup_ref.OpenMousePos = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11489
11490 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11491 if (g.OpenPopupStack.Size < current_stack_size + 1)
11492 {
11493 g.OpenPopupStack.push_back(v: popup_ref);
11494 }
11495 else
11496 {
11497 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11498 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11499 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11500 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11501 bool keep_existing = false;
11502 if (g.OpenPopupStack[current_stack_size].PopupId == id)
11503 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11504 keep_existing = true;
11505 if (keep_existing)
11506 {
11507 // No reopen
11508 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11509 }
11510 else
11511 {
11512 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11513 ClosePopupToLevel(remaining: current_stack_size, restore_focus_to_window_under_popup: true);
11514 g.OpenPopupStack.push_back(v: popup_ref);
11515 }
11516
11517 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11518 // This is equivalent to what ClosePopupToLevel() does.
11519 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11520 // FocusWindow(parent_window);
11521 }
11522}
11523
11524// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11525// This function closes any popups that are over 'ref_window'.
11526void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11527{
11528 ImGuiContext& g = *GImGui;
11529 if (g.OpenPopupStack.Size == 0)
11530 return;
11531
11532 // Don't close our own child popup windows.
11533 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11534 int popup_count_to_keep = 0;
11535 if (ref_window)
11536 {
11537 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11538 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11539 {
11540 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11541 if (!popup.Window)
11542 continue;
11543 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11544
11545 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11546 // - Clicking/Focusing Window2 won't close Popup1:
11547 // Window -> Popup1 -> Window2(Ref)
11548 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11549 // Window -> Popup1(Ref) -> Popup2 -> Popup3
11550 // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11551 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11552 // We step through every popup from bottom to top to validate their position relative to reference window.
11553 bool ref_window_is_descendent_of_popup = false;
11554 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11555 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11556 //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11557 if (IsWindowWithinBeginStackOf(window: ref_window, potential_parent: popup_window))
11558 {
11559 ref_window_is_descendent_of_popup = true;
11560 break;
11561 }
11562 if (!ref_window_is_descendent_of_popup)
11563 break;
11564 }
11565 }
11566 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
11567 {
11568 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11569 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup);
11570 }
11571}
11572
11573void ImGui::ClosePopupsExceptModals()
11574{
11575 ImGuiContext& g = *GImGui;
11576
11577 int popup_count_to_keep;
11578 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11579 {
11580 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11581 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11582 break;
11583 }
11584 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
11585 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup: true);
11586}
11587
11588void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11589{
11590 ImGuiContext& g = *GImGui;
11591 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11592 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11593
11594 // Trim open popup stack
11595 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11596 g.OpenPopupStack.resize(new_size: remaining);
11597
11598 // 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)
11599 if (restore_focus_to_window_under_popup && prev_popup.Window)
11600 {
11601 ImGuiWindow* popup_window = prev_popup.Window;
11602 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11603 if (focus_window && !focus_window->WasActive)
11604 FocusTopMostWindowUnderOne(under_this_window: popup_window, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11605 else
11606 FocusWindow(window: focus_window, flags: (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11607 }
11608}
11609
11610// Close the popup we have begin-ed into.
11611void ImGui::CloseCurrentPopup()
11612{
11613 ImGuiContext& g = *GImGui;
11614 int popup_idx = g.BeginPopupStack.Size - 1;
11615 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11616 return;
11617
11618 // Closing a menu closes its top-most parent popup (unless a modal)
11619 while (popup_idx > 0)
11620 {
11621 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11622 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11623 bool close_parent = false;
11624 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11625 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11626 close_parent = true;
11627 if (!close_parent)
11628 break;
11629 popup_idx--;
11630 }
11631 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11632 ClosePopupToLevel(remaining: popup_idx, restore_focus_to_window_under_popup: true);
11633
11634 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11635 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11636 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11637 if (ImGuiWindow* window = g.NavWindow)
11638 window->DC.NavHideHighlightOneFrame = true;
11639}
11640
11641// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11642bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11643{
11644 ImGuiContext& g = *GImGui;
11645 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
11646 {
11647 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11648 return false;
11649 }
11650
11651 char name[20];
11652 if (flags & ImGuiWindowFlags_ChildMenu)
11653 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11654 else
11655 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11656
11657 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11658 bool is_open = Begin(name, NULL, flags);
11659 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11660 EndPopup();
11661
11662 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11663
11664 return is_open;
11665}
11666
11667bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11668{
11669 ImGuiContext& g = *GImGui;
11670 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11671 {
11672 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11673 return false;
11674 }
11675 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11676 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
11677 return BeginPopupEx(id, flags);
11678}
11679
11680// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11681// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11682// - *p_open set back to false in BeginPopupModal() when popup is not open.
11683// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11684bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11685{
11686 ImGuiContext& g = *GImGui;
11687 ImGuiWindow* window = g.CurrentWindow;
11688 const ImGuiID id = window->GetID(str: name);
11689 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
11690 {
11691 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11692 if (p_open && *p_open)
11693 *p_open = false;
11694 return false;
11695 }
11696
11697 // Center modal windows by default for increased visibility
11698 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11699 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11700 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11701 {
11702 const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11703 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_FirstUseEver, pivot: ImVec2(0.5f, 0.5f));
11704 }
11705
11706 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11707 const bool is_open = Begin(name, p_open, flags);
11708 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11709 {
11710 EndPopup();
11711 if (is_open)
11712 ClosePopupToLevel(remaining: g.BeginPopupStack.Size, restore_focus_to_window_under_popup: true);
11713 return false;
11714 }
11715 return is_open;
11716}
11717
11718void ImGui::EndPopup()
11719{
11720 ImGuiContext& g = *GImGui;
11721 ImGuiWindow* window = g.CurrentWindow;
11722 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
11723 IM_ASSERT(g.BeginPopupStack.Size > 0);
11724
11725 // 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)
11726 if (g.NavWindow == window)
11727 NavMoveRequestTryWrapping(window, move_flags: ImGuiNavMoveFlags_LoopY);
11728
11729 // Child-popups don't need to be laid out
11730 IM_ASSERT(g.WithinEndChild == false);
11731 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11732 g.WithinEndChild = true;
11733 End();
11734 g.WithinEndChild = false;
11735}
11736
11737// Helper to open a popup if mouse button is released over the item
11738// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11739void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11740{
11741 ImGuiContext& g = *GImGui;
11742 ImGuiWindow* window = g.CurrentWindow;
11743 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11744 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11745 {
11746 ImGuiID id = str_id ? window->GetID(str: str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11747 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11748 OpenPopupEx(id, popup_flags);
11749 }
11750}
11751
11752// This is a helper to handle the simplest case of associating one named popup to one given widget.
11753// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11754// - To create a popup with a specific identifier, pass it in str_id.
11755// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11756// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11757// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11758// This is essentially the same as:
11759// id = str_id ? GetID(str_id) : GetItemID();
11760// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11761// return BeginPopup(id);
11762// Which is essentially the same as:
11763// id = str_id ? GetID(str_id) : GetItemID();
11764// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11765// OpenPopup(id);
11766// return BeginPopup(id);
11767// The main difference being that this is tweaked to avoid computing the ID twice.
11768bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11769{
11770 ImGuiContext& g = *GImGui;
11771 ImGuiWindow* window = g.CurrentWindow;
11772 if (window->SkipItems)
11773 return false;
11774 ImGuiID id = str_id ? window->GetID(str: str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11775 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11776 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11777 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11778 OpenPopupEx(id, popup_flags);
11779 return BeginPopupEx(id, flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11780}
11781
11782bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11783{
11784 ImGuiContext& g = *GImGui;
11785 ImGuiWindow* window = g.CurrentWindow;
11786 if (!str_id)
11787 str_id = "window_context";
11788 ImGuiID id = window->GetID(str: str_id);
11789 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11790 if (IsMouseReleased(button: mouse_button) && IsWindowHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11791 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11792 OpenPopupEx(id, popup_flags);
11793 return BeginPopupEx(id, flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11794}
11795
11796bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11797{
11798 ImGuiContext& g = *GImGui;
11799 ImGuiWindow* window = g.CurrentWindow;
11800 if (!str_id)
11801 str_id = "void_context";
11802 ImGuiID id = window->GetID(str: str_id);
11803 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11804 if (IsMouseReleased(button: mouse_button) && !IsWindowHovered(flags: ImGuiHoveredFlags_AnyWindow))
11805 if (GetTopMostPopupModal() == NULL)
11806 OpenPopupEx(id, popup_flags);
11807 return BeginPopupEx(id, flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11808}
11809
11810// 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.)
11811// 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.
11812// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11813// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11814// this allows us to have tooltips/popups displayed out of the parent viewport.)
11815ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11816{
11817 ImVec2 base_pos_clamped = ImClamp(v: ref_pos, mn: r_outer.Min, mx: r_outer.Max - size);
11818 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11819 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11820
11821 // Combo Box policy (we want a connecting edge)
11822 if (policy == ImGuiPopupPositionPolicy_ComboBox)
11823 {
11824 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11825 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11826 {
11827 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11828 if (n != -1 && dir == *last_dir) // Already tried this direction?
11829 continue;
11830 ImVec2 pos;
11831 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
11832 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11833 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11834 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11835 if (!r_outer.Contains(r: ImRect(pos, pos + size)))
11836 continue;
11837 *last_dir = dir;
11838 return pos;
11839 }
11840 }
11841
11842 // Tooltip and Default popup policy
11843 // (Always first try the direction we used on the last frame, if any)
11844 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11845 {
11846 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11847 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11848 {
11849 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11850 if (n != -1 && dir == *last_dir) // Already tried this direction?
11851 continue;
11852
11853 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);
11854 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);
11855
11856 // 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)
11857 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11858 continue;
11859 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11860 continue;
11861
11862 ImVec2 pos;
11863 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11864 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11865
11866 // Clamp top-left corner of popup
11867 pos.x = ImMax(lhs: pos.x, rhs: r_outer.Min.x);
11868 pos.y = ImMax(lhs: pos.y, rhs: r_outer.Min.y);
11869
11870 *last_dir = dir;
11871 return pos;
11872 }
11873 }
11874
11875 // Fallback when not enough room:
11876 *last_dir = ImGuiDir_None;
11877
11878 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11879 if (policy == ImGuiPopupPositionPolicy_Tooltip)
11880 return ref_pos + ImVec2(2, 2);
11881
11882 // Otherwise try to keep within display
11883 ImVec2 pos = ref_pos;
11884 pos.x = ImMax(lhs: ImMin(lhs: pos.x + size.x, rhs: r_outer.Max.x) - size.x, rhs: r_outer.Min.x);
11885 pos.y = ImMax(lhs: ImMin(lhs: pos.y + size.y, rhs: r_outer.Max.y) - size.y, rhs: r_outer.Min.y);
11886 return pos;
11887}
11888
11889// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11890ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11891{
11892 ImGuiContext& g = *GImGui;
11893 ImRect r_screen;
11894 if (window->ViewportAllowPlatformMonitorExtend >= 0)
11895 {
11896 // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11897 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11898 r_screen.Min = monitor.WorkPos;
11899 r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11900 }
11901 else
11902 {
11903 // Use the full viewport area (not work area) for popups
11904 r_screen = window->Viewport->GetMainRect();
11905 }
11906 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11907 r_screen.Expand(amount: ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11908 return r_screen;
11909}
11910
11911ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11912{
11913 ImGuiContext& g = *GImGui;
11914
11915 ImRect r_outer = GetPopupAllowedExtentRect(window);
11916 if (window->Flags & ImGuiWindowFlags_ChildMenu)
11917 {
11918 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11919 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11920 ImGuiWindow* parent_window = window->ParentWindow;
11921 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).
11922 ImRect r_avoid;
11923 if (parent_window->DC.MenuBarAppending)
11924 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
11925 else
11926 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);
11927 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Default);
11928 }
11929 if (window->Flags & ImGuiWindowFlags_Popup)
11930 {
11931 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid: ImRect(window->Pos, window->Pos), policy: ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11932 }
11933 if (window->Flags & ImGuiWindowFlags_Tooltip)
11934 {
11935 // Position tooltip (always follows mouse + clamp within outer boundaries)
11936 // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11937 // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11938 IM_ASSERT(g.CurrentWindow == window);
11939 const float scale = g.Style.MouseCursorScale;
11940 const ImVec2 ref_pos = NavCalcPreferredRefPos();
11941 const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11942 ImRect r_avoid;
11943 if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11944 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11945 else
11946 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.
11947 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11948 return FindBestWindowPosForPopupEx(ref_pos: tooltip_pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Tooltip);
11949 }
11950 IM_ASSERT(0);
11951 return window->Pos;
11952}
11953
11954//-----------------------------------------------------------------------------
11955// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11956//-----------------------------------------------------------------------------
11957
11958// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11959// In our terminology those should be interchangeable, yet right now this is super confusing.
11960// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11961
11962void ImGui::SetNavWindow(ImGuiWindow* window)
11963{
11964 ImGuiContext& g = *GImGui;
11965 if (g.NavWindow != window)
11966 {
11967 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11968 g.NavWindow = window;
11969 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11970 }
11971 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11972 NavUpdateAnyRequestFlag();
11973}
11974
11975void ImGui::NavHighlightActivated(ImGuiID id)
11976{
11977 ImGuiContext& g = *GImGui;
11978 g.NavHighlightActivatedId = id;
11979 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
11980}
11981
11982void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11983{
11984 ImGuiContext& g = *GImGui;
11985 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11986}
11987
11988void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11989{
11990 ImGuiContext& g = *GImGui;
11991 IM_ASSERT(g.NavWindow != NULL);
11992 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11993 g.NavId = id;
11994 g.NavLayer = nav_layer;
11995 SetNavFocusScope(focus_scope_id);
11996 g.NavWindow->NavLastIds[nav_layer] = id;
11997 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11998
11999 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12000 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
12001 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
12002}
12003
12004void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12005{
12006 ImGuiContext& g = *GImGui;
12007 IM_ASSERT(id != 0);
12008
12009 if (g.NavWindow != window)
12010 SetNavWindow(window);
12011
12012 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12013 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12014 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12015 g.NavId = id;
12016 g.NavLayer = nav_layer;
12017 SetNavFocusScope(g.CurrentFocusScopeId);
12018 window->NavLastIds[nav_layer] = id;
12019 if (g.LastItemData.ID == id)
12020 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
12021
12022 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12023 g.NavDisableMouseHover = true;
12024 else
12025 g.NavDisableHighlight = true;
12026
12027 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12028 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
12029 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
12030}
12031
12032static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12033{
12034 if (ImFabs(dx) > ImFabs(dy))
12035 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12036 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12037}
12038
12039static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12040{
12041 if (cand_max < curr_min)
12042 return cand_max - curr_min;
12043 if (curr_max < cand_min)
12044 return cand_min - curr_max;
12045 return 0.0f;
12046}
12047
12048// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12049static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12050{
12051 ImGuiContext& g = *GImGui;
12052 ImGuiWindow* window = g.CurrentWindow;
12053 if (g.NavLayer != window->DC.NavLayerCurrent)
12054 return false;
12055
12056 // FIXME: Those are not good variables names
12057 ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
12058 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)
12059 g.NavScoringDebugCount++;
12060
12061 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12062 if (window->ParentWindow == g.NavWindow)
12063 {
12064 IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
12065 if (!window->ClipRect.Overlaps(r: cand))
12066 return false;
12067 cand.ClipWithFull(r: window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12068 }
12069
12070 // Compute distance between boxes
12071 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12072 float dbx = NavScoreItemDistInterval(cand_min: cand.Min.x, cand_max: cand.Max.x, curr_min: curr.Min.x, curr_max: curr.Max.x);
12073 float dby = NavScoreItemDistInterval(cand_min: ImLerp(a: cand.Min.y, b: cand.Max.y, t: 0.2f), cand_max: ImLerp(a: cand.Min.y, b: cand.Max.y, t: 0.8f), curr_min: ImLerp(a: curr.Min.y, b: curr.Max.y, t: 0.2f), curr_max: ImLerp(a: curr.Min.y, b: curr.Max.y, t: 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12074 if (dby != 0.0f && dbx != 0.0f)
12075 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12076 float dist_box = ImFabs(dbx) + ImFabs(dby);
12077
12078 // 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)
12079 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12080 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12081 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12082
12083 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12084 ImGuiDir quadrant;
12085 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12086 if (dbx != 0.0f || dby != 0.0f)
12087 {
12088 // For non-overlapping boxes, use distance between boxes
12089 dax = dbx;
12090 day = dby;
12091 dist_axial = dist_box;
12092 quadrant = ImGetDirQuadrantFromDelta(dx: dbx, dy: dby);
12093 }
12094 else if (dcx != 0.0f || dcy != 0.0f)
12095 {
12096 // For overlapping boxes with different centers, use distance between centers
12097 dax = dcx;
12098 day = dcy;
12099 dist_axial = dist_center;
12100 quadrant = ImGetDirQuadrantFromDelta(dx: dcx, dy: dcy);
12101 }
12102 else
12103 {
12104 // 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)
12105 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12106 }
12107
12108 const ImGuiDir move_dir = g.NavMoveDir;
12109#if IMGUI_DEBUG_NAV_SCORING
12110 char buf[200];
12111 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12112 {
12113 if (quadrant == move_dir)
12114 {
12115 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12116 ImDrawList* draw_list = GetForegroundDrawList(window);
12117 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12118 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12119 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12120 }
12121 }
12122 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12123 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12124 if (debug_hovering || debug_tty)
12125 {
12126 ImFormatString(buf, IM_ARRAYSIZE(buf),
12127 "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",
12128 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12129 if (debug_hovering)
12130 {
12131 ImDrawList* draw_list = GetForegroundDrawList(window);
12132 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12133 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12134 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12135 draw_list->AddText(cand.Max, ~0U, buf);
12136 }
12137 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12138 }
12139#endif
12140
12141 // Is it in the quadrant we're interested in moving to?
12142 bool new_best = false;
12143 if (quadrant == move_dir)
12144 {
12145 // Does it beat the current best candidate?
12146 if (dist_box < result->DistBox)
12147 {
12148 result->DistBox = dist_box;
12149 result->DistCenter = dist_center;
12150 return true;
12151 }
12152 if (dist_box == result->DistBox)
12153 {
12154 // Try using distance between center points to break ties
12155 if (dist_center < result->DistCenter)
12156 {
12157 result->DistCenter = dist_center;
12158 new_best = true;
12159 }
12160 else if (dist_center == result->DistCenter)
12161 {
12162 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12163 // (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),
12164 // 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.
12165 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12166 new_best = true;
12167 }
12168 }
12169 }
12170
12171 // 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
12172 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12173 // 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.
12174 // 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.
12175 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12176 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
12177 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12178 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))
12179 {
12180 result->DistAxial = dist_axial;
12181 new_best = true;
12182 }
12183
12184 return new_best;
12185}
12186
12187static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12188{
12189 ImGuiContext& g = *GImGui;
12190 ImGuiWindow* window = g.CurrentWindow;
12191 result->Window = window;
12192 result->ID = g.LastItemData.ID;
12193 result->FocusScopeId = g.CurrentFocusScopeId;
12194 result->InFlags = g.LastItemData.InFlags;
12195 result->RectRel = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
12196 if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12197 {
12198 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12199 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12200 }
12201}
12202
12203// True when current work location may be scrolled horizontally when moving left / right.
12204// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12205void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12206{
12207 ImGuiContext& g = *GImGui;
12208 ImGuiWindow* window = g.CurrentWindow;
12209 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12210}
12211
12212// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12213// This is called after LastItemData is set, but NextItemData is also still valid.
12214static void ImGui::NavProcessItem()
12215{
12216 ImGuiContext& g = *GImGui;
12217 ImGuiWindow* window = g.CurrentWindow;
12218 const ImGuiID id = g.LastItemData.ID;
12219 const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12220
12221 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12222 if (window->DC.NavIsScrollPushableX == false)
12223 {
12224 g.LastItemData.NavRect.Min.x = ImClamp(v: g.LastItemData.NavRect.Min.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
12225 g.LastItemData.NavRect.Max.x = ImClamp(v: g.LastItemData.NavRect.Max.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
12226 }
12227 const ImRect nav_bb = g.LastItemData.NavRect;
12228
12229 // Process Init Request
12230 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12231 {
12232 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12233 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12234 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12235 {
12236 NavApplyItemToResult(result: &g.NavInitResult);
12237 }
12238 if (candidate_for_nav_default_focus)
12239 {
12240 g.NavInitRequest = false; // Found a match, clear request
12241 NavUpdateAnyRequestFlag();
12242 }
12243 }
12244
12245 // Process Move Request (scoring for navigation)
12246 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12247 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12248 {
12249 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12250 {
12251 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12252 if (is_tabbing)
12253 {
12254 NavProcessItemForTabbingRequest(id, item_flags, move_flags: g.NavMoveFlags);
12255 }
12256 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12257 {
12258 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12259 if (NavScoreItem(result))
12260 NavApplyItemToResult(result);
12261
12262 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12263 const float VISIBLE_RATIO = 0.70f;
12264 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(r: nav_bb))
12265 if (ImClamp(v: nav_bb.Max.y, mn: window->ClipRect.Min.y, mx: window->ClipRect.Max.y) - ImClamp(v: nav_bb.Min.y, mn: window->ClipRect.Min.y, mx: window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12266 if (NavScoreItem(result: &g.NavMoveResultLocalVisible))
12267 NavApplyItemToResult(result: &g.NavMoveResultLocalVisible);
12268 }
12269 }
12270 }
12271
12272 // Update information for currently focused/navigated item
12273 if (g.NavId == id)
12274 {
12275 if (g.NavWindow != window)
12276 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12277 g.NavLayer = window->DC.NavLayerCurrent;
12278 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12279 g.NavFocusScopeId = g.CurrentFocusScopeId;
12280 g.NavIdIsAlive = true;
12281 if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12282 {
12283 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12284 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12285 }
12286 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, r: nav_bb); // Store item bounding box (relative to window position)
12287 }
12288}
12289
12290// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12291// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12292// - Case 1: no nav/active id: set result to first eligible item, stop storing.
12293// - Case 2: tab forward: on ref id set counter, on counter elapse store result
12294// - 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
12295// - Case 4: tab backward: store all results, on ref id pick prev, stop storing
12296// - 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
12297void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12298{
12299 ImGuiContext& g = *GImGui;
12300
12301 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12302 {
12303 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12304 return;
12305 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12306 return;
12307 }
12308
12309 // - Can always land on an item when using API call.
12310 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12311 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12312 bool can_stop;
12313 if (move_flags & ImGuiNavMoveFlags_FocusApi)
12314 can_stop = true;
12315 else
12316 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12317
12318 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12319 ImGuiNavItemData* result = &g.NavMoveResultLocal;
12320 if (g.NavTabbingDir == +1)
12321 {
12322 // Tab Forward or SetKeyboardFocusHere() with >= 0
12323 if (can_stop && g.NavTabbingResultFirst.ID == 0)
12324 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
12325 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12326 NavMoveRequestResolveWithLastItem(result);
12327 else if (g.NavId == id)
12328 g.NavTabbingCounter = 1;
12329 }
12330 else if (g.NavTabbingDir == -1)
12331 {
12332 // Tab Backward
12333 if (g.NavId == id)
12334 {
12335 if (result->ID)
12336 {
12337 g.NavMoveScoringItems = false;
12338 NavUpdateAnyRequestFlag();
12339 }
12340 }
12341 else if (can_stop)
12342 {
12343 // Keep applying until reaching NavId
12344 NavApplyItemToResult(result);
12345 }
12346 }
12347 else if (g.NavTabbingDir == 0)
12348 {
12349 if (can_stop && g.NavId == id)
12350 NavMoveRequestResolveWithLastItem(result);
12351 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12352 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
12353 }
12354}
12355
12356bool ImGui::NavMoveRequestButNoResultYet()
12357{
12358 ImGuiContext& g = *GImGui;
12359 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12360}
12361
12362// FIXME: ScoringRect is not set
12363void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12364{
12365 ImGuiContext& g = *GImGui;
12366 IM_ASSERT(g.NavWindow != NULL);
12367
12368 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12369 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12370
12371 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12372 g.NavMoveDir = move_dir;
12373 g.NavMoveDirForDebug = move_dir;
12374 g.NavMoveClipDir = clip_dir;
12375 g.NavMoveFlags = move_flags;
12376 g.NavMoveScrollFlags = scroll_flags;
12377 g.NavMoveForwardToNextFrame = false;
12378 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12379 g.NavMoveResultLocal.Clear();
12380 g.NavMoveResultLocalVisible.Clear();
12381 g.NavMoveResultOther.Clear();
12382 g.NavTabbingCounter = 0;
12383 g.NavTabbingResultFirst.Clear();
12384 NavUpdateAnyRequestFlag();
12385}
12386
12387void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12388{
12389 ImGuiContext& g = *GImGui;
12390 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12391 NavApplyItemToResult(result);
12392 NavUpdateAnyRequestFlag();
12393}
12394
12395// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12396void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12397{
12398 ImGuiContext& g = *GImGui;
12399 g.NavMoveScoringItems = false;
12400 g.LastItemData.ID = tree_node_data->ID;
12401 g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12402 g.LastItemData.NavRect = tree_node_data->NavRect;
12403 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12404 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
12405 NavUpdateAnyRequestFlag();
12406}
12407
12408void ImGui::NavMoveRequestCancel()
12409{
12410 ImGuiContext& g = *GImGui;
12411 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12412 NavUpdateAnyRequestFlag();
12413}
12414
12415// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12416void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12417{
12418 ImGuiContext& g = *GImGui;
12419 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12420 NavMoveRequestCancel();
12421 g.NavMoveForwardToNextFrame = true;
12422 g.NavMoveDir = move_dir;
12423 g.NavMoveClipDir = clip_dir;
12424 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12425 g.NavMoveScrollFlags = scroll_flags;
12426}
12427
12428// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12429// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12430void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12431{
12432 ImGuiContext& g = *GImGui;
12433 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12434
12435 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12436 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12437 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12438 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12439}
12440
12441// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12442// This way we could find the last focused window among our children. It would be much less confusing this way?
12443static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12444{
12445 ImGuiWindow* parent = nav_window;
12446 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12447 parent = parent->ParentWindow;
12448 if (parent && parent != nav_window)
12449 parent->NavLastChildNavWindow = nav_window;
12450}
12451
12452// Restore the last focused child.
12453// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12454static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12455{
12456 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12457 return window->NavLastChildNavWindow;
12458 if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12459 if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar: window->DockNodeAsHost->TabBar))
12460 return tab->Window;
12461 return window;
12462}
12463
12464void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12465{
12466 ImGuiContext& g = *GImGui;
12467 if (layer == ImGuiNavLayer_Main)
12468 {
12469 ImGuiWindow* prev_nav_window = g.NavWindow;
12470 g.NavWindow = NavRestoreLastChildNavWindow(window: g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
12471 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12472 if (prev_nav_window)
12473 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12474 }
12475 ImGuiWindow* window = g.NavWindow;
12476 if (window->NavLastIds[layer] != 0)
12477 {
12478 SetNavID(id: window->NavLastIds[layer], nav_layer: layer, focus_scope_id: 0, rect_rel: window->NavRectRel[layer]);
12479 }
12480 else
12481 {
12482 g.NavLayer = layer;
12483 NavInitWindow(window, force_reinit: true);
12484 }
12485}
12486
12487void ImGui::NavRestoreHighlightAfterMove()
12488{
12489 ImGuiContext& g = *GImGui;
12490 g.NavDisableHighlight = false;
12491 g.NavDisableMouseHover = g.NavMousePosDirty = true;
12492}
12493
12494static inline void ImGui::NavUpdateAnyRequestFlag()
12495{
12496 ImGuiContext& g = *GImGui;
12497 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12498 if (g.NavAnyRequest)
12499 IM_ASSERT(g.NavWindow != NULL);
12500}
12501
12502// This needs to be called before we submit any widget (aka in or before Begin)
12503void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12504{
12505 // FIXME: ChildWindow test here is wrong for docking
12506 ImGuiContext& g = *GImGui;
12507 IM_ASSERT(window == g.NavWindow);
12508
12509 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12510 {
12511 g.NavId = 0;
12512 SetNavFocusScope(window->NavRootFocusScopeId);
12513 return;
12514 }
12515
12516 bool init_for_nav = false;
12517 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12518 init_for_nav = true;
12519 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12520 if (init_for_nav)
12521 {
12522 SetNavID(id: 0, nav_layer: g.NavLayer, focus_scope_id: window->NavRootFocusScopeId, rect_rel: ImRect());
12523 g.NavInitRequest = true;
12524 g.NavInitRequestFromMove = false;
12525 g.NavInitResult.ID = 0;
12526 NavUpdateAnyRequestFlag();
12527 }
12528 else
12529 {
12530 g.NavId = window->NavLastIds[0];
12531 SetNavFocusScope(window->NavRootFocusScopeId);
12532 }
12533}
12534
12535static ImVec2 ImGui::NavCalcPreferredRefPos()
12536{
12537 ImGuiContext& g = *GImGui;
12538 ImGuiWindow* window = g.NavWindow;
12539 if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12540 {
12541 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12542 // 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.
12543 // In theory we could move that +1.0f offset in OpenPopupEx()
12544 ImVec2 p = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12545 return ImVec2(p.x + 1.0f, p.y);
12546 }
12547 else
12548 {
12549 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12550 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12551 ImRect rect_rel = WindowRectRelToAbs(window, r: window->NavRectRel[g.NavLayer]);
12552 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12553 {
12554 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12555 rect_rel.Translate(d: window->Scroll - next_scroll);
12556 }
12557 ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(lhs: g.Style.FramePadding.x * 4, rhs: rect_rel.GetWidth()), rect_rel.Max.y - ImMin(lhs: g.Style.FramePadding.y, rhs: rect_rel.GetHeight()));
12558 ImGuiViewport* viewport = window->Viewport;
12559 return ImTrunc(v: ImClamp(v: pos, mn: viewport->Pos, mx: viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12560 }
12561}
12562
12563float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12564{
12565 ImGuiContext& g = *GImGui;
12566 float repeat_delay, repeat_rate;
12567 GetTypematicRepeatRate(flags: ImGuiInputFlags_RepeatRateNavTweak, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
12568
12569 ImGuiKey key_less, key_more;
12570 if (g.NavInputSource == ImGuiInputSource_Gamepad)
12571 {
12572 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12573 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12574 }
12575 else
12576 {
12577 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12578 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12579 }
12580 float amount = (float)GetKeyPressedAmount(key: key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key: key_less, repeat_delay, repeat_rate);
12581 if (amount != 0.0f && IsKeyDown(key: key_less) && IsKeyDown(key: key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12582 amount = 0.0f;
12583 return amount;
12584}
12585
12586static void ImGui::NavUpdate()
12587{
12588 ImGuiContext& g = *GImGui;
12589 ImGuiIO& io = g.IO;
12590
12591 io.WantSetMousePos = false;
12592 //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);
12593
12594 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12595 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12596 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12597 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12598 if (nav_gamepad_active)
12599 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12600 if (IsKeyDown(key))
12601 g.NavInputSource = ImGuiInputSource_Gamepad;
12602 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12603 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12604 if (nav_keyboard_active)
12605 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12606 if (IsKeyDown(key))
12607 g.NavInputSource = ImGuiInputSource_Keyboard;
12608
12609 // Process navigation init request (select first/default focus)
12610 g.NavJustMovedToId = 0;
12611 if (g.NavInitResult.ID != 0)
12612 NavInitRequestApplyResult();
12613 g.NavInitRequest = false;
12614 g.NavInitRequestFromMove = false;
12615 g.NavInitResult.ID = 0;
12616
12617 // Process navigation move request
12618 if (g.NavMoveSubmitted)
12619 NavMoveRequestApplyResult();
12620 g.NavTabbingCounter = 0;
12621 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12622
12623 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12624 bool set_mouse_pos = false;
12625 if (g.NavMousePosDirty && g.NavIdIsAlive)
12626 if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12627 set_mouse_pos = true;
12628 g.NavMousePosDirty = false;
12629 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12630
12631 // 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
12632 if (g.NavWindow)
12633 NavSaveLastChildNavWindowIntoParent(nav_window: g.NavWindow);
12634 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12635 g.NavWindow->NavLastChildNavWindow = NULL;
12636
12637 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12638 NavUpdateWindowing();
12639
12640 // Set output flags for user application
12641 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12642 io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12643
12644 // Process NavCancel input (to close a popup, get back to parent, clear focus)
12645 NavUpdateCancelRequest();
12646
12647 // Process manual activation request
12648 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12649 g.NavActivateFlags = ImGuiActivateFlags_None;
12650 if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12651 {
12652 const bool activate_down = (nav_keyboard_active && IsKeyDown(key: ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None));
12653 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None)));
12654 const bool input_down = (nav_keyboard_active && (IsKeyDown(key: ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyDown(key: ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None));
12655 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(key: ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyPressed(key: ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None)));
12656 if (g.ActiveId == 0 && activate_pressed)
12657 {
12658 g.NavActivateId = g.NavId;
12659 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12660 }
12661 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12662 {
12663 g.NavActivateId = g.NavId;
12664 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12665 }
12666 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12667 g.NavActivateDownId = g.NavId;
12668 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12669 {
12670 g.NavActivatePressedId = g.NavId;
12671 NavHighlightActivated(id: g.NavId);
12672 }
12673 }
12674 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12675 g.NavDisableHighlight = true;
12676 if (g.NavActivateId != 0)
12677 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12678
12679 // Highlight
12680 if (g.NavHighlightActivatedTimer > 0.0f)
12681 g.NavHighlightActivatedTimer = ImMax(lhs: 0.0f, rhs: g.NavHighlightActivatedTimer - io.DeltaTime);
12682 if (g.NavHighlightActivatedTimer == 0.0f)
12683 g.NavHighlightActivatedId = 0;
12684
12685 // Process programmatic activation request
12686 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12687 if (g.NavNextActivateId != 0)
12688 {
12689 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12690 g.NavActivateFlags = g.NavNextActivateFlags;
12691 }
12692 g.NavNextActivateId = 0;
12693
12694 // Process move requests
12695 NavUpdateCreateMoveRequest();
12696 if (g.NavMoveDir == ImGuiDir_None)
12697 NavUpdateCreateTabbingRequest();
12698 NavUpdateAnyRequestFlag();
12699 g.NavIdIsAlive = false;
12700
12701 // Scrolling
12702 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12703 {
12704 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12705 ImGuiWindow* window = g.NavWindow;
12706 const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12707 const ImGuiDir move_dir = g.NavMoveDir;
12708 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12709 {
12710 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12711 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12712 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12713 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12714 }
12715
12716 // *Normal* Manual scroll with LStick
12717 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12718 if (nav_gamepad_active)
12719 {
12720 const ImVec2 scroll_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
12721 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12722 if (scroll_dir.x != 0.0f && window->ScrollbarX)
12723 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12724 if (scroll_dir.y != 0.0f)
12725 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12726 }
12727 }
12728
12729 // Always prioritize mouse highlight if navigation is disabled
12730 if (!nav_keyboard_active && !nav_gamepad_active)
12731 {
12732 g.NavDisableHighlight = true;
12733 g.NavDisableMouseHover = set_mouse_pos = false;
12734 }
12735
12736 // Update mouse position if requested
12737 // (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)
12738 if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12739 TeleportMousePos(pos: NavCalcPreferredRefPos());
12740
12741 // [DEBUG]
12742 g.NavScoringDebugCount = 0;
12743#if IMGUI_DEBUG_NAV_RECTS
12744 if (ImGuiWindow* debug_window = g.NavWindow)
12745 {
12746 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12747 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)); }
12748 //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); }
12749 }
12750#endif
12751}
12752
12753void ImGui::NavInitRequestApplyResult()
12754{
12755 // 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)
12756 ImGuiContext& g = *GImGui;
12757 if (!g.NavWindow)
12758 return;
12759
12760 ImGuiNavItemData* result = &g.NavInitResult;
12761 if (g.NavId != result->ID)
12762 {
12763 g.NavJustMovedToId = result->ID;
12764 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12765 g.NavJustMovedToKeyMods = 0;
12766 }
12767
12768 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12769 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12770 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12771 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
12772 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12773 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12774 g.NavLastValidSelectionUserData = result->SelectionUserData;
12775 if (g.NavInitRequestFromMove)
12776 NavRestoreHighlightAfterMove();
12777}
12778
12779// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12780static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12781{
12782 // Bias initial rect
12783 ImGuiContext& g = *GImGui;
12784 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12785
12786 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12787 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12788 // - But each successful move sets new bias on one axis, only cleared when using mouse.
12789 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12790 {
12791 if (preferred_pos_rel.x == FLT_MAX)
12792 preferred_pos_rel.x = ImMin(lhs: r.Min.x + 1.0f, rhs: r.Max.x) - rel_to_abs_offset.x;
12793 if (preferred_pos_rel.y == FLT_MAX)
12794 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12795 }
12796
12797 // Apply general bias on the other axis
12798 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12799 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12800 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12801 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12802}
12803
12804void ImGui::NavUpdateCreateMoveRequest()
12805{
12806 ImGuiContext& g = *GImGui;
12807 ImGuiIO& io = g.IO;
12808 ImGuiWindow* window = g.NavWindow;
12809 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12810 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12811
12812 if (g.NavMoveForwardToNextFrame && window != NULL)
12813 {
12814 // 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)
12815 // (preserve most state, which were already set by the NavMoveRequestForward() function)
12816 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12817 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12818 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12819 }
12820 else
12821 {
12822 // Initiate directional inputs request
12823 g.NavMoveDir = ImGuiDir_None;
12824 g.NavMoveFlags = ImGuiNavMoveFlags_None;
12825 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12826 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12827 {
12828 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateNavMove;
12829 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadLeft, ImGuiKeyOwner_None, flags: repeat_mode)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_LeftArrow, ImGuiKeyOwner_None, flags: repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12830 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, flags: repeat_mode)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_RightArrow, ImGuiKeyOwner_None, flags: repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12831 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadUp, ImGuiKeyOwner_None, flags: repeat_mode)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_UpArrow, ImGuiKeyOwner_None, flags: repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12832 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadDown, ImGuiKeyOwner_None, flags: repeat_mode)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_DownArrow, ImGuiKeyOwner_None, flags: repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12833 }
12834 g.NavMoveClipDir = g.NavMoveDir;
12835 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12836 }
12837
12838 // Update PageUp/PageDown/Home/End scroll
12839 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12840 float scoring_rect_offset_y = 0.0f;
12841 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12842 scoring_rect_offset_y = NavUpdatePageUpPageDown();
12843 if (scoring_rect_offset_y != 0.0f)
12844 {
12845 g.NavScoringNoClipRect = window->InnerRect;
12846 g.NavScoringNoClipRect.TranslateY(dy: scoring_rect_offset_y);
12847 }
12848
12849 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12850#if IMGUI_DEBUG_NAV_SCORING
12851 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12852 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12853 if (io.KeyCtrl)
12854 {
12855 if (g.NavMoveDir == ImGuiDir_None)
12856 g.NavMoveDir = g.NavMoveDirForDebug;
12857 g.NavMoveClipDir = g.NavMoveDir;
12858 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12859 }
12860#endif
12861
12862 // Submit
12863 g.NavMoveForwardToNextFrame = false;
12864 if (g.NavMoveDir != ImGuiDir_None)
12865 NavMoveRequestSubmit(move_dir: g.NavMoveDir, clip_dir: g.NavMoveClipDir, move_flags: g.NavMoveFlags, scroll_flags: g.NavMoveScrollFlags);
12866
12867 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12868 if (g.NavMoveSubmitted && g.NavId == 0)
12869 {
12870 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12871 g.NavInitRequest = g.NavInitRequestFromMove = true;
12872 g.NavInitResult.ID = 0;
12873 g.NavDisableHighlight = false;
12874 }
12875
12876 // When using gamepad, we project the reference nav bounding box into window visible area.
12877 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12878 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12879 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12880 {
12881 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12882 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12883 ImRect inner_rect_rel = WindowRectAbsToRel(window, r: ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12884
12885 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12886 // Otherwise 'inner_rect_rel' would be off on the move result frame.
12887 inner_rect_rel.Translate(d: CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12888
12889 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(r: window->NavRectRel[g.NavLayer]))
12890 {
12891 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12892 float pad_x = ImMin(lhs: inner_rect_rel.GetWidth(), rhs: window->CalcFontSize() * 0.5f);
12893 float pad_y = ImMin(lhs: inner_rect_rel.GetHeight(), rhs: window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12894 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12895 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12896 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12897 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12898 window->NavRectRel[g.NavLayer].ClipWithFull(r: inner_rect_rel);
12899 g.NavId = 0;
12900 }
12901 }
12902
12903 // 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)
12904 ImRect scoring_rect;
12905 if (window != NULL)
12906 {
12907 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12908 scoring_rect = WindowRectRelToAbs(window, r: nav_rect_rel);
12909 scoring_rect.TranslateY(dy: scoring_rect_offset_y);
12910 if (g.NavMoveSubmitted)
12911 NavBiasScoringRect(r&: scoring_rect, preferred_pos_rel&: window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], move_dir: g.NavMoveDir, move_flags: g.NavMoveFlags);
12912 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12913 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12914 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12915 }
12916 g.NavScoringRect = scoring_rect;
12917 g.NavScoringNoClipRect.Add(r: scoring_rect);
12918}
12919
12920void ImGui::NavUpdateCreateTabbingRequest()
12921{
12922 ImGuiContext& g = *GImGui;
12923 ImGuiWindow* window = g.NavWindow;
12924 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12925 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12926 return;
12927
12928 const bool tab_pressed = IsKeyPressed(key: ImGuiKey_Tab, ImGuiKeyOwner_None, flags: ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12929 if (!tab_pressed)
12930 return;
12931
12932 // Initiate tabbing request
12933 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12934 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12935 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12936 if (nav_keyboard_active)
12937 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12938 else
12939 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12940 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12941 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12942 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12943 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12944 g.NavTabbingCounter = -1;
12945}
12946
12947// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12948void ImGui::NavMoveRequestApplyResult()
12949{
12950 ImGuiContext& g = *GImGui;
12951#if IMGUI_DEBUG_NAV_SCORING
12952 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12953 return;
12954#endif
12955
12956 // Select which result to use
12957 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12958
12959 // Tabbing forward wrap
12960 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12961 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12962 result = &g.NavTabbingResultFirst;
12963
12964 // 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)
12965 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12966 if (result == NULL)
12967 {
12968 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12969 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12970 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12971 NavRestoreHighlightAfterMove();
12972 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12973 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12974 return;
12975 }
12976
12977 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12978 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12979 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12980 result = &g.NavMoveResultLocalVisible;
12981
12982 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12983 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12984 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12985 result = &g.NavMoveResultOther;
12986 IM_ASSERT(g.NavWindow && result->Window);
12987
12988 // Scroll to keep newly navigated item fully into view.
12989 if (g.NavLayer == ImGuiNavLayer_Main)
12990 {
12991 ImRect rect_abs = WindowRectRelToAbs(window: result->Window, r: result->RectRel);
12992 ScrollToRectEx(window: result->Window, item_rect: rect_abs, flags: g.NavMoveScrollFlags);
12993
12994 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12995 {
12996 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12997 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12998 SetScrollY(window: result->Window, scroll_y: scroll_target);
12999 }
13000 }
13001
13002 if (g.NavWindow != result->Window)
13003 {
13004 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13005 g.NavWindow = result->Window;
13006 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13007 }
13008
13009 // Clear active id unless requested not to
13010 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13011 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13012 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13013 ClearActiveID();
13014
13015 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13016 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13017 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13018 {
13019 g.NavJustMovedToId = result->ID;
13020 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13021 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13022 }
13023
13024 // Apply new NavID/Focus
13025 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13026 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13027 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
13028 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13029 g.NavLastValidSelectionUserData = result->SelectionUserData;
13030
13031 // Restore last preferred position for current axis
13032 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13033 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13034 {
13035 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13036 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13037 }
13038
13039 // Tabbing: Activates Inputable, otherwise only Focus
13040 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13041 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13042
13043 // Activate
13044 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13045 {
13046 g.NavNextActivateId = result->ID;
13047 g.NavNextActivateFlags = ImGuiActivateFlags_None;
13048 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13049 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13050 }
13051
13052 // Enable nav highlight
13053 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13054 NavRestoreHighlightAfterMove();
13055}
13056
13057// Process NavCancel input (to close a popup, get back to parent, clear focus)
13058// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13059// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13060// - 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
13061static void ImGui::NavUpdateCancelRequest()
13062{
13063 ImGuiContext& g = *GImGui;
13064 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13065 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13066 if (!(nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
13067 return;
13068
13069 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13070 if (g.ActiveId != 0)
13071 {
13072 ClearActiveID();
13073 }
13074 else if (g.NavLayer != ImGuiNavLayer_Main)
13075 {
13076 // Leave the "menu" layer
13077 NavRestoreLayer(layer: ImGuiNavLayer_Main);
13078 NavRestoreHighlightAfterMove();
13079 }
13080 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13081 {
13082 // Exit child window
13083 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13084 ImGuiWindow* parent_window = child_window->ParentWindow;
13085 IM_ASSERT(child_window->ChildId != 0);
13086 FocusWindow(window: parent_window);
13087 SetNavID(id: child_window->ChildId, nav_layer: ImGuiNavLayer_Main, focus_scope_id: 0, rect_rel: WindowRectAbsToRel(window: parent_window, r: child_window->Rect()));
13088 NavRestoreHighlightAfterMove();
13089 }
13090 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13091 {
13092 // Close open popup/menu
13093 ClosePopupToLevel(remaining: g.OpenPopupStack.Size - 1, restore_focus_to_window_under_popup: true);
13094 }
13095 else
13096 {
13097 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13098 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13099 g.NavWindow->NavLastIds[0] = 0;
13100 g.NavId = 0;
13101 }
13102}
13103
13104// Handle PageUp/PageDown/Home/End keys
13105// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13106// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13107// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13108static float ImGui::NavUpdatePageUpPageDown()
13109{
13110 ImGuiContext& g = *GImGui;
13111 ImGuiWindow* window = g.NavWindow;
13112 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13113 return 0.0f;
13114
13115 const bool page_up_held = IsKeyDown(key: ImGuiKey_PageUp, ImGuiKeyOwner_None);
13116 const bool page_down_held = IsKeyDown(key: ImGuiKey_PageDown, ImGuiKeyOwner_None);
13117 const bool home_pressed = IsKeyPressed(key: ImGuiKey_Home, ImGuiKeyOwner_None, flags: ImGuiInputFlags_Repeat);
13118 const bool end_pressed = IsKeyPressed(key: ImGuiKey_End, ImGuiKeyOwner_None, flags: ImGuiInputFlags_Repeat);
13119 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13120 return 0.0f;
13121
13122 if (g.NavLayer != ImGuiNavLayer_Main)
13123 NavRestoreLayer(layer: ImGuiNavLayer_Main);
13124
13125 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13126 {
13127 // Fallback manual-scroll when window has no navigable item
13128 if (IsKeyPressed(key: ImGuiKey_PageUp, ImGuiKeyOwner_None, flags: ImGuiInputFlags_Repeat))
13129 SetScrollY(window, scroll_y: window->Scroll.y - window->InnerRect.GetHeight());
13130 else if (IsKeyPressed(key: ImGuiKey_PageDown, ImGuiKeyOwner_None, flags: ImGuiInputFlags_Repeat))
13131 SetScrollY(window, scroll_y: window->Scroll.y + window->InnerRect.GetHeight());
13132 else if (home_pressed)
13133 SetScrollY(window, scroll_y: 0.0f);
13134 else if (end_pressed)
13135 SetScrollY(window, scroll_y: window->ScrollMax.y);
13136 }
13137 else
13138 {
13139 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13140 const float page_offset_y = ImMax(lhs: 0.0f, rhs: window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13141 float nav_scoring_rect_offset_y = 0.0f;
13142 if (IsKeyPressed(key: ImGuiKey_PageUp, repeat: true))
13143 {
13144 nav_scoring_rect_offset_y = -page_offset_y;
13145 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)
13146 g.NavMoveClipDir = ImGuiDir_Up;
13147 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13148 }
13149 else if (IsKeyPressed(key: ImGuiKey_PageDown, repeat: true))
13150 {
13151 nav_scoring_rect_offset_y = +page_offset_y;
13152 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)
13153 g.NavMoveClipDir = ImGuiDir_Down;
13154 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13155 }
13156 else if (home_pressed)
13157 {
13158 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13159 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13160 // Preserve current horizontal position if we have any.
13161 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13162 if (nav_rect_rel.IsInverted())
13163 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13164 g.NavMoveDir = ImGuiDir_Down;
13165 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13166 // FIXME-NAV: MoveClipDir left to _None, intentional?
13167 }
13168 else if (end_pressed)
13169 {
13170 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13171 if (nav_rect_rel.IsInverted())
13172 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13173 g.NavMoveDir = ImGuiDir_Up;
13174 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13175 // FIXME-NAV: MoveClipDir left to _None, intentional?
13176 }
13177 return nav_scoring_rect_offset_y;
13178 }
13179 return 0.0f;
13180}
13181
13182static void ImGui::NavEndFrame()
13183{
13184 ImGuiContext& g = *GImGui;
13185
13186 // Show CTRL+TAB list window
13187 if (g.NavWindowingTarget != NULL)
13188 NavUpdateWindowingOverlay();
13189
13190 // Perform wrap-around in menus
13191 // 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.
13192 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13193 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13194 NavUpdateCreateWrappingRequest();
13195}
13196
13197static void ImGui::NavUpdateCreateWrappingRequest()
13198{
13199 ImGuiContext& g = *GImGui;
13200 ImGuiWindow* window = g.NavWindow;
13201
13202 bool do_forward = false;
13203 ImRect bb_rel = window->NavRectRel[g.NavLayer];
13204 ImGuiDir clip_dir = g.NavMoveDir;
13205
13206 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13207 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13208 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13209 {
13210 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13211 if (move_flags & ImGuiNavMoveFlags_WrapX)
13212 {
13213 bb_rel.TranslateY(dy: -bb_rel.GetHeight()); // Previous row
13214 clip_dir = ImGuiDir_Up;
13215 }
13216 do_forward = true;
13217 }
13218 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13219 {
13220 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13221 if (move_flags & ImGuiNavMoveFlags_WrapX)
13222 {
13223 bb_rel.TranslateY(dy: +bb_rel.GetHeight()); // Next row
13224 clip_dir = ImGuiDir_Down;
13225 }
13226 do_forward = true;
13227 }
13228 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13229 {
13230 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13231 if (move_flags & ImGuiNavMoveFlags_WrapY)
13232 {
13233 bb_rel.TranslateX(dx: -bb_rel.GetWidth()); // Previous column
13234 clip_dir = ImGuiDir_Left;
13235 }
13236 do_forward = true;
13237 }
13238 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13239 {
13240 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13241 if (move_flags & ImGuiNavMoveFlags_WrapY)
13242 {
13243 bb_rel.TranslateX(dx: +bb_rel.GetWidth()); // Next column
13244 clip_dir = ImGuiDir_Right;
13245 }
13246 do_forward = true;
13247 }
13248 if (!do_forward)
13249 return;
13250 window->NavRectRel[g.NavLayer] = bb_rel;
13251 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
13252 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13253 NavMoveRequestForward(move_dir: g.NavMoveDir, clip_dir, move_flags, scroll_flags: g.NavMoveScrollFlags);
13254}
13255
13256static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13257{
13258 ImGuiContext& g = *GImGui;
13259 IM_UNUSED(g);
13260 int order = window->FocusOrder;
13261 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13262 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13263 return order;
13264}
13265
13266static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13267{
13268 ImGuiContext& g = *GImGui;
13269 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13270 if (ImGui::IsWindowNavFocusable(window: g.WindowsFocusOrder[i]))
13271 return g.WindowsFocusOrder[i];
13272 return NULL;
13273}
13274
13275static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13276{
13277 ImGuiContext& g = *GImGui;
13278 IM_ASSERT(g.NavWindowingTarget);
13279 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13280 return;
13281
13282 const int i_current = ImGui::FindWindowFocusIndex(window: g.NavWindowingTarget);
13283 ImGuiWindow* window_target = FindWindowNavFocusable(i_start: i_current + focus_change_dir, i_stop: -INT_MAX, dir: focus_change_dir);
13284 if (!window_target)
13285 window_target = FindWindowNavFocusable(i_start: (focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_stop: i_current, dir: focus_change_dir);
13286 if (window_target) // Don't reset windowing target if there's a single window in the list
13287 {
13288 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13289 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13290 }
13291 g.NavWindowingToggleLayer = false;
13292}
13293
13294// Windowing management mode
13295// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13296// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13297static void ImGui::NavUpdateWindowing()
13298{
13299 ImGuiContext& g = *GImGui;
13300 ImGuiIO& io = g.IO;
13301
13302 ImGuiWindow* apply_focus_window = NULL;
13303 bool apply_toggle_layer = false;
13304
13305 ImGuiWindow* modal_window = GetTopMostPopupModal();
13306 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.
13307 if (!allow_windowing)
13308 g.NavWindowingTarget = NULL;
13309
13310 // Fade out
13311 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13312 {
13313 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, rhs: 0.0f);
13314 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13315 g.NavWindowingTargetAnim = NULL;
13316 }
13317
13318 // Start CTRL+Tab or Square+L/R window selection
13319 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13320 const ImGuiID owner_id = ImHashStr(data_p: "###NavUpdateWindowing");
13321 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13322 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13323 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(key_chord: g.ConfigNavWindowingKeyNext, owner_id, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13324 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(key_chord: g.ConfigNavWindowingKeyPrev, owner_id, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13325 const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, owner_id: 0, flags: ImGuiInputFlags_None);
13326 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13327 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13328 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(i_start: g.WindowsFocusOrder.Size - 1, i_stop: -INT_MAX, dir: -1))
13329 {
13330 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13331 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13332 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13333 g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13334 g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13335
13336 // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
13337 if (keyboard_next_window || keyboard_prev_window)
13338 SetKeyOwnersForKeyChord(key_chord: (g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13339 }
13340
13341 // Gamepad update
13342 g.NavWindowingTimer += io.DeltaTime;
13343 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13344 {
13345 // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13346 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha, rhs: ImSaturate(f: (g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13347
13348 // Select window to focus
13349 const int focus_change_dir = (int)IsKeyPressed(key: ImGuiKey_GamepadL1) - (int)IsKeyPressed(key: ImGuiKey_GamepadR1);
13350 if (focus_change_dir != 0)
13351 {
13352 NavUpdateWindowingHighlightWindow(focus_change_dir);
13353 g.NavWindowingHighlightAlpha = 1.0f;
13354 }
13355
13356 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13357 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13358 {
13359 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13360 if (g.NavWindowingToggleLayer && g.NavWindow)
13361 apply_toggle_layer = true;
13362 else if (!g.NavWindowingToggleLayer)
13363 apply_focus_window = g.NavWindowingTarget;
13364 g.NavWindowingTarget = NULL;
13365 }
13366 }
13367
13368 // Keyboard: Focus
13369 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13370 {
13371 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13372 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13373 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13374 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha, rhs: ImSaturate(f: (g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13375 if (keyboard_next_window || keyboard_prev_window)
13376 NavUpdateWindowingHighlightWindow(focus_change_dir: keyboard_next_window ? -1 : +1);
13377 else if ((io.KeyMods & shared_mods) != shared_mods)
13378 apply_focus_window = g.NavWindowingTarget;
13379 }
13380
13381 // Keyboard: Press and Release ALT to toggle menu layer
13382 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13383 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13384 if (nav_keyboard_active && IsKeyPressed(key: windowing_toggle_key, ImGuiKeyOwner_None))
13385 {
13386 g.NavWindowingToggleLayer = true;
13387 g.NavWindowingToggleKey = windowing_toggle_key;
13388 g.NavInputSource = ImGuiInputSource_Keyboard;
13389 break;
13390 }
13391 if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13392 {
13393 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13394 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13395 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13396 // We cancel toggling nav layer if an owner has claimed the key.
13397 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13398 g.NavWindowingToggleLayer = false;
13399 if (TestKeyOwner(key: g.NavWindowingToggleKey, ImGuiKeyOwner_None) == false || TestKeyOwner(key: ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13400 g.NavWindowingToggleLayer = false;
13401
13402 // Apply layer toggle on Alt release
13403 // 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.
13404 if (IsKeyReleased(key: g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13405 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13406 if (IsMousePosValid(mouse_pos: &io.MousePos) == IsMousePosValid(mouse_pos: &io.MousePosPrev))
13407 apply_toggle_layer = true;
13408 if (!IsKeyDown(key: g.NavWindowingToggleKey))
13409 g.NavWindowingToggleLayer = false;
13410 }
13411
13412 // Move window
13413 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13414 {
13415 ImVec2 nav_move_dir;
13416 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13417 nav_move_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
13418 if (g.NavInputSource == ImGuiInputSource_Gamepad)
13419 nav_move_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
13420 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13421 {
13422 const float NAV_MOVE_SPEED = 800.0f;
13423 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(lhs: io.DisplayFramebufferScale.x, rhs: io.DisplayFramebufferScale.y);
13424 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13425 g.NavDisableMouseHover = true;
13426 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaPos);
13427 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13428 {
13429 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13430 SetWindowPos(window: moving_window, pos: moving_window->Pos + accum_floored, cond: ImGuiCond_Always);
13431 g.NavWindowingAccumDeltaPos -= accum_floored;
13432 }
13433 }
13434 }
13435
13436 // Apply final focus
13437 if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13438 {
13439 // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13440 // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13441 ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13442 ClearActiveID();
13443 NavRestoreHighlightAfterMove();
13444 ClosePopupsOverWindow(ref_window: apply_focus_window, restore_focus_to_window_under_popup: false);
13445 FocusWindow(window: apply_focus_window, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
13446 apply_focus_window = g.NavWindow;
13447 if (apply_focus_window->NavLastIds[0] == 0)
13448 NavInitWindow(window: apply_focus_window, force_reinit: false);
13449
13450 // If the window has ONLY a menu layer (no main layer), select it directly
13451 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13452 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13453 // the target window as already been previewed once.
13454 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13455 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13456 // won't be valid.
13457 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13458 g.NavLayer = ImGuiNavLayer_Menu;
13459
13460 // Request OS level focus
13461 if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13462 g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13463 }
13464 if (apply_focus_window)
13465 g.NavWindowingTarget = NULL;
13466
13467 // Apply menu/layer toggle
13468 if (apply_toggle_layer && g.NavWindow)
13469 {
13470 ClearActiveID();
13471
13472 // Move to parent menu if necessary
13473 ImGuiWindow* new_nav_window = g.NavWindow;
13474 while (new_nav_window->ParentWindow
13475 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13476 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13477 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13478 new_nav_window = new_nav_window->ParentWindow;
13479 if (new_nav_window != g.NavWindow)
13480 {
13481 ImGuiWindow* old_nav_window = g.NavWindow;
13482 FocusWindow(window: new_nav_window);
13483 new_nav_window->NavLastChildNavWindow = old_nav_window;
13484 }
13485
13486 // Toggle layer
13487 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13488 if (new_nav_layer != g.NavLayer)
13489 {
13490 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13491 const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13492 if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13493 g.NavWindow->NavLastIds[new_nav_layer] = 0;
13494 NavRestoreLayer(layer: new_nav_layer);
13495 NavRestoreHighlightAfterMove();
13496 }
13497 }
13498}
13499
13500// Window has already passed the IsWindowNavFocusable()
13501static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13502{
13503 if (window->Flags & ImGuiWindowFlags_Popup)
13504 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingPopup);
13505 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(s1: window->Name, s2: "##MainMenuBar") == 0)
13506 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingMainMenuBar);
13507 if (window->DockNodeAsHost)
13508 return "(Dock node)"; // Not normally shown to user.
13509 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingUntitled);
13510}
13511
13512// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13513void ImGui::NavUpdateWindowingOverlay()
13514{
13515 ImGuiContext& g = *GImGui;
13516 IM_ASSERT(g.NavWindowingTarget != NULL);
13517
13518 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13519 return;
13520
13521 if (g.NavWindowingListWindow == NULL)
13522 g.NavWindowingListWindow = FindWindowByName(name: "###NavWindowingList");
13523 const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13524 SetNextWindowSizeConstraints(size_min: ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), size_max: ImVec2(FLT_MAX, FLT_MAX));
13525 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_Always, pivot: ImVec2(0.5f, 0.5f));
13526 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.WindowPadding * 2.0f);
13527 Begin(name: "###NavWindowingList", NULL, flags: ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13528 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13529 {
13530 ImGuiWindow* window = g.WindowsFocusOrder[n];
13531 IM_ASSERT(window != NULL); // Fix static analyzers
13532 if (!IsWindowNavFocusable(window))
13533 continue;
13534 const char* label = window->Name;
13535 if (label == FindRenderedTextEnd(text: label))
13536 label = GetFallbackWindowNameForWindowingList(window);
13537 Selectable(label, selected: g.NavWindowingTarget == window);
13538 }
13539 End();
13540 PopStyleVar();
13541}
13542
13543
13544//-----------------------------------------------------------------------------
13545// [SECTION] DRAG AND DROP
13546//-----------------------------------------------------------------------------
13547
13548bool ImGui::IsDragDropActive()
13549{
13550 ImGuiContext& g = *GImGui;
13551 return g.DragDropActive;
13552}
13553
13554void ImGui::ClearDragDrop()
13555{
13556 ImGuiContext& g = *GImGui;
13557 g.DragDropActive = false;
13558 g.DragDropPayload.Clear();
13559 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13560 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13561 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13562 g.DragDropAcceptFrameCount = -1;
13563
13564 g.DragDropPayloadBufHeap.clear();
13565 memset(s: &g.DragDropPayloadBufLocal, c: 0, n: sizeof(g.DragDropPayloadBufLocal));
13566}
13567
13568bool ImGui::BeginTooltipHidden()
13569{
13570 ImGuiContext& g = *GImGui;
13571 bool ret = Begin(name: "##Tooltip_Hidden", NULL, flags: ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13572 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13573 return ret;
13574}
13575
13576// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13577// If the item has an identifier:
13578// - This assume/require the item to be activated (typically via ButtonBehavior).
13579// - 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.
13580// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13581// If the item has no identifier:
13582// - Currently always assume left mouse button.
13583bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13584{
13585 ImGuiContext& g = *GImGui;
13586 ImGuiWindow* window = g.CurrentWindow;
13587
13588 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13589 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13590 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13591
13592 bool source_drag_active = false;
13593 ImGuiID source_id = 0;
13594 ImGuiID source_parent_id = 0;
13595 if (!(flags & ImGuiDragDropFlags_SourceExtern))
13596 {
13597 source_id = g.LastItemData.ID;
13598 if (source_id != 0)
13599 {
13600 // Common path: items with ID
13601 if (g.ActiveId != source_id)
13602 return false;
13603 if (g.ActiveIdMouseButton != -1)
13604 mouse_button = g.ActiveIdMouseButton;
13605 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13606 return false;
13607 g.ActiveIdAllowOverlap = false;
13608 }
13609 else
13610 {
13611 // Uncommon path: items without ID
13612 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13613 return false;
13614 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13615 return false;
13616
13617 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13618 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13619 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13620 {
13621 IM_ASSERT(0);
13622 return false;
13623 }
13624
13625 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13626 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13627 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13628 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13629 // Rely on keeping other window->LastItemXXX fields intact.
13630 source_id = g.LastItemData.ID = window->GetIDFromRectangle(r_abs: g.LastItemData.Rect);
13631 KeepAliveID(id: source_id);
13632 bool is_hovered = ItemHoverable(bb: g.LastItemData.Rect, id: source_id, item_flags: g.LastItemData.InFlags);
13633 if (is_hovered && g.IO.MouseClicked[mouse_button])
13634 {
13635 SetActiveID(id: source_id, window);
13636 FocusWindow(window);
13637 }
13638 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13639 g.ActiveIdAllowOverlap = is_hovered;
13640 }
13641 if (g.ActiveId != source_id)
13642 return false;
13643 source_parent_id = window->IDStack.back();
13644 source_drag_active = IsMouseDragging(button: mouse_button);
13645
13646 // Disable navigation and key inputs while dragging + cancel existing request if any
13647 SetActiveIdUsingAllKeyboardKeys();
13648 }
13649 else
13650 {
13651 window = NULL;
13652 source_id = ImHashStr(data_p: "#SourceExtern");
13653 source_drag_active = true;
13654 }
13655
13656 if (source_drag_active)
13657 {
13658 if (!g.DragDropActive)
13659 {
13660 IM_ASSERT(source_id != 0);
13661 ClearDragDrop();
13662 ImGuiPayload& payload = g.DragDropPayload;
13663 payload.SourceId = source_id;
13664 payload.SourceParentId = source_parent_id;
13665 g.DragDropActive = true;
13666 g.DragDropSourceFlags = flags;
13667 g.DragDropMouseButton = mouse_button;
13668 if (payload.SourceId == g.ActiveId)
13669 g.ActiveIdNoClearOnFocusLoss = true;
13670 }
13671 g.DragDropSourceFrameCount = g.FrameCount;
13672 g.DragDropWithinSource = true;
13673
13674 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13675 {
13676 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13677 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13678 bool ret;
13679 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13680 ret = BeginTooltipHidden();
13681 else
13682 ret = BeginTooltip();
13683 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13684 IM_UNUSED(ret);
13685 }
13686
13687 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13688 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13689
13690 return true;
13691 }
13692 return false;
13693}
13694
13695void ImGui::EndDragDropSource()
13696{
13697 ImGuiContext& g = *GImGui;
13698 IM_ASSERT(g.DragDropActive);
13699 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13700
13701 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13702 EndTooltip();
13703
13704 // Discard the drag if have not called SetDragDropPayload()
13705 if (g.DragDropPayload.DataFrameCount == -1)
13706 ClearDragDrop();
13707 g.DragDropWithinSource = false;
13708}
13709
13710// Use 'cond' to choose to submit payload on drag start or every frame
13711bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13712{
13713 ImGuiContext& g = *GImGui;
13714 ImGuiPayload& payload = g.DragDropPayload;
13715 if (cond == 0)
13716 cond = ImGuiCond_Always;
13717
13718 IM_ASSERT(type != NULL);
13719 IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13720 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13721 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13722 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
13723
13724 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13725 {
13726 // Copy payload
13727 ImStrncpy(dst: payload.DataType, src: type, IM_ARRAYSIZE(payload.DataType));
13728 g.DragDropPayloadBufHeap.resize(new_size: 0);
13729 if (data_size > sizeof(g.DragDropPayloadBufLocal))
13730 {
13731 // Store in heap
13732 g.DragDropPayloadBufHeap.resize(new_size: (int)data_size);
13733 payload.Data = g.DragDropPayloadBufHeap.Data;
13734 memcpy(dest: payload.Data, src: data, n: data_size);
13735 }
13736 else if (data_size > 0)
13737 {
13738 // Store locally
13739 memset(s: &g.DragDropPayloadBufLocal, c: 0, n: sizeof(g.DragDropPayloadBufLocal));
13740 payload.Data = g.DragDropPayloadBufLocal;
13741 memcpy(dest: payload.Data, src: data, n: data_size);
13742 }
13743 else
13744 {
13745 payload.Data = NULL;
13746 }
13747 payload.DataSize = (int)data_size;
13748 }
13749 payload.DataFrameCount = g.FrameCount;
13750
13751 // Return whether the payload has been accepted
13752 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13753}
13754
13755bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13756{
13757 ImGuiContext& g = *GImGui;
13758 if (!g.DragDropActive)
13759 return false;
13760
13761 ImGuiWindow* window = g.CurrentWindow;
13762 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13763 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13764 return false;
13765 IM_ASSERT(id != 0);
13766 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max) || (id == g.DragDropPayload.SourceId))
13767 return false;
13768 if (window->SkipItems)
13769 return false;
13770
13771 IM_ASSERT(g.DragDropWithinTarget == false);
13772 g.DragDropTargetRect = bb;
13773 g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
13774 g.DragDropTargetId = id;
13775 g.DragDropWithinTarget = true;
13776 return true;
13777}
13778
13779// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13780// 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.
13781// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13782// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13783bool ImGui::BeginDragDropTarget()
13784{
13785 ImGuiContext& g = *GImGui;
13786 if (!g.DragDropActive)
13787 return false;
13788
13789 ImGuiWindow* window = g.CurrentWindow;
13790 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13791 return false;
13792 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13793 if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13794 return false;
13795
13796 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13797 ImGuiID id = g.LastItemData.ID;
13798 if (id == 0)
13799 {
13800 id = window->GetIDFromRectangle(r_abs: display_rect);
13801 KeepAliveID(id);
13802 }
13803 if (g.DragDropPayload.SourceId == id)
13804 return false;
13805
13806 IM_ASSERT(g.DragDropWithinTarget == false);
13807 g.DragDropTargetRect = display_rect;
13808 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
13809 g.DragDropTargetId = id;
13810 g.DragDropWithinTarget = true;
13811 return true;
13812}
13813
13814bool ImGui::IsDragDropPayloadBeingAccepted()
13815{
13816 ImGuiContext& g = *GImGui;
13817 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13818}
13819
13820const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13821{
13822 ImGuiContext& g = *GImGui;
13823 ImGuiPayload& payload = g.DragDropPayload;
13824 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13825 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
13826 if (type != NULL && !payload.IsDataType(type))
13827 return NULL;
13828
13829 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13830 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13831 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13832 ImRect r = g.DragDropTargetRect;
13833 float r_surface = r.GetWidth() * r.GetHeight();
13834 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13835 return NULL;
13836
13837 g.DragDropAcceptFlags = flags;
13838 g.DragDropAcceptIdCurr = g.DragDropTargetId;
13839 g.DragDropAcceptIdCurrRectSurface = r_surface;
13840 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13841
13842 // Render default drop visuals
13843 payload.Preview = was_accepted_previously;
13844 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13845 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13846 RenderDragDropTargetRect(bb: r, item_clip_rect: g.DragDropTargetClipRect);
13847
13848 g.DragDropAcceptFrameCount = g.FrameCount;
13849 payload.Delivery = was_accepted_previously && !IsMouseDown(button: g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13850 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13851 return NULL;
13852
13853 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13854 return &payload;
13855}
13856
13857// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13858void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
13859{
13860 ImGuiContext& g = *GImGui;
13861 ImGuiWindow* window = g.CurrentWindow;
13862 ImRect bb_display = bb;
13863 bb_display.ClipWith(r: item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13864 bb_display.Expand(amount: 3.5f);
13865 bool push_clip_rect = !window->ClipRect.Contains(r: bb_display);
13866 if (push_clip_rect)
13867 window->DrawList->PushClipRectFullScreen();
13868 window->DrawList->AddRect(p_min: bb_display.Min, p_max: bb_display.Max, col: GetColorU32(idx: ImGuiCol_DragDropTarget), rounding: 0.0f, flags: 0, thickness: 2.0f);
13869 if (push_clip_rect)
13870 window->DrawList->PopClipRect();
13871}
13872
13873const ImGuiPayload* ImGui::GetDragDropPayload()
13874{
13875 ImGuiContext& g = *GImGui;
13876 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13877}
13878
13879void ImGui::EndDragDropTarget()
13880{
13881 ImGuiContext& g = *GImGui;
13882 IM_ASSERT(g.DragDropActive);
13883 IM_ASSERT(g.DragDropWithinTarget);
13884 g.DragDropWithinTarget = false;
13885
13886 // Clear drag and drop state payload right after delivery
13887 if (g.DragDropPayload.Delivery)
13888 ClearDragDrop();
13889}
13890
13891//-----------------------------------------------------------------------------
13892// [SECTION] LOGGING/CAPTURING
13893//-----------------------------------------------------------------------------
13894// All text output from the interface can be captured into tty/file/clipboard.
13895// By default, tree nodes are automatically opened during logging.
13896//-----------------------------------------------------------------------------
13897
13898// Pass text data straight to log (without being displayed)
13899static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13900{
13901 if (g.LogFile)
13902 {
13903 g.LogBuffer.Buf.resize(new_size: 0);
13904 g.LogBuffer.appendfv(fmt, args);
13905 ImFileWrite(data: g.LogBuffer.c_str(), sz: sizeof(char), count: (ImU64)g.LogBuffer.size(), f: g.LogFile);
13906 }
13907 else
13908 {
13909 g.LogBuffer.appendfv(fmt, args);
13910 }
13911}
13912
13913void ImGui::LogText(const char* fmt, ...)
13914{
13915 ImGuiContext& g = *GImGui;
13916 if (!g.LogEnabled)
13917 return;
13918
13919 va_list args;
13920 va_start(args, fmt);
13921 LogTextV(g, fmt, args);
13922 va_end(args);
13923}
13924
13925void ImGui::LogTextV(const char* fmt, va_list args)
13926{
13927 ImGuiContext& g = *GImGui;
13928 if (!g.LogEnabled)
13929 return;
13930
13931 LogTextV(g, fmt, args);
13932}
13933
13934// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13935// We split text into individual lines to add current tree level padding
13936// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13937void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13938{
13939 ImGuiContext& g = *GImGui;
13940 ImGuiWindow* window = g.CurrentWindow;
13941
13942 const char* prefix = g.LogNextPrefix;
13943 const char* suffix = g.LogNextSuffix;
13944 g.LogNextPrefix = g.LogNextSuffix = NULL;
13945
13946 if (!text_end)
13947 text_end = FindRenderedTextEnd(text, text_end);
13948
13949 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13950 if (ref_pos)
13951 g.LogLinePosY = ref_pos->y;
13952 if (log_new_line)
13953 {
13954 LogText(IM_NEWLINE);
13955 g.LogLineFirstItem = true;
13956 }
13957
13958 if (prefix)
13959 LogRenderedText(ref_pos, text: prefix, text_end: prefix + strlen(s: prefix)); // Calculate end ourself to ensure "##" are included here.
13960
13961 // Re-adjust padding if we have popped out of our starting depth
13962 if (g.LogDepthRef > window->DC.TreeDepth)
13963 g.LogDepthRef = window->DC.TreeDepth;
13964 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13965
13966 const char* text_remaining = text;
13967 for (;;)
13968 {
13969 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13970 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13971 const char* line_start = text_remaining;
13972 const char* line_end = ImStreolRange(str: line_start, str_end: text_end);
13973 const bool is_last_line = (line_end == text_end);
13974 if (line_start != line_end || !is_last_line)
13975 {
13976 const int line_length = (int)(line_end - line_start);
13977 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13978 LogText(fmt: "%*s%.*s", indentation, "", line_length, line_start);
13979 g.LogLineFirstItem = false;
13980 if (*line_end == '\n')
13981 {
13982 LogText(IM_NEWLINE);
13983 g.LogLineFirstItem = true;
13984 }
13985 }
13986 if (is_last_line)
13987 break;
13988 text_remaining = line_end + 1;
13989 }
13990
13991 if (suffix)
13992 LogRenderedText(ref_pos, text: suffix, text_end: suffix + strlen(s: suffix));
13993}
13994
13995// Start logging/capturing text output
13996void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13997{
13998 ImGuiContext& g = *GImGui;
13999 ImGuiWindow* window = g.CurrentWindow;
14000 IM_ASSERT(g.LogEnabled == false);
14001 IM_ASSERT(g.LogFile == NULL);
14002 IM_ASSERT(g.LogBuffer.empty());
14003 g.LogEnabled = true;
14004 g.LogType = type;
14005 g.LogNextPrefix = g.LogNextSuffix = NULL;
14006 g.LogDepthRef = window->DC.TreeDepth;
14007 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14008 g.LogLinePosY = FLT_MAX;
14009 g.LogLineFirstItem = true;
14010}
14011
14012// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14013void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14014{
14015 ImGuiContext& g = *GImGui;
14016 g.LogNextPrefix = prefix;
14017 g.LogNextSuffix = suffix;
14018}
14019
14020void ImGui::LogToTTY(int auto_open_depth)
14021{
14022 ImGuiContext& g = *GImGui;
14023 if (g.LogEnabled)
14024 return;
14025 IM_UNUSED(auto_open_depth);
14026#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14027 LogBegin(type: ImGuiLogType_TTY, auto_open_depth);
14028 g.LogFile = stdout;
14029#endif
14030}
14031
14032// Start logging/capturing text output to given file
14033void ImGui::LogToFile(int auto_open_depth, const char* filename)
14034{
14035 ImGuiContext& g = *GImGui;
14036 if (g.LogEnabled)
14037 return;
14038
14039 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14040 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14041 // By opening the file in binary mode "ab" we have consistent output everywhere.
14042 if (!filename)
14043 filename = g.IO.LogFilename;
14044 if (!filename || !filename[0])
14045 return;
14046 ImFileHandle f = ImFileOpen(filename, mode: "ab");
14047 if (!f)
14048 {
14049 IM_ASSERT(0);
14050 return;
14051 }
14052
14053 LogBegin(type: ImGuiLogType_File, auto_open_depth);
14054 g.LogFile = f;
14055}
14056
14057// Start logging/capturing text output to clipboard
14058void ImGui::LogToClipboard(int auto_open_depth)
14059{
14060 ImGuiContext& g = *GImGui;
14061 if (g.LogEnabled)
14062 return;
14063 LogBegin(type: ImGuiLogType_Clipboard, auto_open_depth);
14064}
14065
14066void ImGui::LogToBuffer(int auto_open_depth)
14067{
14068 ImGuiContext& g = *GImGui;
14069 if (g.LogEnabled)
14070 return;
14071 LogBegin(type: ImGuiLogType_Buffer, auto_open_depth);
14072}
14073
14074void ImGui::LogFinish()
14075{
14076 ImGuiContext& g = *GImGui;
14077 if (!g.LogEnabled)
14078 return;
14079
14080 LogText(IM_NEWLINE);
14081 switch (g.LogType)
14082 {
14083 case ImGuiLogType_TTY:
14084#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14085 fflush(stream: g.LogFile);
14086#endif
14087 break;
14088 case ImGuiLogType_File:
14089 ImFileClose(f: g.LogFile);
14090 break;
14091 case ImGuiLogType_Buffer:
14092 break;
14093 case ImGuiLogType_Clipboard:
14094 if (!g.LogBuffer.empty())
14095 SetClipboardText(g.LogBuffer.begin());
14096 break;
14097 case ImGuiLogType_None:
14098 IM_ASSERT(0);
14099 break;
14100 }
14101
14102 g.LogEnabled = false;
14103 g.LogType = ImGuiLogType_None;
14104 g.LogFile = NULL;
14105 g.LogBuffer.clear();
14106}
14107
14108// Helper to display logging buttons
14109// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14110void ImGui::LogButtons()
14111{
14112 ImGuiContext& g = *GImGui;
14113
14114 PushID(str_id: "LogButtons");
14115#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14116 const bool log_to_tty = Button(label: "Log To TTY"); SameLine();
14117#else
14118 const bool log_to_tty = false;
14119#endif
14120 const bool log_to_file = Button(label: "Log To File"); SameLine();
14121 const bool log_to_clipboard = Button(label: "Log To Clipboard"); SameLine();
14122 PushTabStop(tab_stop: false);
14123 SetNextItemWidth(80.0f);
14124 SliderInt(label: "Default Depth", v: &g.LogDepthToExpandDefault, v_min: 0, v_max: 9, NULL);
14125 PopTabStop();
14126 PopID();
14127
14128 // Start logging at the end of the function so that the buttons don't appear in the log
14129 if (log_to_tty)
14130 LogToTTY();
14131 if (log_to_file)
14132 LogToFile();
14133 if (log_to_clipboard)
14134 LogToClipboard();
14135}
14136
14137
14138//-----------------------------------------------------------------------------
14139// [SECTION] SETTINGS
14140//-----------------------------------------------------------------------------
14141// - UpdateSettings() [Internal]
14142// - MarkIniSettingsDirty() [Internal]
14143// - FindSettingsHandler() [Internal]
14144// - ClearIniSettings() [Internal]
14145// - LoadIniSettingsFromDisk()
14146// - LoadIniSettingsFromMemory()
14147// - SaveIniSettingsToDisk()
14148// - SaveIniSettingsToMemory()
14149//-----------------------------------------------------------------------------
14150// - CreateNewWindowSettings() [Internal]
14151// - FindWindowSettingsByID() [Internal]
14152// - FindWindowSettingsByWindow() [Internal]
14153// - ClearWindowSettings() [Internal]
14154// - WindowSettingsHandler_***() [Internal]
14155//-----------------------------------------------------------------------------
14156
14157// Called by NewFrame()
14158void ImGui::UpdateSettings()
14159{
14160 // Load settings on first frame (if not explicitly loaded manually before)
14161 ImGuiContext& g = *GImGui;
14162 if (!g.SettingsLoaded)
14163 {
14164 IM_ASSERT(g.SettingsWindows.empty());
14165 if (g.IO.IniFilename)
14166 LoadIniSettingsFromDisk(ini_filename: g.IO.IniFilename);
14167 g.SettingsLoaded = true;
14168 }
14169
14170 // Save settings (with a delay after the last modification, so we don't spam disk too much)
14171 if (g.SettingsDirtyTimer > 0.0f)
14172 {
14173 g.SettingsDirtyTimer -= g.IO.DeltaTime;
14174 if (g.SettingsDirtyTimer <= 0.0f)
14175 {
14176 if (g.IO.IniFilename != NULL)
14177 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
14178 else
14179 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14180 g.SettingsDirtyTimer = 0.0f;
14181 }
14182 }
14183}
14184
14185void ImGui::MarkIniSettingsDirty()
14186{
14187 ImGuiContext& g = *GImGui;
14188 if (g.SettingsDirtyTimer <= 0.0f)
14189 g.SettingsDirtyTimer = g.IO.IniSavingRate;
14190}
14191
14192void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14193{
14194 ImGuiContext& g = *GImGui;
14195 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14196 if (g.SettingsDirtyTimer <= 0.0f)
14197 g.SettingsDirtyTimer = g.IO.IniSavingRate;
14198}
14199
14200void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14201{
14202 ImGuiContext& g = *GImGui;
14203 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14204 g.SettingsHandlers.push_back(v: *handler);
14205}
14206
14207void ImGui::RemoveSettingsHandler(const char* type_name)
14208{
14209 ImGuiContext& g = *GImGui;
14210 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14211 g.SettingsHandlers.erase(it: handler);
14212}
14213
14214ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14215{
14216 ImGuiContext& g = *GImGui;
14217 const ImGuiID type_hash = ImHashStr(data_p: type_name);
14218 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14219 if (handler.TypeHash == type_hash)
14220 return &handler;
14221 return NULL;
14222}
14223
14224// Clear all settings (windows, tables, docking etc.)
14225void ImGui::ClearIniSettings()
14226{
14227 ImGuiContext& g = *GImGui;
14228 g.SettingsIniData.clear();
14229 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14230 if (handler.ClearAllFn != NULL)
14231 handler.ClearAllFn(&g, &handler);
14232}
14233
14234void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14235{
14236 size_t file_data_size = 0;
14237 char* file_data = (char*)ImFileLoadToMemory(filename: ini_filename, mode: "rb", out_file_size: &file_data_size);
14238 if (!file_data)
14239 return;
14240 if (file_data_size > 0)
14241 LoadIniSettingsFromMemory(ini_data: file_data, ini_size: (size_t)file_data_size);
14242 IM_FREE(file_data);
14243}
14244
14245// Zero-tolerance, no error reporting, cheap .ini parsing
14246// 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!
14247void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14248{
14249 ImGuiContext& g = *GImGui;
14250 IM_ASSERT(g.Initialized);
14251 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14252 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14253
14254 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14255 // 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..
14256 if (ini_size == 0)
14257 ini_size = strlen(s: ini_data);
14258 g.SettingsIniData.Buf.resize(new_size: (int)ini_size + 1);
14259 char* const buf = g.SettingsIniData.Buf.Data;
14260 char* const buf_end = buf + ini_size;
14261 memcpy(dest: buf, src: ini_data, n: ini_size);
14262 buf_end[0] = 0;
14263
14264 // Call pre-read handlers
14265 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14266 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14267 if (handler.ReadInitFn != NULL)
14268 handler.ReadInitFn(&g, &handler);
14269
14270 void* entry_data = NULL;
14271 ImGuiSettingsHandler* entry_handler = NULL;
14272
14273 char* line_end = NULL;
14274 for (char* line = buf; line < buf_end; line = line_end + 1)
14275 {
14276 // Skip new lines markers, then find end of the line
14277 while (*line == '\n' || *line == '\r')
14278 line++;
14279 line_end = line;
14280 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14281 line_end++;
14282 line_end[0] = 0;
14283 if (line[0] == ';')
14284 continue;
14285 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14286 {
14287 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14288 line_end[-1] = 0;
14289 const char* name_end = line_end - 1;
14290 const char* type_start = line + 1;
14291 char* type_end = (char*)(void*)ImStrchrRange(str: type_start, str_end: name_end, c: ']');
14292 const char* name_start = type_end ? ImStrchrRange(str: type_end + 1, str_end: name_end, c: '[') : NULL;
14293 if (!type_end || !name_start)
14294 continue;
14295 *type_end = 0; // Overwrite first ']'
14296 name_start++; // Skip second '['
14297 entry_handler = FindSettingsHandler(type_name: type_start);
14298 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14299 }
14300 else if (entry_handler != NULL && entry_data != NULL)
14301 {
14302 // Let type handler parse the line
14303 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14304 }
14305 }
14306 g.SettingsLoaded = true;
14307
14308 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14309 memcpy(dest: buf, src: ini_data, n: ini_size);
14310
14311 // Call post-read handlers
14312 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14313 if (handler.ApplyAllFn != NULL)
14314 handler.ApplyAllFn(&g, &handler);
14315}
14316
14317void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14318{
14319 ImGuiContext& g = *GImGui;
14320 g.SettingsDirtyTimer = 0.0f;
14321 if (!ini_filename)
14322 return;
14323
14324 size_t ini_data_size = 0;
14325 const char* ini_data = SaveIniSettingsToMemory(out_ini_size: &ini_data_size);
14326 ImFileHandle f = ImFileOpen(filename: ini_filename, mode: "wt");
14327 if (!f)
14328 return;
14329 ImFileWrite(data: ini_data, sz: sizeof(char), count: ini_data_size, f);
14330 ImFileClose(f);
14331}
14332
14333// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14334const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14335{
14336 ImGuiContext& g = *GImGui;
14337 g.SettingsDirtyTimer = 0.0f;
14338 g.SettingsIniData.Buf.resize(new_size: 0);
14339 g.SettingsIniData.Buf.push_back(v: 0);
14340 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14341 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14342 if (out_size)
14343 *out_size = (size_t)g.SettingsIniData.size();
14344 return g.SettingsIniData.c_str();
14345}
14346
14347ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14348{
14349 ImGuiContext& g = *GImGui;
14350
14351 if (g.IO.ConfigDebugIniSettings == false)
14352 {
14353 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14354 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14355 if (const char* p = strstr(haystack: name, needle: "###"))
14356 name = p;
14357 }
14358 const size_t name_len = strlen(s: name);
14359
14360 // Allocate chunk
14361 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14362 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(sz: chunk_size);
14363 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14364 settings->ID = ImHashStr(data_p: name, data_size: name_len);
14365 memcpy(dest: settings->GetName(), src: name, n: name_len + 1); // Store with zero terminator
14366
14367 return settings;
14368}
14369
14370// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14371// This is called once per window .ini entry + once per newly instantiated window.
14372ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14373{
14374 ImGuiContext& g = *GImGui;
14375 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
14376 if (settings->ID == id && !settings->WantDelete)
14377 return settings;
14378 return NULL;
14379}
14380
14381// This is faster if you are holding on a Window already as we don't need to perform a search.
14382ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14383{
14384 ImGuiContext& g = *GImGui;
14385 if (window->SettingsOffset != -1)
14386 return g.SettingsWindows.ptr_from_offset(off: window->SettingsOffset);
14387 return FindWindowSettingsByID(id: window->ID);
14388}
14389
14390// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14391void ImGui::ClearWindowSettings(const char* name)
14392{
14393 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14394 ImGuiContext& g = *GImGui;
14395 ImGuiWindow* window = FindWindowByName(name);
14396 if (window != NULL)
14397 {
14398 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14399 InitOrLoadWindowSettings(window, NULL);
14400 if (window->DockId != 0)
14401 DockContextProcessUndockWindow(ctx: &g, window, clear_persistent_docking_ref: true);
14402 }
14403 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(id: ImHashStr(data_p: name)))
14404 settings->WantDelete = true;
14405}
14406
14407static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14408{
14409 ImGuiContext& g = *ctx;
14410 for (ImGuiWindow* window : g.Windows)
14411 window->SettingsOffset = -1;
14412 g.SettingsWindows.clear();
14413}
14414
14415static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14416{
14417 ImGuiID id = ImHashStr(data_p: name);
14418 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14419 if (settings)
14420 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14421 else
14422 settings = ImGui::CreateNewWindowSettings(name);
14423 settings->ID = id;
14424 settings->WantApply = true;
14425 return (void*)settings;
14426}
14427
14428static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14429{
14430 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14431 int x, y;
14432 int i;
14433 ImU32 u1;
14434 if (sscanf(s: line, format: "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
14435 else if (sscanf(s: line, format: "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
14436 else if (sscanf(s: line, format: "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
14437 else if (sscanf(s: line, format: "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14438 else if (sscanf(s: line, format: "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
14439 else if (sscanf(s: line, format: "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
14440 else if (sscanf(s: line, format: "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
14441 else if (sscanf(s: line, format: "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
14442 else if (sscanf(s: line, format: "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
14443}
14444
14445// Apply to existing windows (if any)
14446static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14447{
14448 ImGuiContext& g = *ctx;
14449 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
14450 if (settings->WantApply)
14451 {
14452 if (ImGuiWindow* window = ImGui::FindWindowByID(id: settings->ID))
14453 ApplyWindowSettings(window, settings);
14454 settings->WantApply = false;
14455 }
14456}
14457
14458static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14459{
14460 // Gather data from windows that were active during this session
14461 // (if a window wasn't opened in this session we preserve its settings)
14462 ImGuiContext& g = *ctx;
14463 for (ImGuiWindow* window : g.Windows)
14464 {
14465 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14466 continue;
14467
14468 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14469 if (!settings)
14470 {
14471 settings = ImGui::CreateNewWindowSettings(name: window->Name);
14472 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
14473 }
14474 IM_ASSERT(settings->ID == window->ID);
14475 settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14476 settings->Size = ImVec2ih(window->SizeFull);
14477 settings->ViewportId = window->ViewportId;
14478 settings->ViewportPos = ImVec2ih(window->ViewportPos);
14479 IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14480 settings->DockId = window->DockId;
14481 settings->ClassId = window->WindowClass.ClassId;
14482 settings->DockOrder = window->DockOrder;
14483 settings->Collapsed = window->Collapsed;
14484 settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14485 settings->WantDelete = false;
14486 }
14487
14488 // Write to text buffer
14489 buf->reserve(capacity: buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14490 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
14491 {
14492 if (settings->WantDelete)
14493 continue;
14494 const char* settings_name = settings->GetName();
14495 buf->appendf(fmt: "[%s][%s]\n", handler->TypeName, settings_name);
14496 if (settings->IsChild)
14497 {
14498 buf->appendf(fmt: "IsChild=1\n");
14499 buf->appendf(fmt: "Size=%d,%d\n", settings->Size.x, settings->Size.y);
14500 }
14501 else
14502 {
14503 if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14504 {
14505 buf->appendf(fmt: "ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14506 buf->appendf(fmt: "ViewportId=0x%08X\n", settings->ViewportId);
14507 }
14508 if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14509 buf->appendf(fmt: "Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14510 if (settings->Size.x != 0 || settings->Size.y != 0)
14511 buf->appendf(fmt: "Size=%d,%d\n", settings->Size.x, settings->Size.y);
14512 buf->appendf(fmt: "Collapsed=%d\n", settings->Collapsed);
14513 if (settings->DockId != 0)
14514 {
14515 //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.
14516 if (settings->DockOrder == -1)
14517 buf->appendf(fmt: "DockId=0x%08X\n", settings->DockId);
14518 else
14519 buf->appendf(fmt: "DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14520 if (settings->ClassId != 0)
14521 buf->appendf(fmt: "ClassId=0x%08X\n", settings->ClassId);
14522 }
14523 }
14524 buf->append(str: "\n");
14525 }
14526}
14527
14528
14529//-----------------------------------------------------------------------------
14530// [SECTION] LOCALIZATION
14531//-----------------------------------------------------------------------------
14532
14533void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14534{
14535 ImGuiContext& g = *GImGui;
14536 for (int n = 0; n < count; n++)
14537 g.LocalizationTable[entries[n].Key] = entries[n].Text;
14538}
14539
14540
14541//-----------------------------------------------------------------------------
14542// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14543//-----------------------------------------------------------------------------
14544// - GetMainViewport()
14545// - FindViewportByID()
14546// - FindViewportByPlatformHandle()
14547// - SetCurrentViewport() [Internal]
14548// - SetWindowViewport() [Internal]
14549// - GetWindowAlwaysWantOwnViewport() [Internal]
14550// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14551// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14552// - TranslateWindowsInViewport() [Internal]
14553// - ScaleWindowsInViewport() [Internal]
14554// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14555// - UpdateViewportsNewFrame() [Internal]
14556// - UpdateViewportsEndFrame() [Internal]
14557// - AddUpdateViewport() [Internal]
14558// - WindowSelectViewport() [Internal]
14559// - WindowSyncOwnedViewport() [Internal]
14560// - UpdatePlatformWindows()
14561// - RenderPlatformWindowsDefault()
14562// - FindPlatformMonitorForPos() [Internal]
14563// - FindPlatformMonitorForRect() [Internal]
14564// - UpdateViewportPlatformMonitor() [Internal]
14565// - DestroyPlatformWindow() [Internal]
14566// - DestroyPlatformWindows()
14567//-----------------------------------------------------------------------------
14568
14569ImGuiViewport* ImGui::GetMainViewport()
14570{
14571 ImGuiContext& g = *GImGui;
14572 return g.Viewports[0];
14573}
14574
14575// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14576ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14577{
14578 ImGuiContext& g = *GImGui;
14579 for (ImGuiViewportP* viewport : g.Viewports)
14580 if (viewport->ID == id)
14581 return viewport;
14582 return NULL;
14583}
14584
14585ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14586{
14587 ImGuiContext& g = *GImGui;
14588 for (ImGuiViewportP* viewport : g.Viewports)
14589 if (viewport->PlatformHandle == platform_handle)
14590 return viewport;
14591 return NULL;
14592}
14593
14594void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14595{
14596 ImGuiContext& g = *GImGui;
14597 (void)current_window;
14598
14599 if (viewport)
14600 viewport->LastFrameActive = g.FrameCount;
14601 if (g.CurrentViewport == viewport)
14602 return;
14603 g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14604 g.CurrentViewport = viewport;
14605 //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14606
14607 // Notify platform layer of viewport changes
14608 // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14609 if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14610 g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14611}
14612
14613void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14614{
14615 // Abandon viewport
14616 if (window->ViewportOwned && window->Viewport->Window == window)
14617 window->Viewport->Size = ImVec2(0.0f, 0.0f);
14618
14619 window->Viewport = viewport;
14620 window->ViewportId = viewport->ID;
14621 window->ViewportOwned = (viewport->Window == window);
14622}
14623
14624static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14625{
14626 // 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.
14627 ImGuiContext& g = *GImGui;
14628 if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14629 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14630 if (!window->DockIsActive)
14631 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14632 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14633 return true;
14634 return false;
14635}
14636
14637static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14638{
14639 ImGuiContext& g = *GImGui;
14640 if (window->Viewport == viewport)
14641 return false;
14642 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14643 return false;
14644 if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14645 return false;
14646 if (!viewport->GetMainRect().Contains(r: window->Rect()))
14647 return false;
14648 if (GetWindowAlwaysWantOwnViewport(window))
14649 return false;
14650
14651 // 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..
14652 for (ImGuiWindow* window_behind : g.Windows)
14653 {
14654 if (window_behind == window)
14655 break;
14656 if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14657 if (window_behind->Viewport->GetMainRect().Overlaps(r: window->Rect()))
14658 return false;
14659 }
14660
14661 // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14662 ImGuiViewportP* old_viewport = window->Viewport;
14663 if (window->ViewportOwned)
14664 for (int n = 0; n < g.Windows.Size; n++)
14665 if (g.Windows[n]->Viewport == old_viewport)
14666 SetWindowViewport(window: g.Windows[n], viewport);
14667 SetWindowViewport(window, viewport);
14668 BringWindowToDisplayFront(window);
14669
14670 return true;
14671}
14672
14673// FIXME: handle 0 to N host viewports
14674static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14675{
14676 ImGuiContext& g = *GImGui;
14677 return UpdateTryMergeWindowIntoHostViewport(window, viewport: g.Viewports[0]);
14678}
14679
14680// Translate Dear ImGui windows when a Host Viewport has been moved
14681// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14682void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14683{
14684 ImGuiContext& g = *GImGui;
14685 IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14686
14687 // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14688 // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14689 // 2) If it's not going to fit into the new size, keep it at same absolute position.
14690 // One problem with this is that most Win32 applications doesn't update their render while dragging,
14691 // and so the window will appear to teleport when releasing the mouse.
14692 const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14693 ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14694 ImVec2 delta_pos = new_pos - old_pos;
14695 for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14696 if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(r: window->Rect())))
14697 TranslateWindow(window, delta: delta_pos);
14698}
14699
14700// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14701void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14702{
14703 ImGuiContext& g = *GImGui;
14704 if (viewport->Window)
14705 {
14706 ScaleWindow(window: viewport->Window, scale);
14707 }
14708 else
14709 {
14710 for (ImGuiWindow* window : g.Windows)
14711 if (window->Viewport == viewport)
14712 ScaleWindow(window, scale);
14713 }
14714}
14715
14716// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14717// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14718// B) It requires Platform_GetWindowFocus to be implemented by backend.
14719ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14720{
14721 ImGuiContext& g = *GImGui;
14722 ImGuiViewportP* best_candidate = NULL;
14723 for (ImGuiViewportP* viewport : g.Viewports)
14724 if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(p: mouse_platform_pos))
14725 if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14726 best_candidate = viewport;
14727 return best_candidate;
14728}
14729
14730// Update viewports and monitor infos
14731// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14732static void ImGui::UpdateViewportsNewFrame()
14733{
14734 ImGuiContext& g = *GImGui;
14735 IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14736
14737 // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14738 // Update Focused status
14739 const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14740 if (viewports_enabled)
14741 {
14742 ImGuiViewportP* focused_viewport = NULL;
14743 for (ImGuiViewportP* viewport : g.Viewports)
14744 {
14745 const bool platform_funcs_available = viewport->PlatformWindowCreated;
14746 if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14747 {
14748 bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14749 if (is_minimized)
14750 viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14751 else
14752 viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14753 }
14754
14755 // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14756 // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14757 if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14758 {
14759 bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14760 if (is_focused)
14761 viewport->Flags |= ImGuiViewportFlags_IsFocused;
14762 else
14763 viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14764 if (is_focused)
14765 focused_viewport = viewport;
14766 }
14767 }
14768
14769 // Focused viewport has changed?
14770 if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14771 {
14772 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14773 const ImGuiViewport* prev_focused_viewport = FindViewportByID(id: g.PlatformLastFocusedViewportId);
14774 const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14775
14776 // Store a tag so we can infer z-order easily from all our windows
14777 // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14778 // will keep the front most stamp instead of losing it back to their parent viewport.
14779 if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14780 focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14781 g.PlatformLastFocusedViewportId = focused_viewport->ID;
14782
14783 // Focus associated dear imgui window
14784 // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14785 // - if focus didn't happen because we destroyed another window (#6462)
14786 // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14787 const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14788 if (apply_imgui_focus_on_focused_viewport)
14789 {
14790 focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14791 ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14792 if (focused_viewport->Window != NULL)
14793 FocusWindow(window: focused_viewport->Window, flags: focus_request_flags);
14794 else if (focused_viewport->LastFocusedHadNavWindow)
14795 FocusTopMostWindowUnderOne(NULL, NULL, filter_viewport: focused_viewport, flags: focus_request_flags); // Focus top most in viewport
14796 else
14797 FocusWindow(NULL, flags: focus_request_flags); // No window had focus last time viewport was focused
14798 }
14799 }
14800 if (focused_viewport)
14801 focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14802 }
14803
14804 // Create/update main viewport with current platform position.
14805 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14806 ImGuiViewportP* main_viewport = g.Viewports[0];
14807 IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14808 IM_ASSERT(main_viewport->Window == NULL);
14809 ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14810 ImVec2 main_viewport_size = g.IO.DisplaySize;
14811 if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14812 {
14813 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)
14814 main_viewport_size = main_viewport->Size;
14815 }
14816 AddUpdateViewport(NULL, id: IMGUI_VIEWPORT_DEFAULT_ID, platform_pos: main_viewport_pos, size: main_viewport_size, flags: ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14817
14818 g.CurrentDpiScale = 0.0f;
14819 g.CurrentViewport = NULL;
14820 g.MouseViewport = NULL;
14821 for (int n = 0; n < g.Viewports.Size; n++)
14822 {
14823 ImGuiViewportP* viewport = g.Viewports[n];
14824 viewport->Idx = n;
14825
14826 // Erase unused viewports
14827 if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14828 {
14829 DestroyViewport(viewport);
14830 n--;
14831 continue;
14832 }
14833
14834 const bool platform_funcs_available = viewport->PlatformWindowCreated;
14835 if (viewports_enabled)
14836 {
14837 // Update Position and Size (from Platform Window to ImGui) if requested.
14838 // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14839 if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14840 {
14841 // Viewport->WorkPos and WorkSize will be updated below
14842 if (viewport->PlatformRequestMove)
14843 viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14844 if (viewport->PlatformRequestResize)
14845 viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14846 }
14847 }
14848
14849 // Update/copy monitor info
14850 UpdateViewportPlatformMonitor(viewport);
14851
14852 // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14853 viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14854 viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14855 viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14856 viewport->UpdateWorkRect();
14857
14858 // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14859 viewport->Alpha = 1.0f;
14860
14861 // Translate Dear ImGui windows when a Host Viewport has been moved
14862 // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14863 const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14864 if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14865 TranslateWindowsInViewport(viewport, old_pos: viewport->LastPos, new_pos: viewport->Pos);
14866
14867 // Update DPI scale
14868 float new_dpi_scale;
14869 if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14870 new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14871 else if (viewport->PlatformMonitor != -1)
14872 new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14873 else
14874 new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14875 if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14876 {
14877 float scale_factor = new_dpi_scale / viewport->DpiScale;
14878 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14879 ScaleWindowsInViewport(viewport, scale: scale_factor);
14880 //if (viewport == GetMainViewport())
14881 // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14882
14883 // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14884 // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14885 // (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.)
14886 //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14887 // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14888 }
14889 viewport->DpiScale = new_dpi_scale;
14890 }
14891
14892 // Update fallback monitor
14893 g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14894 if (g.PlatformIO.Monitors.Size == 0)
14895 {
14896 ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14897 monitor->MainPos = main_viewport->Pos;
14898 monitor->MainSize = main_viewport->Size;
14899 monitor->WorkPos = main_viewport->WorkPos;
14900 monitor->WorkSize = main_viewport->WorkSize;
14901 monitor->DpiScale = main_viewport->DpiScale;
14902 g.PlatformMonitorsFullWorkRect.Add(p: monitor->WorkPos);
14903 g.PlatformMonitorsFullWorkRect.Add(p: monitor->WorkPos + monitor->WorkSize);
14904 }
14905 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
14906 {
14907 g.PlatformMonitorsFullWorkRect.Add(p: monitor.WorkPos);
14908 g.PlatformMonitorsFullWorkRect.Add(p: monitor.WorkPos + monitor.WorkSize);
14909 }
14910
14911 if (!viewports_enabled)
14912 {
14913 g.MouseViewport = main_viewport;
14914 return;
14915 }
14916
14917 // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14918 // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14919 ImGuiViewportP* viewport_hovered = NULL;
14920 if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14921 {
14922 viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(id: g.IO.MouseHoveredViewport) : NULL;
14923 if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14924 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos: g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14925 }
14926 else
14927 {
14928 // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14929 // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14930 // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14931 // 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)
14932 viewport_hovered = FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos: g.IO.MousePos);
14933 }
14934 if (viewport_hovered != NULL)
14935 g.MouseLastHoveredViewport = viewport_hovered;
14936 else if (g.MouseLastHoveredViewport == NULL)
14937 g.MouseLastHoveredViewport = g.Viewports[0];
14938
14939 // Update mouse reference viewport
14940 // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14941 // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14942 if (g.MovingWindow && g.MovingWindow->Viewport)
14943 g.MouseViewport = g.MovingWindow->Viewport;
14944 else
14945 g.MouseViewport = g.MouseLastHoveredViewport;
14946
14947 // When dragging something, always refer to the last hovered viewport.
14948 // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14949 // - 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)
14950 // - 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.
14951 // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14952 const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14953 if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14954 viewport_hovered = g.MouseLastHoveredViewport;
14955 if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14956 if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14957 g.MouseViewport = viewport_hovered;
14958
14959 IM_ASSERT(g.MouseViewport != NULL);
14960}
14961
14962// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14963static void ImGui::UpdateViewportsEndFrame()
14964{
14965 ImGuiContext& g = *GImGui;
14966 g.PlatformIO.Viewports.resize(new_size: 0);
14967 for (int i = 0; i < g.Viewports.Size; i++)
14968 {
14969 ImGuiViewportP* viewport = g.Viewports[i];
14970 viewport->LastPos = viewport->Pos;
14971 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14972 if (i > 0) // Always include main viewport in the list
14973 continue;
14974 if (viewport->Window && !IsWindowActiveAndVisible(window: viewport->Window))
14975 continue;
14976 if (i > 0)
14977 IM_ASSERT(viewport->Window != NULL);
14978 g.PlatformIO.Viewports.push_back(v: viewport);
14979 }
14980 g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14981}
14982
14983// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14984ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14985{
14986 ImGuiContext& g = *GImGui;
14987 IM_ASSERT(id != 0);
14988
14989 flags |= ImGuiViewportFlags_IsPlatformWindow;
14990 if (window != NULL)
14991 {
14992 if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14993 flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14994 if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14995 flags |= ImGuiViewportFlags_NoInputs;
14996 if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14997 flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14998 }
14999
15000 ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15001 if (viewport)
15002 {
15003 // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15004 if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15005 viewport->Pos = pos;
15006 if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15007 viewport->Size = size;
15008 viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15009 }
15010 else
15011 {
15012 // New viewport
15013 viewport = IM_NEW(ImGuiViewportP)();
15014 viewport->ID = id;
15015 viewport->Idx = g.Viewports.Size;
15016 viewport->Pos = viewport->LastPos = pos;
15017 viewport->Size = size;
15018 viewport->Flags = flags;
15019 UpdateViewportPlatformMonitor(viewport);
15020 g.Viewports.push_back(v: viewport);
15021 g.ViewportCreatedCount++;
15022 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15023
15024 // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15025 // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15026 g.DrawListSharedData.ClipRectFullscreen.x = ImMin(lhs: g.DrawListSharedData.ClipRectFullscreen.x, rhs: viewport->Pos.x);
15027 g.DrawListSharedData.ClipRectFullscreen.y = ImMin(lhs: g.DrawListSharedData.ClipRectFullscreen.y, rhs: viewport->Pos.y);
15028 g.DrawListSharedData.ClipRectFullscreen.z = ImMax(lhs: g.DrawListSharedData.ClipRectFullscreen.z, rhs: viewport->Pos.x + viewport->Size.x);
15029 g.DrawListSharedData.ClipRectFullscreen.w = ImMax(lhs: g.DrawListSharedData.ClipRectFullscreen.w, rhs: viewport->Pos.y + viewport->Size.y);
15030
15031 // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15032 // This is so we can select an appropriate font size on the first frame of our window lifetime
15033 if (viewport->PlatformMonitor != -1)
15034 viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15035 }
15036
15037 viewport->Window = window;
15038 viewport->LastFrameActive = g.FrameCount;
15039 viewport->UpdateWorkRect();
15040 IM_ASSERT(window == NULL || viewport->ID == window->ID);
15041
15042 if (window != NULL)
15043 window->ViewportOwned = true;
15044
15045 return viewport;
15046}
15047
15048static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15049{
15050 // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15051 ImGuiContext& g = *GImGui;
15052 for (ImGuiWindow* window : g.Windows)
15053 {
15054 if (window->Viewport != viewport)
15055 continue;
15056 window->Viewport = NULL;
15057 window->ViewportOwned = false;
15058 }
15059 if (viewport == g.MouseLastHoveredViewport)
15060 g.MouseLastHoveredViewport = NULL;
15061
15062 // Destroy
15063 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15064 DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15065 IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15066 IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15067 g.Viewports.erase(it: g.Viewports.Data + viewport->Idx);
15068 IM_DELETE(p: viewport);
15069}
15070
15071// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15072static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15073{
15074 ImGuiContext& g = *GImGui;
15075 ImGuiWindowFlags flags = window->Flags;
15076 window->ViewportAllowPlatformMonitorExtend = -1;
15077
15078 // Restore main viewport if multi-viewport is not supported by the backend
15079 ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15080 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15081 {
15082 SetWindowViewport(window, viewport: main_viewport);
15083 return;
15084 }
15085 window->ViewportOwned = false;
15086
15087 // Appearing popups reset their viewport so they can inherit again
15088 if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15089 {
15090 window->Viewport = NULL;
15091 window->ViewportId = 0;
15092 }
15093
15094 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15095 {
15096 // By default inherit from parent window
15097 if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15098 window->Viewport = window->ParentWindow->Viewport;
15099
15100 // 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
15101 if (window->Viewport == NULL && window->ViewportId != 0)
15102 {
15103 window->Viewport = (ImGuiViewportP*)FindViewportByID(id: window->ViewportId);
15104 if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15105 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->ViewportPos, size: window->Size, flags: ImGuiViewportFlags_None);
15106 }
15107 }
15108
15109 bool lock_viewport = false;
15110 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15111 {
15112 // Code explicitly request a viewport
15113 window->Viewport = (ImGuiViewportP*)FindViewportByID(id: g.NextWindowData.ViewportId);
15114 window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15115 if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15116 {
15117 window->Viewport->Window = window;
15118 window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15119 }
15120 lock_viewport = true;
15121 }
15122 else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15123 {
15124 // Always inherit viewport from parent window
15125 if (window->DockNode && window->DockNode->HostWindow)
15126 IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15127 window->Viewport = window->ParentWindow->Viewport;
15128 }
15129 else if (window->DockNode && window->DockNode->HostWindow)
15130 {
15131 // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15132 window->Viewport = window->DockNode->HostWindow->Viewport;
15133 }
15134 else if (flags & ImGuiWindowFlags_Tooltip)
15135 {
15136 window->Viewport = g.MouseViewport;
15137 }
15138 else if (GetWindowAlwaysWantOwnViewport(window))
15139 {
15140 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_None);
15141 }
15142 else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15143 {
15144 if (window->Viewport != NULL && window->Viewport->Window == window)
15145 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_None);
15146 }
15147 else
15148 {
15149 // Merge into host viewport?
15150 // We cannot test window->ViewportOwned as it set lower in the function.
15151 // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15152 bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15153 if (try_to_merge_into_host_viewport)
15154 UpdateTryMergeWindowIntoHostViewports(window);
15155 }
15156
15157 // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15158 if (window->Viewport == NULL)
15159 if (!UpdateTryMergeWindowIntoHostViewport(window, viewport: main_viewport))
15160 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_None);
15161
15162 // Mark window as allowed to protrude outside of its viewport and into the current monitor
15163 if (!lock_viewport)
15164 {
15165 if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15166 {
15167 // We need to take account of the possibility that mouse may become invalid.
15168 // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15169 ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15170 bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15171 bool mouse_valid = IsMousePosValid(mouse_pos: &mouse_ref);
15172 if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15173 window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos(pos: (use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15174 else
15175 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15176 }
15177 else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15178 {
15179 // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15180 const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15181 if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15182 {
15183 // Steal/transfer ownership
15184 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15185 window->Viewport->Window = window;
15186 window->Viewport->ID = window->ID;
15187 window->Viewport->LastNameHash = 0;
15188 }
15189 else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15190 {
15191 // New viewport
15192 window->Viewport = AddUpdateViewport(window, id: window->ID, pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_NoFocusOnAppearing);
15193 }
15194 }
15195 else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15196 {
15197 // Regular (non-child, non-popup) windows by default are also allowed to protrude
15198 // Child windows are kept contained within their parent.
15199 window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15200 }
15201 }
15202
15203 // Update flags
15204 window->ViewportOwned = (window == window->Viewport->Window);
15205 window->ViewportId = window->Viewport->ID;
15206
15207 // If the OS window has a title bar, hide our imgui title bar
15208 //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15209 // window->Flags |= ImGuiWindowFlags_NoTitleBar;
15210}
15211
15212void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15213{
15214 ImGuiContext& g = *GImGui;
15215
15216 bool viewport_rect_changed = false;
15217
15218 // Synchronize window --> viewport in most situations
15219 // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15220 if (window->Viewport->PlatformRequestMove)
15221 {
15222 window->Pos = window->Viewport->Pos;
15223 MarkIniSettingsDirty(window);
15224 }
15225 else if (memcmp(s1: &window->Viewport->Pos, s2: &window->Pos, n: sizeof(window->Pos)) != 0)
15226 {
15227 viewport_rect_changed = true;
15228 window->Viewport->Pos = window->Pos;
15229 }
15230
15231 if (window->Viewport->PlatformRequestResize)
15232 {
15233 window->Size = window->SizeFull = window->Viewport->Size;
15234 MarkIniSettingsDirty(window);
15235 }
15236 else if (memcmp(s1: &window->Viewport->Size, s2: &window->Size, n: sizeof(window->Size)) != 0)
15237 {
15238 viewport_rect_changed = true;
15239 window->Viewport->Size = window->Size;
15240 }
15241 window->Viewport->UpdateWorkRect();
15242
15243 // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15244 // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15245 if (viewport_rect_changed)
15246 UpdateViewportPlatformMonitor(viewport: window->Viewport);
15247
15248 // Update common viewport flags
15249 const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15250 ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15251 ImGuiWindowFlags window_flags = window->Flags;
15252 const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15253 const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15254 if (window_flags & ImGuiWindowFlags_Tooltip)
15255 viewport_flags |= ImGuiViewportFlags_TopMost;
15256 if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15257 viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15258 if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15259 viewport_flags |= ImGuiViewportFlags_NoDecoration;
15260
15261 // Not correct to set modal as topmost because:
15262 // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15263 // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15264 //if (flags & ImGuiWindowFlags_Modal)
15265 // viewport_flags |= ImGuiViewportFlags_TopMost;
15266
15267 // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15268 // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15269 // 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,
15270 // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15271 if (is_short_lived_floating_window && !is_modal)
15272 viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15273
15274 // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15275 if (window->WindowClass.ViewportFlagsOverrideSet)
15276 viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15277 if (window->WindowClass.ViewportFlagsOverrideClear)
15278 viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15279
15280 // We can also tell the backend that clearing the platform window won't be necessary,
15281 // as our window background is filling the viewport and we have disabled BgAlpha.
15282 // FIXME: Work on support for per-viewport transparency (#2766)
15283 if (!(window_flags & ImGuiWindowFlags_NoBackground))
15284 viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15285
15286 window->Viewport->Flags = viewport_flags;
15287
15288 // Update parent viewport ID
15289 // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15290 if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15291 window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15292 else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15293 window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15294 else
15295 window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15296}
15297
15298// Called by user at the end of the main loop, after EndFrame()
15299// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15300void ImGui::UpdatePlatformWindows()
15301{
15302 ImGuiContext& g = *GImGui;
15303 IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15304 IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15305 g.FrameCountPlatformEnded = g.FrameCount;
15306 if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15307 return;
15308
15309 // Create/resize/destroy platform windows to match each active viewport.
15310 // Skip the main viewport (index 0), which is always fully handled by the application!
15311 for (int i = 1; i < g.Viewports.Size; i++)
15312 {
15313 ImGuiViewportP* viewport = g.Viewports[i];
15314
15315 // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15316 // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15317 bool destroy_platform_window = false;
15318 destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15319 destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(window: viewport->Window));
15320 if (destroy_platform_window)
15321 {
15322 DestroyPlatformWindow(viewport);
15323 continue;
15324 }
15325
15326 // New windows that appears directly in a new viewport won't always have a size on their first frame
15327 if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15328 continue;
15329
15330 // Create window
15331 const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15332 if (is_new_platform_window)
15333 {
15334 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15335 g.PlatformIO.Platform_CreateWindow(viewport);
15336 if (g.PlatformIO.Renderer_CreateWindow != NULL)
15337 g.PlatformIO.Renderer_CreateWindow(viewport);
15338 g.PlatformWindowsCreatedCount++;
15339 viewport->LastNameHash = 0;
15340 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?)
15341 viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15342 viewport->PlatformWindowCreated = true;
15343 }
15344
15345 // Apply Position and Size (from ImGui to Platform/Renderer backends)
15346 if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15347 g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15348 if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15349 g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15350 if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15351 g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15352 viewport->LastPlatformPos = viewport->Pos;
15353 viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15354
15355 // Update title bar (if it changed)
15356 if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(window: viewport->Window))
15357 {
15358 const char* title_begin = window_for_title->Name;
15359 char* title_end = (char*)(intptr_t)FindRenderedTextEnd(text: title_begin);
15360 const ImGuiID title_hash = ImHashStr(data_p: title_begin, data_size: title_end - title_begin);
15361 if (viewport->LastNameHash != title_hash)
15362 {
15363 char title_end_backup_c = *title_end;
15364 *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15365 g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15366 *title_end = title_end_backup_c;
15367 viewport->LastNameHash = title_hash;
15368 }
15369 }
15370
15371 // Update alpha (if it changed)
15372 if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15373 g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15374 viewport->LastAlpha = viewport->Alpha;
15375
15376 // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15377 if (g.PlatformIO.Platform_UpdateWindow)
15378 g.PlatformIO.Platform_UpdateWindow(viewport);
15379
15380 if (is_new_platform_window)
15381 {
15382 // 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)
15383 if (g.FrameCount < 3)
15384 viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15385
15386 // Show window
15387 g.PlatformIO.Platform_ShowWindow(viewport);
15388
15389 // Even without focus, we assume the window becomes front-most.
15390 // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15391 if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15392 viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15393 }
15394
15395 // Clear request flags
15396 viewport->ClearRequestFlags();
15397 }
15398}
15399
15400// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15401// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15402// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15403//
15404// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15405// for (int i = 1; i < platform_io.Viewports.Size; i++)
15406// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15407// MyRenderFunction(platform_io.Viewports[i], my_args);
15408// for (int i = 1; i < platform_io.Viewports.Size; i++)
15409// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15410// MySwapBufferFunction(platform_io.Viewports[i], my_args);
15411//
15412void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15413{
15414 // Skip the main viewport (index 0), which is always fully handled by the application!
15415 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15416 for (int i = 1; i < platform_io.Viewports.Size; i++)
15417 {
15418 ImGuiViewport* viewport = platform_io.Viewports[i];
15419 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15420 continue;
15421 if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15422 if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15423 }
15424 for (int i = 1; i < platform_io.Viewports.Size; i++)
15425 {
15426 ImGuiViewport* viewport = platform_io.Viewports[i];
15427 if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15428 continue;
15429 if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15430 if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15431 }
15432}
15433
15434static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15435{
15436 ImGuiContext& g = *GImGui;
15437 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15438 {
15439 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15440 if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(p: pos))
15441 return monitor_n;
15442 }
15443 return -1;
15444}
15445
15446// Search for the monitor with the largest intersection area with the given rectangle
15447// We generally try to avoid searching loops but the monitor count should be very small here
15448// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15449static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15450{
15451 ImGuiContext& g = *GImGui;
15452
15453 const int monitor_count = g.PlatformIO.Monitors.Size;
15454 if (monitor_count <= 1)
15455 return monitor_count - 1;
15456
15457 // 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.
15458 // This is necessary for tooltips which always resize down to zero at first.
15459 const float surface_threshold = ImMax(lhs: rect.GetWidth() * rect.GetHeight() * 0.5f, rhs: 1.0f);
15460 int best_monitor_n = -1;
15461 float best_monitor_surface = 0.001f;
15462
15463 for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15464 {
15465 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15466 const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15467 if (monitor_rect.Contains(r: rect))
15468 return monitor_n;
15469 ImRect overlapping_rect = rect;
15470 overlapping_rect.ClipWithFull(r: monitor_rect);
15471 float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15472 if (overlapping_surface < best_monitor_surface)
15473 continue;
15474 best_monitor_surface = overlapping_surface;
15475 best_monitor_n = monitor_n;
15476 }
15477 return best_monitor_n;
15478}
15479
15480// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15481static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15482{
15483 viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(rect: viewport->GetMainRect());
15484}
15485
15486// Return value is always != NULL, but don't hold on it across frames.
15487const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15488{
15489 ImGuiContext& g = *GImGui;
15490 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15491 int monitor_idx = viewport->PlatformMonitor;
15492 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15493 return &g.PlatformIO.Monitors[monitor_idx];
15494 return &g.FallbackMonitor;
15495}
15496
15497void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15498{
15499 ImGuiContext& g = *GImGui;
15500 if (viewport->PlatformWindowCreated)
15501 {
15502 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15503 if (g.PlatformIO.Renderer_DestroyWindow)
15504 g.PlatformIO.Renderer_DestroyWindow(viewport);
15505 if (g.PlatformIO.Platform_DestroyWindow)
15506 g.PlatformIO.Platform_DestroyWindow(viewport);
15507 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15508
15509 // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15510 // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15511 if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15512 viewport->PlatformWindowCreated = false;
15513 }
15514 else
15515 {
15516 IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15517 }
15518 viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15519 viewport->ClearRequestFlags();
15520}
15521
15522void ImGui::DestroyPlatformWindows()
15523{
15524 // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15525 // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15526 // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15527 // code to operator a consistent manner.
15528 // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15529 // crashing if it doesn't have data stored.
15530 ImGuiContext& g = *GImGui;
15531 for (ImGuiViewportP* viewport : g.Viewports)
15532 DestroyPlatformWindow(viewport);
15533}
15534
15535
15536//-----------------------------------------------------------------------------
15537// [SECTION] DOCKING
15538//-----------------------------------------------------------------------------
15539// Docking: Internal Types
15540// Docking: Forward Declarations
15541// Docking: ImGuiDockContext
15542// Docking: ImGuiDockContext Docking/Undocking functions
15543// Docking: ImGuiDockNode
15544// Docking: ImGuiDockNode Tree manipulation functions
15545// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15546// Docking: Builder Functions
15547// Docking: Begin/End Support Functions (called from Begin/End)
15548// Docking: Settings
15549//-----------------------------------------------------------------------------
15550
15551//-----------------------------------------------------------------------------
15552// Typical Docking call flow: (root level is generally public API):
15553//-----------------------------------------------------------------------------
15554// - NewFrame() new dear imgui frame
15555// | DockContextNewFrameUpdateUndocking() - process queued undocking requests
15556// | - DockContextProcessUndockWindow() - process one window undocking request
15557// | - DockContextProcessUndockNode() - process one whole node undocking request
15558// | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes
15559// | - update g.HoveredDockNode - [debug] update node hovered by mouse
15560// | - DockContextProcessDock() - process one docking request
15561// | - DockNodeUpdate()
15562// | - DockNodeUpdateForRootNode()
15563// | - DockNodeUpdateFlagsAndCollapse()
15564// | - DockNodeFindInfo()
15565// | - destroy unused node or tab bar
15566// | - create dock node host window
15567// | - Begin() etc.
15568// | - DockNodeStartMouseMovingWindow()
15569// | - DockNodeTreeUpdatePosSize()
15570// | - DockNodeTreeUpdateSplitter()
15571// | - draw node background
15572// | - DockNodeUpdateTabBar() - create/update tab bar for a docking node
15573// | - DockNodeAddTabBar()
15574// | - DockNodeWindowMenuUpdate()
15575// | - DockNodeCalcTabBarLayout()
15576// | - BeginTabBarEx()
15577// | - TabItemEx() calls
15578// | - EndTabBar()
15579// | - BeginDockableDragDropTarget()
15580// | - DockNodeUpdate() - recurse into child nodes...
15581//-----------------------------------------------------------------------------
15582// - DockSpace() user submit a dockspace into a window
15583// | Begin(Child) - create a child window
15584// | DockNodeUpdate() - call main dock node update function
15585// | End(Child)
15586// | ItemSize()
15587//-----------------------------------------------------------------------------
15588// - Begin()
15589// | BeginDocked()
15590// | BeginDockableDragDropSource()
15591// | BeginDockableDragDropTarget()
15592// | - DockNodePreviewDockRender()
15593//-----------------------------------------------------------------------------
15594// - EndFrame()
15595// | DockContextEndFrame()
15596//-----------------------------------------------------------------------------
15597
15598//-----------------------------------------------------------------------------
15599// Docking: Internal Types
15600//-----------------------------------------------------------------------------
15601// - ImGuiDockRequestType
15602// - ImGuiDockRequest
15603// - ImGuiDockPreviewData
15604// - ImGuiDockNodeSettings
15605// - ImGuiDockContext
15606//-----------------------------------------------------------------------------
15607
15608enum ImGuiDockRequestType
15609{
15610 ImGuiDockRequestType_None = 0,
15611 ImGuiDockRequestType_Dock,
15612 ImGuiDockRequestType_Undock,
15613 ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
15614};
15615
15616struct ImGuiDockRequest
15617{
15618 ImGuiDockRequestType Type;
15619 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)
15620 ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
15621 ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15622 ImGuiDir DockSplitDir;
15623 float DockSplitRatio;
15624 bool DockSplitOuter;
15625 ImGuiWindow* UndockTargetWindow;
15626 ImGuiDockNode* UndockTargetNode;
15627
15628 ImGuiDockRequest()
15629 {
15630 Type = ImGuiDockRequestType_None;
15631 DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15632 DockTargetNode = UndockTargetNode = NULL;
15633 DockSplitDir = ImGuiDir_None;
15634 DockSplitRatio = 0.5f;
15635 DockSplitOuter = false;
15636 }
15637};
15638
15639struct ImGuiDockPreviewData
15640{
15641 ImGuiDockNode FutureNode;
15642 bool IsDropAllowed;
15643 bool IsCenterAvailable;
15644 bool IsSidesAvailable; // Hold your breath, grammar freaks..
15645 bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15646 ImGuiDockNode* SplitNode;
15647 ImGuiDir SplitDir;
15648 float SplitRatio;
15649 ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15650
15651 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); }
15652};
15653
15654// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15655struct ImGuiDockNodeSettings
15656{
15657 ImGuiID ID;
15658 ImGuiID ParentNodeId;
15659 ImGuiID ParentWindowId;
15660 ImGuiID SelectedTabId;
15661 signed char SplitAxis;
15662 char Depth;
15663 ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15664 ImVec2ih Pos;
15665 ImVec2ih Size;
15666 ImVec2ih SizeRef;
15667 ImGuiDockNodeSettings() { memset(s: this, c: 0, n: sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15668};
15669
15670//-----------------------------------------------------------------------------
15671// Docking: Forward Declarations
15672//-----------------------------------------------------------------------------
15673
15674namespace ImGui
15675{
15676 // ImGuiDockContext
15677 static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15678 static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15679 static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15680 static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15681 static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15682 static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15683 static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15684 static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
15685
15686 // ImGuiDockNode
15687 static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15688 static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15689 static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15690 static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15691 static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15692 static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15693 static void DockNodeHideHostWindow(ImGuiDockNode* node);
15694 static void DockNodeUpdate(ImGuiDockNode* node);
15695 static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
15696 static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15697 static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15698 static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15699 static void DockNodeAddTabBar(ImGuiDockNode* node);
15700 static void DockNodeRemoveTabBar(ImGuiDockNode* node);
15701 static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15702 static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15703 static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15704 static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15705 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);
15706 static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15707 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);
15708 static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15709 static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15710 static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, fmt: "##DockNode_%02X", node->ID); return buf; }
15711 static int DockNodeGetTabOrder(ImGuiWindow* window);
15712
15713 // ImGuiDockNode tree manipulations
15714 static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15715 static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15716 static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15717 static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15718 static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15719 static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15720
15721 // Settings
15722 static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15723 static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15724 static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15725 static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15726 static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15727 static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15728 static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15729 static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15730}
15731
15732//-----------------------------------------------------------------------------
15733// Docking: ImGuiDockContext
15734//-----------------------------------------------------------------------------
15735// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15736// 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.
15737// At boot time only, we run a simple GC to remove nodes that have no references.
15738// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15739// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15740// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15741//-----------------------------------------------------------------------------
15742// - DockContextInitialize()
15743// - DockContextShutdown()
15744// - DockContextClearNodes()
15745// - DockContextRebuildNodes()
15746// - DockContextNewFrameUpdateUndocking()
15747// - DockContextNewFrameUpdateDocking()
15748// - DockContextEndFrame()
15749// - DockContextFindNodeByID()
15750// - DockContextBindNodeToWindow()
15751// - DockContextGenNodeID()
15752// - DockContextAddNode()
15753// - DockContextRemoveNode()
15754// - ImGuiDockContextPruneNodeData
15755// - DockContextPruneUnusedSettingsNodes()
15756// - DockContextBuildNodesFromSettings()
15757// - DockContextBuildAddWindowsToNodes()
15758//-----------------------------------------------------------------------------
15759
15760void ImGui::DockContextInitialize(ImGuiContext* ctx)
15761{
15762 ImGuiContext& g = *ctx;
15763
15764 // Add .ini handle for persistent docking data
15765 ImGuiSettingsHandler ini_handler;
15766 ini_handler.TypeName = "Docking";
15767 ini_handler.TypeHash = ImHashStr(data_p: "Docking");
15768 ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15769 ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15770 ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15771 ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15772 ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15773 ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15774 g.SettingsHandlers.push_back(v: ini_handler);
15775
15776 g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15777}
15778
15779void ImGui::DockContextShutdown(ImGuiContext* ctx)
15780{
15781 ImGuiDockContext* dc = &ctx->DockContext;
15782 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15783 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15784 IM_DELETE(p: node);
15785}
15786
15787void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15788{
15789 IM_UNUSED(ctx);
15790 IM_ASSERT(ctx == GImGui);
15791 DockBuilderRemoveNodeDockedWindows(node_id: root_id, clear_settings_refs);
15792 DockBuilderRemoveNodeChildNodes(node_id: root_id);
15793}
15794
15795// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15796// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15797void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15798{
15799 ImGuiContext& g = *ctx;
15800 ImGuiDockContext* dc = &ctx->DockContext;
15801 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15802 SaveIniSettingsToMemory();
15803 ImGuiID root_id = 0; // Rebuild all
15804 DockContextClearNodes(ctx, root_id, clear_settings_refs: false);
15805 DockContextBuildNodesFromSettings(ctx, node_settings_array: dc->NodesSettings.Data, node_settings_count: dc->NodesSettings.Size);
15806 DockContextBuildAddWindowsToNodes(ctx, root_id);
15807}
15808
15809// Docking context update function, called by NewFrame()
15810void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15811{
15812 ImGuiContext& g = *ctx;
15813 ImGuiDockContext* dc = &ctx->DockContext;
15814 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15815 {
15816 if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15817 DockContextClearNodes(ctx, root_id: 0, clear_settings_refs: true);
15818 return;
15819 }
15820
15821 // Setting NoSplit at runtime merges all nodes
15822 if (g.IO.ConfigDockingNoSplit)
15823 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15824 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15825 if (node->IsRootNode() && node->IsSplitNode())
15826 {
15827 DockBuilderRemoveNodeChildNodes(node_id: node->ID);
15828 //dc->WantFullRebuild = true;
15829 }
15830
15831 // Process full rebuild
15832#if 0
15833 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15834 dc->WantFullRebuild = true;
15835#endif
15836 if (dc->WantFullRebuild)
15837 {
15838 DockContextRebuildNodes(ctx);
15839 dc->WantFullRebuild = false;
15840 }
15841
15842 // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15843 for (ImGuiDockRequest& req : dc->Requests)
15844 {
15845 if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15846 DockContextProcessUndockWindow(ctx, window: req.UndockTargetWindow);
15847 else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15848 DockContextProcessUndockNode(ctx, node: req.UndockTargetNode);
15849 }
15850}
15851
15852// Docking context update function, called by NewFrame()
15853void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15854{
15855 ImGuiContext& g = *ctx;
15856 ImGuiDockContext* dc = &ctx->DockContext;
15857 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15858 return;
15859
15860 // [DEBUG] Store hovered dock node.
15861 // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15862 // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15863 g.DebugHoveredDockNode = NULL;
15864 if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15865 {
15866 if (hovered_window->DockNodeAsHost)
15867 g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(node: hovered_window->DockNodeAsHost, pos: g.IO.MousePos);
15868 else if (hovered_window->RootWindow->DockNode)
15869 g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15870 }
15871
15872 // Process Docking requests
15873 for (ImGuiDockRequest& req : dc->Requests)
15874 if (req.Type == ImGuiDockRequestType_Dock)
15875 DockContextProcessDock(ctx, req: &req);
15876 dc->Requests.resize(new_size: 0);
15877
15878 // Create windows for each automatic docking nodes
15879 // 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)
15880 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15881 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15882 if (node->IsFloatingNode())
15883 DockNodeUpdate(node);
15884}
15885
15886void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15887{
15888 // Draw backgrounds of node missing their window
15889 ImGuiContext& g = *ctx;
15890 ImGuiDockContext* dc = &g.DockContext;
15891 for (int n = 0; n < dc->Nodes.Data.Size; n++)
15892 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15893 if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15894 {
15895 ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15896 ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(r_in: bg_rect, r_outer: node->HostWindow->Rect(), threshold: g.Style.DockingSeparatorSize);
15897 node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15898 node->HostWindow->DrawList->AddRectFilled(p_min: bg_rect.Min, p_max: bg_rect.Max, col: node->LastBgColor, rounding: node->HostWindow->WindowRounding, flags: bg_rounding_flags);
15899 }
15900}
15901
15902ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15903{
15904 return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(key: id);
15905}
15906
15907ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15908{
15909 // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15910 // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15911 // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15912 ImGuiID id = 0x0001;
15913 while (DockContextFindNodeByID(ctx, id) != NULL)
15914 id++;
15915 return id;
15916}
15917
15918static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15919{
15920 // 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.
15921 ImGuiContext& g = *ctx;
15922 if (id == 0)
15923 id = DockContextGenNodeID(ctx);
15924 else
15925 IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15926
15927 // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15928 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15929 ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15930 ctx->DockContext.Nodes.SetVoidPtr(key: node->ID, val: node);
15931 return node;
15932}
15933
15934static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15935{
15936 ImGuiContext& g = *ctx;
15937 ImGuiDockContext* dc = &ctx->DockContext;
15938
15939 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15940 IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15941 IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15942 IM_ASSERT(node->Windows.Size == 0);
15943
15944 if (node->HostWindow)
15945 node->HostWindow->DockNodeAsHost = NULL;
15946
15947 ImGuiDockNode* parent_node = node->ParentNode;
15948 const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15949 if (merge)
15950 {
15951 IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15952 ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15953 DockNodeTreeMerge(ctx: &g, parent_node, merge_lead_child: sibling_node);
15954 }
15955 else
15956 {
15957 for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15958 if (parent_node->ChildNodes[n] == node)
15959 node->ParentNode->ChildNodes[n] = NULL;
15960 dc->Nodes.SetVoidPtr(key: node->ID, NULL);
15961 IM_DELETE(p: node);
15962 }
15963}
15964
15965static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15966{
15967 const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15968 const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15969 return ImGui::DockNodeGetDepth(node: b) - ImGui::DockNodeGetDepth(node: a);
15970}
15971
15972// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15973struct ImGuiDockContextPruneNodeData
15974{
15975 int CountWindows, CountChildWindows, CountChildNodes;
15976 ImGuiID RootId;
15977 ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15978};
15979
15980// Garbage collect unused nodes (run once at init time)
15981static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15982{
15983 ImGuiContext& g = *ctx;
15984 ImGuiDockContext* dc = &ctx->DockContext;
15985 IM_ASSERT(g.Windows.Size == 0);
15986
15987 ImPool<ImGuiDockContextPruneNodeData> pool;
15988 pool.Reserve(capacity: dc->NodesSettings.Size);
15989
15990 // Count child nodes and compute RootID
15991 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15992 {
15993 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15994 ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(key: settings->ParentNodeId) : 0;
15995 pool.GetOrAddByKey(key: settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15996 if (settings->ParentNodeId)
15997 pool.GetOrAddByKey(key: settings->ParentNodeId)->CountChildNodes++;
15998 }
15999
16000 // Count reference to dock ids from dockspaces
16001 // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16002 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16003 {
16004 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16005 if (settings->ParentWindowId != 0)
16006 if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(id: settings->ParentWindowId))
16007 if (window_settings->DockId)
16008 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(key: window_settings->DockId))
16009 data->CountChildNodes++;
16010 }
16011
16012 // Count reference to dock ids from window settings
16013 // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16014 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
16015 if (ImGuiID dock_id = settings->DockId)
16016 if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(key: dock_id))
16017 {
16018 data->CountWindows++;
16019 if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(key: data->RootId))
16020 data_root->CountChildWindows++;
16021 }
16022
16023 // Prune
16024 for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16025 {
16026 ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16027 ImGuiDockContextPruneNodeData* data = pool.GetByKey(key: settings->ID);
16028 if (data->CountWindows > 1)
16029 continue;
16030 ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(key: data->RootId);
16031
16032 bool remove = false;
16033 remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
16034 remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16035 remove |= (data_root->CountChildWindows == 0);
16036 if (remove)
16037 {
16038 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16039 DockSettingsRemoveNodeReferences(node_ids: &settings->ID, node_ids_count: 1);
16040 settings->ID = 0;
16041 }
16042 }
16043}
16044
16045static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16046{
16047 // Build nodes
16048 for (int node_n = 0; node_n < node_settings_count; node_n++)
16049 {
16050 ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16051 if (settings->ID == 0)
16052 continue;
16053 ImGuiDockNode* node = DockContextAddNode(ctx, id: settings->ID);
16054 node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, id: settings->ParentNodeId) : NULL;
16055 node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16056 node->Size = ImVec2(settings->Size.x, settings->Size.y);
16057 node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16058 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16059 if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16060 node->ParentNode->ChildNodes[0] = node;
16061 else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16062 node->ParentNode->ChildNodes[1] = node;
16063 node->SelectedTabId = settings->SelectedTabId;
16064 node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16065 node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16066
16067 // Bind host window immediately if it already exist (in case of a rebuild)
16068 // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16069 char host_window_title[20];
16070 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16071 node->HostWindow = FindWindowByName(name: DockNodeGetHostWindowTitle(node: root_node, buf: host_window_title, IM_ARRAYSIZE(host_window_title)));
16072 }
16073}
16074
16075void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16076{
16077 // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16078 ImGuiContext& g = *ctx;
16079 for (ImGuiWindow* window : g.Windows)
16080 {
16081 if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16082 continue;
16083 if (window->DockNode != NULL)
16084 continue;
16085
16086 ImGuiDockNode* node = DockContextFindNodeByID(ctx, id: window->DockId);
16087 IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
16088 if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16089 DockNodeAddWindow(node, window, add_to_tab_bar: true);
16090 }
16091}
16092
16093//-----------------------------------------------------------------------------
16094// Docking: ImGuiDockContext Docking/Undocking functions
16095//-----------------------------------------------------------------------------
16096// - DockContextQueueDock()
16097// - DockContextQueueUndockWindow()
16098// - DockContextQueueUndockNode()
16099// - DockContextQueueNotifyRemovedNode()
16100// - DockContextProcessDock()
16101// - DockContextProcessUndockWindow()
16102// - DockContextProcessUndockNode()
16103// - DockContextCalcDropPosForDocking()
16104//-----------------------------------------------------------------------------
16105
16106void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16107{
16108 IM_ASSERT(target != payload);
16109 ImGuiDockRequest req;
16110 req.Type = ImGuiDockRequestType_Dock;
16111 req.DockTargetWindow = target;
16112 req.DockTargetNode = target_node;
16113 req.DockPayload = payload;
16114 req.DockSplitDir = split_dir;
16115 req.DockSplitRatio = split_ratio;
16116 req.DockSplitOuter = split_outer;
16117 ctx->DockContext.Requests.push_back(v: req);
16118}
16119
16120void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16121{
16122 ImGuiDockRequest req;
16123 req.Type = ImGuiDockRequestType_Undock;
16124 req.UndockTargetWindow = window;
16125 ctx->DockContext.Requests.push_back(v: req);
16126}
16127
16128void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16129{
16130 ImGuiDockRequest req;
16131 req.Type = ImGuiDockRequestType_Undock;
16132 req.UndockTargetNode = node;
16133 ctx->DockContext.Requests.push_back(v: req);
16134}
16135
16136void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16137{
16138 ImGuiDockContext* dc = &ctx->DockContext;
16139 for (ImGuiDockRequest& req : dc->Requests)
16140 if (req.DockTargetNode == node)
16141 req.Type = ImGuiDockRequestType_None;
16142}
16143
16144void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16145{
16146 IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16147 IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16148
16149 ImGuiContext& g = *ctx;
16150 IM_UNUSED(g);
16151
16152 ImGuiWindow* payload_window = req->DockPayload; // Optional
16153 ImGuiWindow* target_window = req->DockTargetWindow;
16154 ImGuiDockNode* node = req->DockTargetNode;
16155 if (payload_window)
16156 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);
16157 else
16158 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16159
16160 // Decide which Tab will be selected at the end of the operation
16161 ImGuiID next_selected_id = 0;
16162 ImGuiDockNode* payload_node = NULL;
16163 if (payload_window)
16164 {
16165 payload_node = payload_window->DockNodeAsHost;
16166 payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16167 if (payload_node && payload_node->IsLeafNode())
16168 next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16169 if (payload_node == NULL)
16170 next_selected_id = payload_window->TabId;
16171 }
16172
16173 // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16174 // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16175 if (node)
16176 IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16177 if (node && target_window && node == target_window->DockNodeAsHost)
16178 IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16179
16180 // Create new node and add existing window to it
16181 if (node == NULL)
16182 {
16183 node = DockContextAddNode(ctx, id: 0);
16184 node->Pos = target_window->Pos;
16185 node->Size = target_window->Size;
16186 if (target_window->DockNodeAsHost == NULL)
16187 {
16188 DockNodeAddWindow(node, window: target_window, add_to_tab_bar: true);
16189 node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16190 target_window->DockIsActive = true;
16191 }
16192 }
16193
16194 ImGuiDir split_dir = req->DockSplitDir;
16195 if (split_dir != ImGuiDir_None)
16196 {
16197 // Split into two, one side will be our payload node unless we are dropping a loose window
16198 const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16199 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
16200 const float split_ratio = req->DockSplitRatio;
16201 DockNodeTreeSplit(ctx, parent_node: node, split_axis, split_first_child: split_inheritor_child_idx, split_ratio, new_node: payload_node); // payload_node may be NULL here!
16202 ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16203 new_node->HostWindow = node->HostWindow;
16204 node = new_node;
16205 }
16206 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16207
16208 if (node != payload_node)
16209 {
16210 // 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!)
16211 if (node->Windows.Size > 0 && node->TabBar == NULL)
16212 {
16213 DockNodeAddTabBar(node);
16214 for (int n = 0; n < node->Windows.Size; n++)
16215 TabBarAddTab(tab_bar: node->TabBar, tab_flags: ImGuiTabItemFlags_None, window: node->Windows[n]);
16216 }
16217
16218 if (payload_node != NULL)
16219 {
16220 // Transfer full payload node (with 1+ child windows or child nodes)
16221 if (payload_node->IsSplitNode())
16222 {
16223 if (node->Windows.Size > 0)
16224 {
16225 // 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.
16226 // In this situation, we move the windows of the target node into the currently visible node of the payload.
16227 // This allows us to preserve some of the underlying dock tree settings nicely.
16228 IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16229 ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16230 if (visible_node->TabBar)
16231 IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16232 DockNodeMoveWindows(dst_node: node, src_node: visible_node);
16233 DockNodeMoveWindows(dst_node: visible_node, src_node: node);
16234 DockSettingsRenameNodeReferences(old_node_id: node->ID, new_node_id: visible_node->ID);
16235 }
16236 if (node->IsCentralNode())
16237 {
16238 // Central node property needs to be moved to a leaf node, pick the last focused one.
16239 // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16240 ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, id: payload_node->LastFocusedNodeId);
16241 IM_ASSERT(last_focused_node != NULL);
16242 ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(node: last_focused_node);
16243 IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16244 last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16245 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16246 last_focused_root_node->CentralNode = last_focused_node;
16247 }
16248
16249 IM_ASSERT(node->Windows.Size == 0);
16250 DockNodeMoveChildNodes(dst_node: node, src_node: payload_node);
16251 }
16252 else
16253 {
16254 const ImGuiID payload_dock_id = payload_node->ID;
16255 DockNodeMoveWindows(dst_node: node, src_node: payload_node);
16256 DockSettingsRenameNodeReferences(old_node_id: payload_dock_id, new_node_id: node->ID);
16257 }
16258 DockContextRemoveNode(ctx, node: payload_node, merge_sibling_into_parent_node: true);
16259 }
16260 else if (payload_window)
16261 {
16262 // Transfer single window
16263 const ImGuiID payload_dock_id = payload_window->DockId;
16264 node->VisibleWindow = payload_window;
16265 DockNodeAddWindow(node, window: payload_window, add_to_tab_bar: true);
16266 if (payload_dock_id != 0)
16267 DockSettingsRenameNodeReferences(old_node_id: payload_dock_id, new_node_id: node->ID);
16268 }
16269 }
16270 else
16271 {
16272 // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16273 node->WantHiddenTabBarUpdate = true;
16274 }
16275
16276 // Update selection immediately
16277 if (ImGuiTabBar* tab_bar = node->TabBar)
16278 tab_bar->NextSelectedTabId = next_selected_id;
16279 MarkIniSettingsDirty();
16280}
16281
16282// Problem:
16283// Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16284// than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16285// with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16286// due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16287// Solution:
16288// When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16289// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16290static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16291{
16292 if (ref_viewport == NULL)
16293 return size;
16294
16295 ImGuiContext& g = *GImGui;
16296 ImVec2 max_size = ImTrunc(v: ref_viewport->WorkSize * 0.90f);
16297 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16298 {
16299 const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(viewport_p: ref_viewport);
16300 max_size = ImTrunc(v: monitor->WorkSize * 0.90f);
16301 }
16302 return ImMin(lhs: size, rhs: max_size);
16303}
16304
16305void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16306{
16307 ImGuiContext& g = *ctx;
16308 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16309 if (window->DockNode)
16310 DockNodeRemoveWindow(node: window->DockNode, window, save_dock_id: clear_persistent_docking_ref ? 0 : window->DockId);
16311 else
16312 window->DockId = 0;
16313 window->Collapsed = false;
16314 window->DockIsActive = false;
16315 window->DockNodeIsVisible = window->DockTabIsVisible = false;
16316 window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(size: window->SizeFull, ref_viewport: window->Viewport);
16317
16318 MarkIniSettingsDirty();
16319}
16320
16321void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16322{
16323 ImGuiContext& g = *ctx;
16324 IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16325 IM_ASSERT(node->IsLeafNode());
16326 IM_ASSERT(node->Windows.Size >= 1);
16327
16328 if (node->IsRootNode() || node->IsCentralNode())
16329 {
16330 // 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.
16331 ImGuiDockNode* new_node = DockContextAddNode(ctx, id: 0);
16332 new_node->Pos = node->Pos;
16333 new_node->Size = node->Size;
16334 new_node->SizeRef = node->SizeRef;
16335 DockNodeMoveWindows(dst_node: new_node, src_node: node);
16336 DockSettingsRenameNodeReferences(old_node_id: node->ID, new_node_id: new_node->ID);
16337 node = new_node;
16338 }
16339 else
16340 {
16341 // Otherwise extract our node and merge our sibling back into the parent node.
16342 IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16343 int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16344 node->ParentNode->ChildNodes[index_in_parent] = NULL;
16345 DockNodeTreeMerge(ctx, parent_node: node->ParentNode, merge_lead_child: node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16346 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
16347 node->ParentNode = NULL;
16348 }
16349 for (ImGuiWindow* window : node->Windows)
16350 {
16351 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16352 if (window->ParentWindow)
16353 window->ParentWindow->DC.ChildWindows.find_erase(v: window);
16354 UpdateWindowParentAndRootLinks(window, flags: window->Flags, NULL);
16355 }
16356 node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16357 node->Size = FixLargeWindowsWhenUndocking(size: node->Size, ref_viewport: node->Windows[0]->Viewport);
16358 node->WantMouseMove = true;
16359 MarkIniSettingsDirty();
16360}
16361
16362// This is mostly used for automation.
16363bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16364{
16365 if (target != NULL && target_node == NULL)
16366 target_node = target->DockNode;
16367
16368 // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16369 // (which would be functionally identical) we only show the outer one. Reflect this here.
16370 if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16371 split_outer = true;
16372 ImGuiDockPreviewData split_data;
16373 DockNodePreviewDockSetup(host_window: target, host_node: target_node, payload_window, payload_node, preview_data: &split_data, is_explicit_target: false, is_outer_docking: split_outer);
16374 if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16375 return false;
16376 *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16377 return true;
16378}
16379
16380//-----------------------------------------------------------------------------
16381// Docking: ImGuiDockNode
16382//-----------------------------------------------------------------------------
16383// - DockNodeGetTabOrder()
16384// - DockNodeAddWindow()
16385// - DockNodeRemoveWindow()
16386// - DockNodeMoveChildNodes()
16387// - DockNodeMoveWindows()
16388// - DockNodeApplyPosSizeToWindows()
16389// - DockNodeHideHostWindow()
16390// - ImGuiDockNodeFindInfoResults
16391// - DockNodeFindInfo()
16392// - DockNodeFindWindowByID()
16393// - DockNodeUpdateFlagsAndCollapse()
16394// - DockNodeUpdateHasCentralNodeFlag()
16395// - DockNodeUpdateVisibleFlag()
16396// - DockNodeStartMouseMovingWindow()
16397// - DockNodeUpdate()
16398// - DockNodeUpdateWindowMenu()
16399// - DockNodeBeginAmendTabBar()
16400// - DockNodeEndAmendTabBar()
16401// - DockNodeUpdateTabBar()
16402// - DockNodeAddTabBar()
16403// - DockNodeRemoveTabBar()
16404// - DockNodeIsDropAllowedOne()
16405// - DockNodeIsDropAllowed()
16406// - DockNodeCalcTabBarLayout()
16407// - DockNodeCalcSplitRects()
16408// - DockNodeCalcDropRectsAndTestMousePos()
16409// - DockNodePreviewDockSetup()
16410// - DockNodePreviewDockRender()
16411//-----------------------------------------------------------------------------
16412
16413ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16414{
16415 ID = id;
16416 SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16417 ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16418 TabBar = NULL;
16419 SplitAxis = ImGuiAxis_None;
16420
16421 State = ImGuiDockNodeState_Unknown;
16422 LastBgColor = IM_COL32_WHITE;
16423 HostWindow = VisibleWindow = NULL;
16424 CentralNode = OnlyNodeWithWindows = NULL;
16425 CountNodeWithWindows = 0;
16426 LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16427 LastFocusedNodeId = 0;
16428 SelectedTabId = 0;
16429 WantCloseTabId = 0;
16430 RefViewportId = 0;
16431 AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16432 AuthorityForViewport = ImGuiDataAuthority_Auto;
16433 IsVisible = true;
16434 IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16435 IsBgDrawnThisFrame = false;
16436 WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16437}
16438
16439ImGuiDockNode::~ImGuiDockNode()
16440{
16441 IM_DELETE(p: TabBar);
16442 TabBar = NULL;
16443 ChildNodes[0] = ChildNodes[1] = NULL;
16444}
16445
16446int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16447{
16448 ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16449 if (tab_bar == NULL)
16450 return -1;
16451 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id: window->TabId);
16452 return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16453}
16454
16455static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16456{
16457 window->Hidden = true;
16458 window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16459}
16460
16461static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16462{
16463 ImGuiContext& g = *GImGui; (void)g;
16464 if (window->DockNode)
16465 {
16466 // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16467 IM_ASSERT(window->DockNode->ID != node->ID);
16468 DockNodeRemoveWindow(node: window->DockNode, window, save_dock_id: 0);
16469 }
16470 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16471 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16472
16473 // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16474 // 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).
16475 // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16476 if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16477 DockNodeHideWindowDuringHostWindowCreation(window: node->Windows[0]);
16478
16479 node->Windows.push_back(v: window);
16480 node->WantHiddenTabBarUpdate = true;
16481 window->DockNode = node;
16482 window->DockId = node->ID;
16483 window->DockIsActive = (node->Windows.Size > 1);
16484 window->DockTabWantClose = false;
16485
16486 // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16487 // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16488 if (node->HostWindow == NULL && node->IsFloatingNode())
16489 {
16490 if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16491 node->AuthorityForPos = ImGuiDataAuthority_Window;
16492 if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16493 node->AuthorityForSize = ImGuiDataAuthority_Window;
16494 if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16495 node->AuthorityForViewport = ImGuiDataAuthority_Window;
16496 }
16497
16498 // Add to tab bar if requested
16499 if (add_to_tab_bar)
16500 {
16501 if (node->TabBar == NULL)
16502 {
16503 DockNodeAddTabBar(node);
16504 node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16505
16506 // Add existing windows
16507 for (int n = 0; n < node->Windows.Size - 1; n++)
16508 TabBarAddTab(tab_bar: node->TabBar, tab_flags: ImGuiTabItemFlags_None, window: node->Windows[n]);
16509 }
16510 TabBarAddTab(tab_bar: node->TabBar, tab_flags: ImGuiTabItemFlags_Unsorted, window);
16511 }
16512
16513 DockNodeUpdateVisibleFlag(node);
16514
16515 // 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.
16516 if (node->HostWindow)
16517 UpdateWindowParentAndRootLinks(window, flags: window->Flags | ImGuiWindowFlags_ChildWindow, parent_window: node->HostWindow);
16518}
16519
16520static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16521{
16522 ImGuiContext& g = *GImGui;
16523 IM_ASSERT(window->DockNode == node);
16524 //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16525 //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
16526 IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16527 IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16528
16529 window->DockNode = NULL;
16530 window->DockIsActive = window->DockTabWantClose = false;
16531 window->DockId = save_dock_id;
16532 window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16533 if (window->ParentWindow)
16534 window->ParentWindow->DC.ChildWindows.find_erase(v: window);
16535 UpdateWindowParentAndRootLinks(window, flags: window->Flags, NULL); // Update immediately
16536
16537 if (node->HostWindow && node->HostWindow->ViewportOwned)
16538 {
16539 // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16540 // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16541 window->Viewport = NULL;
16542 window->ViewportId = 0;
16543 window->ViewportOwned = false;
16544 window->Hidden = true;
16545 }
16546
16547 // Remove window
16548 bool erased = false;
16549 for (int n = 0; n < node->Windows.Size; n++)
16550 if (node->Windows[n] == window)
16551 {
16552 node->Windows.erase(it: node->Windows.Data + n);
16553 erased = true;
16554 break;
16555 }
16556 if (!erased)
16557 IM_ASSERT(erased);
16558 if (node->VisibleWindow == window)
16559 node->VisibleWindow = NULL;
16560
16561 // Remove tab and possibly tab bar
16562 node->WantHiddenTabBarUpdate = true;
16563 if (node->TabBar)
16564 {
16565 TabBarRemoveTab(tab_bar: node->TabBar, tab_id: window->TabId);
16566 const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16567 if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16568 DockNodeRemoveTabBar(node);
16569 }
16570
16571 if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16572 {
16573 // Automatic dock node delete themselves if they are not holding at least one tab
16574 DockContextRemoveNode(ctx: &g, node, merge_sibling_into_parent_node: true);
16575 return;
16576 }
16577
16578 if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16579 {
16580 ImGuiWindow* remaining_window = node->Windows[0];
16581 // Note: we used to transport viewport ownership here.
16582 remaining_window->Collapsed = node->HostWindow->Collapsed;
16583 }
16584
16585 // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16586 DockNodeUpdateVisibleFlag(node);
16587}
16588
16589static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16590{
16591 IM_ASSERT(dst_node->Windows.Size == 0);
16592 dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16593 dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16594 if (dst_node->ChildNodes[0])
16595 dst_node->ChildNodes[0]->ParentNode = dst_node;
16596 if (dst_node->ChildNodes[1])
16597 dst_node->ChildNodes[1]->ParentNode = dst_node;
16598 dst_node->SplitAxis = src_node->SplitAxis;
16599 dst_node->SizeRef = src_node->SizeRef;
16600 src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16601}
16602
16603static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16604{
16605 // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16606 IM_ASSERT(src_node && dst_node && dst_node != src_node);
16607 ImGuiTabBar* src_tab_bar = src_node->TabBar;
16608 if (src_tab_bar != NULL)
16609 IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16610
16611 // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16612 bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16613 if (move_tab_bar)
16614 {
16615 dst_node->TabBar = src_node->TabBar;
16616 src_node->TabBar = NULL;
16617 }
16618
16619 // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16620 for (ImGuiWindow* window : src_node->Windows)
16621 {
16622 window->DockNode = NULL;
16623 window->DockIsActive = false;
16624 DockNodeAddWindow(node: dst_node, window, add_to_tab_bar: !move_tab_bar);
16625 }
16626 src_node->Windows.clear();
16627
16628 if (!move_tab_bar && src_node->TabBar)
16629 {
16630 if (dst_node->TabBar)
16631 dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16632 DockNodeRemoveTabBar(node: src_node);
16633 }
16634}
16635
16636static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16637{
16638 for (ImGuiWindow* window : node->Windows)
16639 {
16640 SetWindowPos(window, pos: node->Pos, cond: ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16641 SetWindowSize(window, size: node->Size, cond: ImGuiCond_Always);
16642 }
16643}
16644
16645static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16646{
16647 if (node->HostWindow)
16648 {
16649 if (node->HostWindow->DockNodeAsHost == node)
16650 node->HostWindow->DockNodeAsHost = NULL;
16651 node->HostWindow = NULL;
16652 }
16653
16654 if (node->Windows.Size == 1)
16655 {
16656 node->VisibleWindow = node->Windows[0];
16657 node->Windows[0]->DockIsActive = false;
16658 }
16659
16660 if (node->TabBar)
16661 DockNodeRemoveTabBar(node);
16662}
16663
16664// Search function called once by root node in DockNodeUpdate()
16665struct ImGuiDockNodeTreeInfo
16666{
16667 ImGuiDockNode* CentralNode;
16668 ImGuiDockNode* FirstNodeWithWindows;
16669 int CountNodesWithWindows;
16670 //ImGuiWindowClass WindowClassForMerges;
16671
16672 ImGuiDockNodeTreeInfo() { memset(s: this, c: 0, n: sizeof(*this)); }
16673};
16674
16675static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16676{
16677 if (node->Windows.Size > 0)
16678 {
16679 if (info->FirstNodeWithWindows == NULL)
16680 info->FirstNodeWithWindows = node;
16681 info->CountNodesWithWindows++;
16682 }
16683 if (node->IsCentralNode())
16684 {
16685 IM_ASSERT(info->CentralNode == NULL); // Should be only one
16686 IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16687 info->CentralNode = node;
16688 }
16689 if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16690 return;
16691 if (node->ChildNodes[0])
16692 DockNodeFindInfo(node: node->ChildNodes[0], info);
16693 if (node->ChildNodes[1])
16694 DockNodeFindInfo(node: node->ChildNodes[1], info);
16695}
16696
16697static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16698{
16699 IM_ASSERT(id != 0);
16700 for (ImGuiWindow* window : node->Windows)
16701 if (window->ID == id)
16702 return window;
16703 return NULL;
16704}
16705
16706// - Remove inactive windows/nodes.
16707// - Update visibility flag.
16708static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16709{
16710 ImGuiContext& g = *GImGui;
16711 IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16712
16713 // Inherit most flags
16714 if (node->ParentNode)
16715 node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16716
16717 // Recurse into children
16718 // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16719 // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16720 // 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)
16721 node->HasCentralNodeChild = false;
16722 if (node->ChildNodes[0])
16723 DockNodeUpdateFlagsAndCollapse(node: node->ChildNodes[0]);
16724 if (node->ChildNodes[1])
16725 DockNodeUpdateFlagsAndCollapse(node: node->ChildNodes[1]);
16726
16727 // Remove inactive windows, collapse nodes
16728 // Merge node flags overrides stored in windows
16729 node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16730 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16731 {
16732 ImGuiWindow* window = node->Windows[window_n];
16733 IM_ASSERT(window->DockNode == node);
16734
16735 bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16736 bool remove = false;
16737 remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16738 remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
16739 remove |= (window->DockTabWantClose);
16740 if (remove)
16741 {
16742 window->DockTabWantClose = false;
16743 if (node->Windows.Size == 1 && !node->IsCentralNode())
16744 {
16745 DockNodeHideHostWindow(node);
16746 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16747 DockNodeRemoveWindow(node, window, save_dock_id: node->ID); // Will delete the node so it'll be invalid on return
16748 return;
16749 }
16750 DockNodeRemoveWindow(node, window, save_dock_id: node->ID);
16751 window_n--;
16752 continue;
16753 }
16754
16755 // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16756 //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16757 node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16758 }
16759 node->UpdateMergedFlags();
16760
16761 // Auto-hide tab bar option
16762 ImGuiDockNodeFlags node_flags = node->MergedFlags;
16763 if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16764 node->WantHiddenTabBarToggle = true;
16765 node->WantHiddenTabBarUpdate = false;
16766
16767 // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16768 if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16769 node->WantHiddenTabBarToggle = false;
16770
16771 // Apply toggles at a single point of the frame (here!)
16772 if (node->Windows.Size > 1)
16773 node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16774 else if (node->WantHiddenTabBarToggle)
16775 node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16776 node->WantHiddenTabBarToggle = false;
16777
16778 DockNodeUpdateVisibleFlag(node);
16779}
16780
16781// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16782static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16783{
16784 node->HasCentralNodeChild = false;
16785 if (node->ChildNodes[0])
16786 DockNodeUpdateHasCentralNodeChild(node: node->ChildNodes[0]);
16787 if (node->ChildNodes[1])
16788 DockNodeUpdateHasCentralNodeChild(node: node->ChildNodes[1]);
16789 if (node->IsRootNode())
16790 {
16791 ImGuiDockNode* mark_node = node->CentralNode;
16792 while (mark_node)
16793 {
16794 mark_node->HasCentralNodeChild = true;
16795 mark_node = mark_node->ParentNode;
16796 }
16797 }
16798}
16799
16800static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16801{
16802 // Update visibility flag
16803 bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16804 is_visible |= (node->Windows.Size > 0);
16805 is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16806 is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16807 node->IsVisible = is_visible;
16808}
16809
16810static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16811{
16812 ImGuiContext& g = *GImGui;
16813 IM_ASSERT(node->WantMouseMove == true);
16814 StartMouseMovingWindow(window);
16815 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16816 g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16817 node->WantMouseMove = false;
16818}
16819
16820// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16821static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16822{
16823 DockNodeUpdateFlagsAndCollapse(node);
16824
16825 // - Setup central node pointers
16826 // - 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!)
16827 // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16828 ImGuiDockNodeTreeInfo info;
16829 DockNodeFindInfo(node, info: &info);
16830 node->CentralNode = info.CentralNode;
16831 node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16832 node->CountNodeWithWindows = info.CountNodesWithWindows;
16833 if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16834 node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16835
16836 // Copy the window class from of our first window so it can be used for proper dock filtering.
16837 // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16838 // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16839 if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16840 {
16841 node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16842 for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16843 if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16844 {
16845 node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16846 break;
16847 }
16848 }
16849
16850 ImGuiDockNode* mark_node = node->CentralNode;
16851 while (mark_node)
16852 {
16853 mark_node->HasCentralNodeChild = true;
16854 mark_node = mark_node->ParentNode;
16855 }
16856}
16857
16858static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16859{
16860 // Remove ourselves from any previous different host window
16861 // This can happen if a user mistakenly does (see #4295 for details):
16862 // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace
16863 // - N+1: NewFrame() // will create floating host window for that node
16864 // - N+1: DockSpace(id) // requalify node as dockspace, moving host window
16865 if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16866 node->HostWindow->DockNodeAsHost = NULL;
16867
16868 host_window->DockNodeAsHost = node;
16869 node->HostWindow = host_window;
16870}
16871
16872static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16873{
16874 ImGuiContext& g = *GImGui;
16875 IM_ASSERT(node->LastFrameActive != g.FrameCount);
16876 node->LastFrameAlive = g.FrameCount;
16877 node->IsBgDrawnThisFrame = false;
16878
16879 node->CentralNode = node->OnlyNodeWithWindows = NULL;
16880 if (node->IsRootNode())
16881 DockNodeUpdateForRootNode(node);
16882
16883 // Remove tab bar if not needed
16884 if (node->TabBar && node->IsNoTabBar())
16885 DockNodeRemoveTabBar(node);
16886
16887 // 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)
16888 bool want_to_hide_host_window = false;
16889 if (node->IsFloatingNode())
16890 {
16891 if (node->Windows.Size <= 1 && node->IsLeafNode())
16892 if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16893 want_to_hide_host_window = true;
16894 if (node->CountNodeWithWindows == 0)
16895 want_to_hide_host_window = true;
16896 }
16897 if (want_to_hide_host_window)
16898 {
16899 if (node->Windows.Size == 1)
16900 {
16901 // Floating window pos/size is authoritative
16902 ImGuiWindow* single_window = node->Windows[0];
16903 node->Pos = single_window->Pos;
16904 node->Size = single_window->SizeFull;
16905 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16906
16907 // Transfer focus immediately so when we revert to a regular window it is immediately selected
16908 if (node->HostWindow && g.NavWindow == node->HostWindow)
16909 FocusWindow(window: single_window);
16910 if (node->HostWindow)
16911 {
16912 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);
16913 single_window->Viewport = node->HostWindow->Viewport;
16914 single_window->ViewportId = node->HostWindow->ViewportId;
16915 if (node->HostWindow->ViewportOwned)
16916 {
16917 single_window->Viewport->ID = single_window->ID;
16918 single_window->Viewport->Window = single_window;
16919 single_window->ViewportOwned = true;
16920 }
16921 }
16922 node->RefViewportId = single_window->ViewportId;
16923 }
16924
16925 DockNodeHideHostWindow(node);
16926 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16927 node->WantCloseAll = false;
16928 node->WantCloseTabId = 0;
16929 node->HasCloseButton = node->HasWindowMenuButton = false;
16930 node->LastFrameActive = g.FrameCount;
16931
16932 if (node->WantMouseMove && node->Windows.Size == 1)
16933 DockNodeStartMouseMovingWindow(node, window: node->Windows[0]);
16934 return;
16935 }
16936
16937 // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16938 // while the expected visible window is resizing itself.
16939 // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16940 // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16941 // N+0: Begin(): window created (with no known size), node is created
16942 // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16943 // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16944 // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16945 // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16946 // In reality it isn't very important as user quickly ends up with size data in .ini file.
16947 if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16948 {
16949 IM_ASSERT(node->Windows.Size > 0);
16950 ImGuiWindow* ref_window = NULL;
16951 if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16952 ref_window = DockNodeFindWindowByID(node, id: node->SelectedTabId);
16953 if (ref_window == NULL)
16954 ref_window = node->Windows[0];
16955 if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16956 {
16957 node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16958 return;
16959 }
16960 }
16961
16962 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16963
16964 // Decide if the node will have a close button and a window menu button
16965 node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16966 node->HasCloseButton = false;
16967 for (ImGuiWindow* window : node->Windows)
16968 {
16969 // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16970 node->HasCloseButton |= window->HasCloseButton;
16971 window->DockIsActive = (node->Windows.Size > 1);
16972 }
16973 if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16974 node->HasCloseButton = false;
16975
16976 // Bind or create host window
16977 ImGuiWindow* host_window = NULL;
16978 bool beginned_into_host_window = false;
16979 if (node->IsDockSpace())
16980 {
16981 // [Explicit root dockspace node]
16982 IM_ASSERT(node->HostWindow);
16983 host_window = node->HostWindow;
16984 }
16985 else
16986 {
16987 // [Automatic root or child nodes]
16988 if (node->IsRootNode() && node->IsVisible)
16989 {
16990 ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16991
16992 // Sync Pos
16993 if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16994 SetNextWindowPos(pos: ref_window->Pos);
16995 else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16996 SetNextWindowPos(pos: node->Pos);
16997
16998 // Sync Size
16999 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17000 SetNextWindowSize(size: ref_window->SizeFull);
17001 else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17002 SetNextWindowSize(size: node->Size);
17003
17004 // Sync Collapsed
17005 if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17006 SetNextWindowCollapsed(collapsed: ref_window->Collapsed);
17007
17008 // Sync Viewport
17009 if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17010 SetNextWindowViewport(ref_window->ViewportId);
17011 else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17012 SetNextWindowViewport(node->RefViewportId);
17013
17014 SetNextWindowClass(&node->WindowClass);
17015
17016 // Begin into the host window
17017 char window_label[20];
17018 DockNodeGetHostWindowTitle(node, buf: window_label, IM_ARRAYSIZE(window_label));
17019 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17020 window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17021 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17022 window_flags |= ImGuiWindowFlags_NoTitleBar;
17023
17024 SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17025 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: ImVec2(0, 0));
17026 Begin(name: window_label, NULL, flags: window_flags);
17027 PopStyleVar();
17028 beginned_into_host_window = true;
17029
17030 host_window = g.CurrentWindow;
17031 DockNodeSetupHostWindow(node, host_window);
17032 host_window->DC.CursorPos = host_window->Pos;
17033 node->Pos = host_window->Pos;
17034 node->Size = host_window->Size;
17035
17036 // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17037 // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17038 // 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.
17039 // 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
17040 // 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
17041 // after the dock host window, losing their top-most status.
17042 if (node->HostWindow->Appearing)
17043 BringWindowToDisplayFront(window: node->HostWindow);
17044
17045 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17046 }
17047 else if (node->ParentNode)
17048 {
17049 node->HostWindow = host_window = node->ParentNode->HostWindow;
17050 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17051 }
17052 if (node->WantMouseMove && node->HostWindow)
17053 DockNodeStartMouseMovingWindow(node, window: node->HostWindow);
17054 }
17055 node->RefViewportId = 0; // Clear when we have a host window
17056
17057 // Update focused node (the one whose title bar is highlight) within a node tree
17058 if (node->IsSplitNode())
17059 IM_ASSERT(node->TabBar == NULL);
17060 if (node->IsRootNode())
17061 if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17062 while (p_window != NULL && p_window->DockNode != NULL)
17063 {
17064 ImGuiDockNode* p_node = DockNodeGetRootNode(node: p_window->DockNode);
17065 if (p_node == node)
17066 {
17067 node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17068 break;
17069 }
17070 p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17071 }
17072
17073 // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17074 ImGuiDockNode* central_node = node->CentralNode;
17075 const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17076 bool central_node_hole_register_hit_test_hole = central_node_hole;
17077 if (central_node_hole)
17078 if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17079 if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, payload_window: *(ImGuiWindow**)payload->Data))
17080 central_node_hole_register_hit_test_hole = false;
17081 if (central_node_hole_register_hit_test_hole)
17082 {
17083 // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17084 // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17085 // covering passthru node we'd have a gap on the edge not covered by the hole)
17086 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
17087 ImGuiDockNode* root_node = DockNodeGetRootNode(node: central_node);
17088 ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17089 ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17090 if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17091 if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17092 if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17093 if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17094 //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17095 if (central_node_hole && !hole_rect.IsInverted())
17096 {
17097 SetWindowHitTestHole(window: host_window, pos: hole_rect.Min, size: hole_rect.Max - hole_rect.Min);
17098 if (host_window->ParentWindow)
17099 SetWindowHitTestHole(window: host_window->ParentWindow, pos: hole_rect.Min, size: hole_rect.Max - hole_rect.Min);
17100 }
17101 }
17102
17103 // Update position/size, process and draw resizing splitters
17104 if (node->IsRootNode() && host_window)
17105 {
17106 DockNodeTreeUpdatePosSize(node, pos: host_window->Pos, size: host_window->Size);
17107 PushStyleColor(idx: ImGuiCol_Separator, col: g.Style.Colors[ImGuiCol_Border]);
17108 PushStyleColor(idx: ImGuiCol_SeparatorActive, col: g.Style.Colors[ImGuiCol_ResizeGripActive]);
17109 PushStyleColor(idx: ImGuiCol_SeparatorHovered, col: g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17110 DockNodeTreeUpdateSplitter(node);
17111 PopStyleColor(count: 3);
17112 }
17113
17114 // Draw empty node background (currently can only be the Central Node)
17115 if (host_window && node->IsEmpty() && node->IsVisible)
17116 {
17117 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17118 node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(idx: ImGuiCol_DockingEmptyBg);
17119 if (node->LastBgColor != 0)
17120 host_window->DrawList->AddRectFilled(p_min: node->Pos, p_max: node->Pos + node->Size, col: node->LastBgColor);
17121 node->IsBgDrawnThisFrame = true;
17122 }
17123
17124 // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17125 // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17126 // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17127 const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17128 if (render_dockspace_bg && node->IsVisible)
17129 {
17130 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17131 if (central_node_hole)
17132 RenderRectFilledWithHole(draw_list: host_window->DrawList, outer: node->Rect(), inner: central_node->Rect(), col: GetColorU32(idx: ImGuiCol_WindowBg), rounding: 0.0f);
17133 else
17134 host_window->DrawList->AddRectFilled(p_min: node->Pos, p_max: node->Pos + node->Size, col: GetColorU32(idx: ImGuiCol_WindowBg), rounding: 0.0f);
17135 }
17136
17137 // Draw and populate Tab Bar
17138 if (host_window)
17139 host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17140 if (host_window && node->Windows.Size > 0)
17141 {
17142 DockNodeUpdateTabBar(node, host_window);
17143 }
17144 else
17145 {
17146 node->WantCloseAll = false;
17147 node->WantCloseTabId = 0;
17148 node->IsFocused = false;
17149 }
17150 if (node->TabBar && node->TabBar->SelectedTabId)
17151 node->SelectedTabId = node->TabBar->SelectedTabId;
17152 else if (node->Windows.Size > 0)
17153 node->SelectedTabId = node->Windows[0]->TabId;
17154
17155 // Draw payload drop target
17156 if (host_window && node->IsVisible)
17157 if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17158 BeginDockableDragDropTarget(window: host_window);
17159
17160 // We update this after DockNodeUpdateTabBar()
17161 node->LastFrameActive = g.FrameCount;
17162
17163 // Recurse into children
17164 // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17165 if (host_window)
17166 {
17167 if (node->ChildNodes[0])
17168 DockNodeUpdate(node: node->ChildNodes[0]);
17169 if (node->ChildNodes[1])
17170 DockNodeUpdate(node: node->ChildNodes[1]);
17171
17172 // Render outer borders last (after the tab bar)
17173 if (node->IsRootNode())
17174 RenderWindowOuterBorders(window: host_window);
17175 }
17176
17177 // End host window
17178 if (beginned_into_host_window) //-V1020
17179 End();
17180}
17181
17182// 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.
17183static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17184{
17185 ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17186 ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17187 if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17188 return d;
17189 return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17190}
17191
17192// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17193// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17194// Custom overrides may want to decorate, group, sort entries.
17195// Please note those are internal structures: if you copy this expect occasional breakage.
17196// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17197void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17198{
17199 IM_UNUSED(ctx);
17200 if (tab_bar->Tabs.Size == 1)
17201 {
17202 // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17203 if (MenuItem(label: LocalizeGetMsg(key: ImGuiLocKey_DockingHideTabBar), NULL, selected: node->IsHiddenTabBar()))
17204 node->WantHiddenTabBarToggle = true;
17205 }
17206 else
17207 {
17208 // Display a selectable list of windows in this docking node
17209 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17210 {
17211 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17212 if (tab->Flags & ImGuiTabItemFlags_Button)
17213 continue;
17214 if (Selectable(label: TabBarGetTabName(tab_bar, tab), selected: tab->ID == tab_bar->SelectedTabId))
17215 TabBarQueueFocus(tab_bar, tab);
17216 SameLine();
17217 Text(fmt: " ");
17218 }
17219 }
17220}
17221
17222static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17223{
17224 // Try to position the menu so it is more likely to stays within the same viewport
17225 ImGuiContext& g = *GImGui;
17226 if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17227 SetNextWindowPos(pos: ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), cond: ImGuiCond_Always, pivot: ImVec2(0.0f, 0.0f));
17228 else
17229 SetNextWindowPos(pos: ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), cond: ImGuiCond_Always, pivot: ImVec2(1.0f, 0.0f));
17230 if (BeginPopup(str_id: "#WindowMenu"))
17231 {
17232 node->IsFocused = true;
17233 g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17234 EndPopup();
17235 }
17236}
17237
17238// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17239bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17240{
17241 if (node->TabBar == NULL || node->HostWindow == NULL)
17242 return false;
17243 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17244 return false;
17245 if (node->TabBar->ID == 0)
17246 return false;
17247 Begin(name: node->HostWindow->Name);
17248 PushOverrideID(id: node->ID);
17249 bool ret = BeginTabBarEx(tab_bar: node->TabBar, bb: node->TabBar->BarRect, flags: node->TabBar->Flags);
17250 IM_UNUSED(ret);
17251 IM_ASSERT(ret);
17252 return true;
17253}
17254
17255void ImGui::DockNodeEndAmendTabBar()
17256{
17257 EndTabBar();
17258 PopID();
17259 End();
17260}
17261
17262static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17263{
17264 // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17265 ImGuiContext& g = *GImGui;
17266 if (g.NavWindowingTarget)
17267 return (g.NavWindowingTarget->DockNode == node);
17268
17269 // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17270 if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17271 {
17272 // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17273 ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17274 while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17275 parent_window = parent_window->ParentWindow->RootWindow;
17276 ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17277 for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17278 if ((parent_node = ImGui::DockNodeGetRootNode(node: parent_node)) == root_node)
17279 return true;
17280 }
17281 return false;
17282}
17283
17284// Submit the tab bar corresponding to a dock node and various housekeeping details.
17285static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17286{
17287 ImGuiContext& g = *GImGui;
17288 ImGuiStyle& style = g.Style;
17289
17290 const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17291 const bool closed_all = node->WantCloseAll && node_was_active;
17292 const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17293 node->WantCloseAll = false;
17294 node->WantCloseTabId = 0;
17295
17296 // Decide if we should use a focused title bar color
17297 bool is_focused = false;
17298 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17299 if (IsDockNodeTitleBarHighlighted(node, root_node))
17300 is_focused = true;
17301
17302 // Hidden tab bar will show a triangle on the upper-left (in Begin)
17303 if (node->IsHiddenTabBar() || node->IsNoTabBar())
17304 {
17305 node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17306 node->IsFocused = is_focused;
17307 if (is_focused)
17308 node->LastFrameFocused = g.FrameCount;
17309 if (node->VisibleWindow)
17310 {
17311 // Notify root of visible window (used to display title in OS task bar)
17312 if (is_focused || root_node->VisibleWindow == NULL)
17313 root_node->VisibleWindow = node->VisibleWindow;
17314 if (node->TabBar)
17315 node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17316 }
17317 return;
17318 }
17319
17320 // 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
17321 bool backup_skip_item = host_window->SkipItems;
17322 if (!node->IsDockSpace())
17323 {
17324 host_window->SkipItems = false;
17325 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17326 }
17327
17328 // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17329 // 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,
17330 // as docked windows themselves will override the stack with their own root ID.
17331 PushOverrideID(id: node->ID);
17332 ImGuiTabBar* tab_bar = node->TabBar;
17333 bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17334 if (tab_bar == NULL)
17335 {
17336 DockNodeAddTabBar(node);
17337 tab_bar = node->TabBar;
17338 }
17339
17340 ImGuiID focus_tab_id = 0;
17341 node->IsFocused = is_focused;
17342
17343 const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17344 const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17345
17346 // In a dock node, the Collapse Button turns into the Window Menu button.
17347 // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17348 if (has_window_menu_button && IsPopupOpen(str_id: "#WindowMenu"))
17349 {
17350 ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17351 DockNodeWindowMenuUpdate(node, tab_bar);
17352 if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17353 focus_tab_id = tab_bar->NextSelectedTabId;
17354 is_focused |= node->IsFocused;
17355 }
17356
17357 // Layout
17358 ImRect title_bar_rect, tab_bar_rect;
17359 ImVec2 window_menu_button_pos;
17360 ImVec2 close_button_pos;
17361 DockNodeCalcTabBarLayout(node, out_title_rect: &title_bar_rect, out_tab_bar_rect: &tab_bar_rect, out_window_menu_button_pos: &window_menu_button_pos, out_close_button_pos: &close_button_pos);
17362
17363 // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17364 const int tabs_count_old = tab_bar->Tabs.Size;
17365 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17366 {
17367 ImGuiWindow* window = node->Windows[window_n];
17368 if (TabBarFindTabByID(tab_bar, tab_id: window->TabId) == NULL)
17369 TabBarAddTab(tab_bar, tab_flags: ImGuiTabItemFlags_Unsorted, window);
17370 }
17371
17372 // Title bar
17373 if (is_focused)
17374 node->LastFrameFocused = g.FrameCount;
17375 ImU32 title_bar_col = GetColorU32(idx: host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17376 ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(r_in: title_bar_rect, r_outer: host_window->Rect(), threshold: g.Style.DockingSeparatorSize);
17377 host_window->DrawList->AddRectFilled(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, col: title_bar_col, rounding: host_window->WindowRounding, flags: rounding_flags);
17378
17379 // Docking/Collapse button
17380 if (has_window_menu_button)
17381 {
17382 if (CollapseButton(id: host_window->GetID(str: "#COLLAPSE"), pos: window_menu_button_pos, dock_node: node)) // == DockNodeGetWindowMenuButtonId(node)
17383 OpenPopup(str_id: "#WindowMenu");
17384 if (IsItemActive())
17385 focus_tab_id = tab_bar->SelectedTabId;
17386 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17387 SetTooltip("%s", LocalizeGetMsg(key: ImGuiLocKey_DockingDragToUndockOrMoveNode));
17388 }
17389
17390 // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17391 int tabs_unsorted_start = tab_bar->Tabs.Size;
17392 for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17393 {
17394 // 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?
17395 tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17396 tabs_unsorted_start = tab_n;
17397 }
17398 if (tab_bar->Tabs.Size > tabs_unsorted_start)
17399 {
17400 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)" : "");
17401 for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17402 {
17403 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17404 IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17405 }
17406 IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17407 if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17408 ImQsort(base: tab_bar->Tabs.Data + tabs_unsorted_start, count: tab_bar->Tabs.Size - tabs_unsorted_start, size_of_element: sizeof(ImGuiTabItem), compare_func: TabItemComparerByDockOrder);
17409 }
17410
17411 // Apply NavWindow focus back to the tab bar
17412 if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17413 tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17414
17415 // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17416 if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, tab_id: node->SelectedTabId) != NULL)
17417 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17418 else if (tab_bar->Tabs.Size > tabs_count_old)
17419 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17420
17421 // Begin tab bar
17422 ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17423 tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17424 if (!host_window->Collapsed && is_focused)
17425 tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17426 tab_bar->ID = GetID(str_id: "#TabBar");
17427 tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17428 tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17429 BeginTabBarEx(tab_bar, bb: tab_bar_rect, flags: tab_bar_flags);
17430 //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17431
17432 // Backup style colors
17433 ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17434 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17435 backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17436
17437 // Submit actual tabs
17438 node->VisibleWindow = NULL;
17439 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17440 {
17441 ImGuiWindow* window = node->Windows[window_n];
17442 if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17443 continue;
17444 if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17445 {
17446 ImGuiTabItemFlags tab_item_flags = 0;
17447 tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17448 if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17449 tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17450 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17451 tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17452
17453 // Apply stored style overrides for the window
17454 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17455 g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(in: window->DockStyle.Colors[color_n]);
17456
17457 // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17458 bool tab_open = true;
17459 TabItemEx(tab_bar, label: window->Name, p_open: window->HasCloseButton ? &tab_open : NULL, flags: tab_item_flags, docked_window: window);
17460 if (!tab_open)
17461 node->WantCloseTabId = window->TabId;
17462 if (tab_bar->VisibleTabId == window->TabId)
17463 node->VisibleWindow = window;
17464
17465 // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17466 window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17467 window->DockTabItemRect = g.LastItemData.Rect;
17468
17469 // Update navigation ID on menu layer
17470 if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17471 host_window->NavLastIds[1] = window->TabId;
17472 }
17473 }
17474
17475 // Restore style colors
17476 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17477 g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17478
17479 // Notify root of visible window (used to display title in OS task bar)
17480 if (node->VisibleWindow)
17481 if (is_focused || root_node->VisibleWindow == NULL)
17482 root_node->VisibleWindow = node->VisibleWindow;
17483
17484 // Close button (after VisibleWindow was updated)
17485 // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17486 const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17487 const bool close_button_is_visible = node->HasCloseButton;
17488 //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)
17489 if (close_button_is_visible)
17490 {
17491 if (!close_button_is_enabled)
17492 {
17493 PushItemFlag(option: ImGuiItemFlags_Disabled, enabled: true);
17494 PushStyleColor(idx: ImGuiCol_Text, col: style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17495 }
17496 if (CloseButton(id: host_window->GetID(str: "#CLOSE"), pos: close_button_pos))
17497 {
17498 node->WantCloseAll = true;
17499 for (int n = 0; n < tab_bar->Tabs.Size; n++)
17500 TabBarCloseTab(tab_bar, tab: &tab_bar->Tabs[n]);
17501 }
17502 //if (IsItemActive())
17503 // focus_tab_id = tab_bar->SelectedTabId;
17504 if (!close_button_is_enabled)
17505 {
17506 PopStyleColor();
17507 PopItemFlag();
17508 }
17509 }
17510
17511 // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17512 // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17513 ImGuiID title_bar_id = host_window->GetID(str: "#TITLEBAR");
17514 if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17515 {
17516 // AllowOverlap mode required for appending into dock node tab bar,
17517 // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17518 bool held;
17519 KeepAliveID(id: title_bar_id);
17520 ButtonBehavior(bb: title_bar_rect, id: title_bar_id, NULL, out_held: &held, flags: ImGuiButtonFlags_AllowOverlap);
17521 if (g.HoveredId == title_bar_id)
17522 {
17523 g.LastItemData.ID = title_bar_id;
17524 }
17525 if (held)
17526 {
17527 if (IsMouseClicked(button: 0))
17528 focus_tab_id = tab_bar->SelectedTabId;
17529
17530 // Forward moving request to selected window
17531 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id: tab_bar->SelectedTabId))
17532 StartMouseMovingWindowOrNode(window: tab->Window ? tab->Window : node->HostWindow, node, undock: false); // Undock from tab bar empty space
17533 }
17534 }
17535
17536 // Forward focus from host node to selected window
17537 //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17538 // focus_tab_id = tab_bar->SelectedTabId;
17539
17540 // When clicked on a tab we requested focus to the docked child
17541 // This overrides the value set by "forward focus from host node to selected window".
17542 if (tab_bar->NextSelectedTabId)
17543 focus_tab_id = tab_bar->NextSelectedTabId;
17544
17545 // Apply navigation focus
17546 if (focus_tab_id != 0)
17547 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id: focus_tab_id))
17548 if (tab->Window)
17549 {
17550 FocusWindow(window: tab->Window);
17551 NavInitWindow(window: tab->Window, force_reinit: false);
17552 }
17553
17554 EndTabBar();
17555 PopID();
17556
17557 // Restore SkipItems flag
17558 if (!node->IsDockSpace())
17559 {
17560 host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17561 host_window->SkipItems = backup_skip_item;
17562 }
17563}
17564
17565static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17566{
17567 IM_ASSERT(node->TabBar == NULL);
17568 node->TabBar = IM_NEW(ImGuiTabBar);
17569}
17570
17571static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17572{
17573 if (node->TabBar == NULL)
17574 return;
17575 IM_DELETE(p: node->TabBar);
17576 node->TabBar = NULL;
17577}
17578
17579static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17580{
17581 if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17582 return false;
17583
17584 ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17585 ImGuiWindowClass* payload_class = &payload->WindowClass;
17586 if (host_class->ClassId != payload_class->ClassId)
17587 {
17588 bool pass = false;
17589 if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17590 pass = true;
17591 if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17592 pass = true;
17593 if (!pass)
17594 return false;
17595 }
17596
17597 // Prevent docking any window created above a popup
17598 // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17599 // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17600 // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17601 // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17602 ImGuiContext& g = *GImGui;
17603 for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17604 if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17605 if (ImGui::IsWindowWithinBeginStackOf(window: payload, potential_parent: popup_window)) // Payload is created from within a popup begin stack.
17606 return false;
17607
17608 return true;
17609}
17610
17611static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17612{
17613 if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17614 return true;
17615
17616 const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17617 for (int payload_n = 0; payload_n < payload_count; payload_n++)
17618 {
17619 ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17620 if (DockNodeIsDropAllowedOne(payload, host_window))
17621 return true;
17622 }
17623 return false;
17624}
17625
17626// window menu button == collapse button when not in a dock node.
17627// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17628static 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)
17629{
17630 ImGuiContext& g = *GImGui;
17631 ImGuiStyle& style = g.Style;
17632
17633 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);
17634 if (out_title_rect) { *out_title_rect = r; }
17635
17636 r.Min.x += style.WindowBorderSize;
17637 r.Max.x -= style.WindowBorderSize;
17638
17639 float button_sz = g.FontSize;
17640 r.Min.x += style.FramePadding.x;
17641 r.Max.x -= style.FramePadding.x;
17642 ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17643 if (node->HasCloseButton)
17644 {
17645 if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17646 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17647 }
17648 if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17649 {
17650 r.Min.x += button_sz + style.ItemInnerSpacing.x;
17651 }
17652 else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17653 {
17654 window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17655 r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17656 }
17657 if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17658 if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17659}
17660
17661void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17662{
17663 ImGuiContext& g = *GImGui;
17664 const float dock_spacing = g.Style.ItemInnerSpacing.x;
17665 const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17666 pos_new[axis ^ 1] = pos_old[axis ^ 1];
17667 size_new[axis ^ 1] = size_old[axis ^ 1];
17668
17669 // Distribute size on given axis (with a desired size or equally)
17670 const float w_avail = size_old[axis] - dock_spacing;
17671 if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17672 {
17673 size_new[axis] = size_new_desired[axis];
17674 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17675 }
17676 else
17677 {
17678 size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17679 size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17680 }
17681
17682 // Position each node
17683 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17684 {
17685 pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17686 }
17687 else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17688 {
17689 pos_new[axis] = pos_old[axis];
17690 pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17691 }
17692}
17693
17694// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17695bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17696{
17697 ImGuiContext& g = *GImGui;
17698
17699 const float parent_smaller_axis = ImMin(lhs: parent.GetWidth(), rhs: parent.GetHeight());
17700 const float hs_for_central_nodes = ImMin(lhs: g.FontSize * 1.5f, rhs: ImMax(lhs: g.FontSize * 0.5f, rhs: parent_smaller_axis / 8.0f));
17701 float hs_w; // Half-size, longer axis
17702 float hs_h; // Half-size, smaller axis
17703 ImVec2 off; // Distance from edge or center
17704 if (outer_docking)
17705 {
17706 //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17707 //hs_h = ImTrunc(hs_w * 0.15f);
17708 //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17709 hs_w = ImTrunc(f: hs_for_central_nodes * 1.50f);
17710 hs_h = ImTrunc(f: hs_for_central_nodes * 0.80f);
17711 off = ImTrunc(v: ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17712 }
17713 else
17714 {
17715 hs_w = ImTrunc(f: hs_for_central_nodes);
17716 hs_h = ImTrunc(f: hs_for_central_nodes * 0.90f);
17717 off = ImTrunc(v: ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17718 }
17719
17720 ImVec2 c = ImTrunc(v: parent.GetCenter());
17721 if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
17722 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); }
17723 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); }
17724 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); }
17725 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); }
17726
17727 if (test_mouse_pos == NULL)
17728 return false;
17729
17730 ImRect hit_r = out_r;
17731 if (!outer_docking)
17732 {
17733 // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17734 hit_r.Expand(amount: ImTrunc(f: hs_w * 0.30f));
17735 ImVec2 mouse_delta = (*test_mouse_pos - c);
17736 float mouse_delta_len2 = ImLengthSqr(lhs: mouse_delta);
17737 float r_threshold_center = hs_w * 1.4f;
17738 float r_threshold_sides = hs_w * (1.4f + 1.2f);
17739 if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17740 return (dir == ImGuiDir_None);
17741 if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17742 return (dir == ImGetDirQuadrantFromDelta(dx: mouse_delta.x, dy: mouse_delta.y));
17743 }
17744 return hit_r.Contains(p: *test_mouse_pos);
17745}
17746
17747// host_node may be NULL if the window doesn't have a DockNode already.
17748// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17749static 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)
17750{
17751 ImGuiContext& g = *GImGui;
17752
17753 // There is an edge case when docking into a dockspace which only has inactive nodes.
17754 // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17755 // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17756 if (payload_node == NULL)
17757 payload_node = payload_window->DockNodeAsHost;
17758 ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(node: host_node) : host_node;
17759 if (ref_node_for_rect)
17760 IM_ASSERT(ref_node_for_rect->IsVisible == true);
17761
17762 // Filter, figure out where we are allowed to dock
17763 ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17764 ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17765 data->IsCenterAvailable = true;
17766 if (is_outer_docking)
17767 data->IsCenterAvailable = false;
17768 else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17769 data->IsCenterAvailable = false;
17770 else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17771 data->IsCenterAvailable = false;
17772 else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17773 data->IsCenterAvailable = false;
17774 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17775 data->IsCenterAvailable = false;
17776 else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17777 data->IsCenterAvailable = false;
17778
17779 data->IsSidesAvailable = true;
17780 if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17781 data->IsSidesAvailable = false;
17782 else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17783 data->IsSidesAvailable = false;
17784 else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17785 data->IsSidesAvailable = false;
17786
17787 // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17788 data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17789 data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17790 data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17791 data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17792
17793 // Calculate drop shapes geometry for allowed splitting directions
17794 IM_ASSERT(ImGuiDir_None == -1);
17795 data->SplitNode = host_node;
17796 data->SplitDir = ImGuiDir_None;
17797 data->IsSplitDirExplicit = false;
17798 if (!host_window->Collapsed)
17799 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17800 {
17801 if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17802 continue;
17803 if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17804 continue;
17805 if (DockNodeCalcDropRectsAndTestMousePos(parent: data->FutureNode.Rect(), dir: (ImGuiDir)dir, out_r&: data->DropRectsDraw[dir+1], outer_docking: is_outer_docking, test_mouse_pos: &g.IO.MousePos))
17806 {
17807 data->SplitDir = (ImGuiDir)dir;
17808 data->IsSplitDirExplicit = true;
17809 }
17810 }
17811
17812 // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17813 data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17814 if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17815 data->IsDropAllowed = false;
17816
17817 // Calculate split area
17818 data->SplitRatio = 0.0f;
17819 if (data->SplitDir != ImGuiDir_None)
17820 {
17821 ImGuiDir split_dir = data->SplitDir;
17822 ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17823 ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17824 ImVec2 size_new, size_old = data->FutureNode.Size;
17825 DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir: split_dir, size_new_desired: payload_window->Size);
17826
17827 // Calculate split ratio so we can pass it down the docking request
17828 float split_ratio = ImSaturate(f: size_new[split_axis] / data->FutureNode.Size[split_axis]);
17829 data->FutureNode.Pos = pos_new;
17830 data->FutureNode.Size = size_new;
17831 data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17832 }
17833}
17834
17835static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17836{
17837 ImGuiContext& g = *GImGui;
17838 IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
17839
17840 // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17841 // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17842 const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17843
17844 // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17845 int overlay_draw_lists_count = 0;
17846 ImDrawList* overlay_draw_lists[2];
17847 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(viewport: host_window->Viewport);
17848 if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17849 overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(viewport: root_payload->Viewport);
17850
17851 // Draw main preview rectangle
17852 const ImU32 overlay_col_main = GetColorU32(idx: ImGuiCol_DockingPreview, alpha_mul: is_transparent_payload ? 0.60f : 0.40f);
17853 const ImU32 overlay_col_drop = GetColorU32(idx: ImGuiCol_DockingPreview, alpha_mul: is_transparent_payload ? 0.90f : 0.70f);
17854 const ImU32 overlay_col_drop_hovered = GetColorU32(idx: ImGuiCol_DockingPreview, alpha_mul: is_transparent_payload ? 1.20f : 1.00f);
17855 const ImU32 overlay_col_lines = GetColorU32(idx: ImGuiCol_NavWindowingHighlight, alpha_mul: is_transparent_payload ? 0.80f : 0.60f);
17856
17857 // Display area preview
17858 const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17859 if (data->IsDropAllowed)
17860 {
17861 ImRect overlay_rect = data->FutureNode.Rect();
17862 if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17863 overlay_rect.Min.y += GetFrameHeight();
17864 if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17865 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17866 overlay_draw_lists[overlay_n]->AddRectFilled(p_min: overlay_rect.Min, p_max: overlay_rect.Max, col: overlay_col_main, rounding: host_window->WindowRounding, flags: CalcRoundingFlagsForRectInRect(r_in: overlay_rect, r_outer: host_window->Rect(), threshold: g.Style.DockingSeparatorSize));
17867 }
17868
17869 // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17870 if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17871 {
17872 // Compute target tab bar geometry so we can locate our preview tabs
17873 ImRect tab_bar_rect;
17874 DockNodeCalcTabBarLayout(node: &data->FutureNode, NULL, out_tab_bar_rect: &tab_bar_rect, NULL, NULL);
17875 ImVec2 tab_pos = tab_bar_rect.Min;
17876 if (host_node && host_node->TabBar)
17877 {
17878 if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17879 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.
17880 else
17881 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(window: host_node->Windows[0]).x;
17882 }
17883 else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17884 {
17885 tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(window: host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17886 }
17887
17888 // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17889 if (root_payload->DockNodeAsHost)
17890 IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17891 ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17892 const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17893 for (int payload_n = 0; payload_n < payload_count; payload_n++)
17894 {
17895 // DockNode's TabBar may have non-window Tabs manually appended by user
17896 ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17897 if (tab_bar_with_payload && payload_window == NULL)
17898 continue;
17899 if (!DockNodeIsDropAllowedOne(payload: payload_window, host_window))
17900 continue;
17901
17902 // Calculate the tab bounding box for each payload window
17903 ImVec2 tab_size = TabItemCalcSize(window: payload_window);
17904 ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17905 tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17906 const ImU32 overlay_col_text = GetColorU32(col: payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17907 const ImU32 overlay_col_tabs = GetColorU32(col: payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17908 PushStyleColor(idx: ImGuiCol_Text, col: overlay_col_text);
17909 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17910 {
17911 ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17912 if (!tab_bar_rect.Contains(r: tab_bb))
17913 overlay_draw_lists[overlay_n]->PushClipRect(clip_rect_min: tab_bar_rect.Min, clip_rect_max: tab_bar_rect.Max);
17914 TabItemBackground(draw_list: overlay_draw_lists[overlay_n], bb: tab_bb, flags: tab_flags, col: overlay_col_tabs);
17915 TabItemLabelAndCloseButton(draw_list: overlay_draw_lists[overlay_n], bb: tab_bb, flags: tab_flags, frame_padding: g.Style.FramePadding, label: payload_window->Name, tab_id: 0, close_button_id: 0, is_contents_visible: false, NULL, NULL);
17916 if (!tab_bar_rect.Contains(r: tab_bb))
17917 overlay_draw_lists[overlay_n]->PopClipRect();
17918 }
17919 PopStyleColor();
17920 }
17921 }
17922
17923 // Display drop boxes
17924 const float overlay_rounding = ImMax(lhs: 3.0f, rhs: g.Style.FrameRounding);
17925 for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17926 {
17927 if (!data->DropRectsDraw[dir + 1].IsInverted())
17928 {
17929 ImRect draw_r = data->DropRectsDraw[dir + 1];
17930 ImRect draw_r_in = draw_r;
17931 draw_r_in.Expand(amount: -2.0f);
17932 ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17933 for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17934 {
17935 ImVec2 center = ImFloor(v: draw_r_in.GetCenter());
17936 overlay_draw_lists[overlay_n]->AddRectFilled(p_min: draw_r.Min, p_max: draw_r.Max, col: overlay_col, rounding: overlay_rounding);
17937 overlay_draw_lists[overlay_n]->AddRect(p_min: draw_r_in.Min, p_max: draw_r_in.Max, col: overlay_col_lines, rounding: overlay_rounding);
17938 if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17939 overlay_draw_lists[overlay_n]->AddLine(p1: ImVec2(center.x, draw_r_in.Min.y), p2: ImVec2(center.x, draw_r_in.Max.y), col: overlay_col_lines);
17940 if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17941 overlay_draw_lists[overlay_n]->AddLine(p1: ImVec2(draw_r_in.Min.x, center.y), p2: ImVec2(draw_r_in.Max.x, center.y), col: overlay_col_lines);
17942 }
17943 }
17944
17945 // Stop after ImGuiDir_None
17946 if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17947 return;
17948 }
17949}
17950
17951//-----------------------------------------------------------------------------
17952// Docking: ImGuiDockNode Tree manipulation functions
17953//-----------------------------------------------------------------------------
17954// - DockNodeTreeSplit()
17955// - DockNodeTreeMerge()
17956// - DockNodeTreeUpdatePosSize()
17957// - DockNodeTreeUpdateSplitterFindTouchingNode()
17958// - DockNodeTreeUpdateSplitter()
17959// - DockNodeTreeFindFallbackLeafNode()
17960// - DockNodeTreeFindNodeByPos()
17961//-----------------------------------------------------------------------------
17962
17963void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17964{
17965 ImGuiContext& g = *GImGui;
17966 IM_ASSERT(split_axis != ImGuiAxis_None);
17967
17968 ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, id: 0);
17969 child_0->ParentNode = parent_node;
17970
17971 ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, id: 0);
17972 child_1->ParentNode = parent_node;
17973
17974 ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17975 DockNodeMoveChildNodes(dst_node: child_inheritor, src_node: parent_node);
17976 parent_node->ChildNodes[0] = child_0;
17977 parent_node->ChildNodes[1] = child_1;
17978 parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17979 parent_node->SplitAxis = split_axis;
17980 parent_node->VisibleWindow = NULL;
17981 parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17982
17983 float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17984 size_avail = ImMax(lhs: size_avail, rhs: g.Style.WindowMinSize[split_axis] * 2.0f);
17985 IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17986 child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17987 child_0->SizeRef[split_axis] = ImTrunc(f: size_avail * split_ratio);
17988 child_1->SizeRef[split_axis] = ImTrunc(f: size_avail - child_0->SizeRef[split_axis]);
17989
17990 DockNodeMoveWindows(dst_node: parent_node->ChildNodes[split_inheritor_child_idx], src_node: parent_node);
17991 DockSettingsRenameNodeReferences(old_node_id: parent_node->ID, new_node_id: parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17992 DockNodeUpdateHasCentralNodeChild(node: DockNodeGetRootNode(node: parent_node));
17993 DockNodeTreeUpdatePosSize(node: parent_node, pos: parent_node->Pos, size: parent_node->Size);
17994
17995 // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17996 child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17997 child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17998 child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17999 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18000 child_0->UpdateMergedFlags();
18001 child_1->UpdateMergedFlags();
18002 parent_node->UpdateMergedFlags();
18003 if (child_inheritor->IsCentralNode())
18004 DockNodeGetRootNode(node: parent_node)->CentralNode = child_inheritor;
18005}
18006
18007void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18008{
18009 // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18010 ImGuiContext& g = *GImGui;
18011 ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18012 ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18013 IM_ASSERT(child_0 || child_1);
18014 IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18015 if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18016 {
18017 IM_ASSERT(parent_node->TabBar == NULL);
18018 IM_ASSERT(parent_node->Windows.Size == 0);
18019 }
18020 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);
18021
18022 ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18023 DockNodeMoveChildNodes(dst_node: parent_node, src_node: merge_lead_child);
18024 if (child_0)
18025 {
18026 DockNodeMoveWindows(dst_node: parent_node, src_node: child_0); // Generally only 1 of the 2 child node will have windows
18027 DockSettingsRenameNodeReferences(old_node_id: child_0->ID, new_node_id: parent_node->ID);
18028 }
18029 if (child_1)
18030 {
18031 DockNodeMoveWindows(dst_node: parent_node, src_node: child_1);
18032 DockSettingsRenameNodeReferences(old_node_id: child_1->ID, new_node_id: parent_node->ID);
18033 }
18034 DockNodeApplyPosSizeToWindows(node: parent_node);
18035 parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18036 parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18037 parent_node->SizeRef = backup_last_explicit_size;
18038
18039 // Flags transfer
18040 parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18041 parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18042 parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18043 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
18044 parent_node->UpdateMergedFlags();
18045
18046 if (child_0)
18047 {
18048 ctx->DockContext.Nodes.SetVoidPtr(key: child_0->ID, NULL);
18049 IM_DELETE(p: child_0);
18050 }
18051 if (child_1)
18052 {
18053 ctx->DockContext.Nodes.SetVoidPtr(key: child_1->ID, NULL);
18054 IM_DELETE(p: child_1);
18055 }
18056}
18057
18058// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18059// (Depth-first, Pre-Order)
18060void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18061{
18062 // During the regular dock node update we write to all nodes.
18063 // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18064 ImGuiContext& g = *GImGui;
18065 const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18066 if (write_to_node)
18067 {
18068 node->Pos = pos;
18069 node->Size = size;
18070 }
18071
18072 if (node->IsLeafNode())
18073 return;
18074
18075 ImGuiDockNode* child_0 = node->ChildNodes[0];
18076 ImGuiDockNode* child_1 = node->ChildNodes[1];
18077 ImVec2 child_0_pos = pos, child_1_pos = pos;
18078 ImVec2 child_0_size = size, child_1_size = size;
18079
18080 const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(node: only_write_to_single_node, parent: child_0));
18081 const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(node: only_write_to_single_node, parent: child_1));
18082 const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18083 const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18084
18085 if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18086 {
18087 const float spacing = g.Style.DockingSeparatorSize;
18088 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18089 const float size_avail = ImMax(lhs: size[axis] - spacing, rhs: 0.0f);
18090
18091 // Size allocation policy
18092 // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18093 const float size_min_each = ImTrunc(f: ImMin(lhs: size_avail, rhs: g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18094
18095 // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18096 // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18097 // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18098
18099 // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18100 if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18101 {
18102 child_0_size[axis] = child_0->SizeRef[axis] = ImMin(lhs: size_avail - 1.0f, rhs: child_0->Size[axis]);
18103 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18104 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18105 }
18106 else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18107 {
18108 child_1_size[axis] = child_1->SizeRef[axis] = ImMin(lhs: size_avail - 1.0f, rhs: child_1->Size[axis]);
18109 child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18110 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18111 }
18112 else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18113 {
18114 // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18115 // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18116 float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18117 child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(f: size_avail * split_ratio);
18118 child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18119 IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18120 }
18121
18122 // 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
18123 else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18124 {
18125 child_0_size[axis] = ImMin(lhs: size_avail - size_min_each, rhs: child_0->SizeRef[axis]);
18126 child_1_size[axis] = (size_avail - child_0_size[axis]);
18127 }
18128 else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18129 {
18130 child_1_size[axis] = ImMin(lhs: size_avail - size_min_each, rhs: child_1->SizeRef[axis]);
18131 child_0_size[axis] = (size_avail - child_1_size[axis]);
18132 }
18133 else
18134 {
18135 // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18136 float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18137 child_0_size[axis] = ImMax(lhs: size_min_each, rhs: ImTrunc(f: size_avail * split_ratio + 0.5f));
18138 child_1_size[axis] = (size_avail - child_0_size[axis]);
18139 }
18140
18141 child_1_pos[axis] += spacing + child_0_size[axis];
18142 }
18143
18144 if (only_write_to_single_node == NULL)
18145 child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18146
18147 const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18148 const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18149 if (child_0_recurse)
18150 DockNodeTreeUpdatePosSize(node: child_0, pos: child_0_pos, size: child_0_size);
18151 if (child_1_recurse)
18152 DockNodeTreeUpdatePosSize(node: child_1, pos: child_1_pos, size: child_1_size);
18153}
18154
18155static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18156{
18157 if (node->IsLeafNode())
18158 {
18159 touching_nodes->push_back(v: node);
18160 return;
18161 }
18162 if (node->ChildNodes[0]->IsVisible)
18163 if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18164 DockNodeTreeUpdateSplitterFindTouchingNode(node: node->ChildNodes[0], axis, side, touching_nodes);
18165 if (node->ChildNodes[1]->IsVisible)
18166 if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18167 DockNodeTreeUpdateSplitterFindTouchingNode(node: node->ChildNodes[1], axis, side, touching_nodes);
18168}
18169
18170// (Depth-First, Pre-Order)
18171void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18172{
18173 if (node->IsLeafNode())
18174 return;
18175
18176 ImGuiContext& g = *GImGui;
18177
18178 ImGuiDockNode* child_0 = node->ChildNodes[0];
18179 ImGuiDockNode* child_1 = node->ChildNodes[1];
18180 if (child_0->IsVisible && child_1->IsVisible)
18181 {
18182 // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18183 const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18184 IM_ASSERT(axis != ImGuiAxis_None);
18185 ImRect bb;
18186 bb.Min = child_0->Pos;
18187 bb.Max = child_1->Pos;
18188 bb.Min[axis] += child_0->Size[axis];
18189 bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18190 //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18191
18192 const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18193 const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18194 if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18195 {
18196 ImGuiWindow* window = g.CurrentWindow;
18197 window->DrawList->AddRectFilled(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Separator), rounding: g.Style.FrameRounding);
18198 }
18199 else
18200 {
18201 //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18202 //bb.Max[axis] -= 1;
18203 PushID(int_id: node->ID);
18204
18205 // Find resizing limits by gathering list of nodes that are touching the splitter line.
18206 ImVector<ImGuiDockNode*> touching_nodes[2];
18207 float min_size = g.Style.WindowMinSize[axis];
18208 float resize_limits[2];
18209 resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18210 resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18211
18212 ImGuiID splitter_id = GetID(str_id: "##Splitter");
18213 if (g.ActiveId == splitter_id) // Only process when splitter is active
18214 {
18215 DockNodeTreeUpdateSplitterFindTouchingNode(node: child_0, axis, side: 1, touching_nodes: &touching_nodes[0]);
18216 DockNodeTreeUpdateSplitterFindTouchingNode(node: child_1, axis, side: 0, touching_nodes: &touching_nodes[1]);
18217 for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18218 resize_limits[0] = ImMax(lhs: resize_limits[0], rhs: touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18219 for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18220 resize_limits[1] = ImMin(lhs: resize_limits[1], rhs: touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18221
18222 // [DEBUG] Render touching nodes & limits
18223 /*
18224 ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18225 for (int n = 0; n < 2; n++)
18226 {
18227 for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18228 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));
18229 if (axis == ImGuiAxis_X)
18230 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);
18231 else
18232 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);
18233 }
18234 */
18235 }
18236
18237 // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18238 float cur_size_0 = child_0->Size[axis];
18239 float cur_size_1 = child_1->Size[axis];
18240 float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18241 float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18242 ImU32 bg_col = GetColorU32(idx: ImGuiCol_WindowBg);
18243 if (SplitterBehavior(bb, id: GetID(str_id: "##Splitter"), axis, size1: &cur_size_0, size2: &cur_size_1, min_size1: min_size_0, min_size2: min_size_1, hover_extend: WINDOWS_HOVER_PADDING, hover_visibility_delay: WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18244 {
18245 if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18246 {
18247 child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18248 child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18249 child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18250
18251 // Lock the size of every node that is a sibling of the node we are touching
18252 // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18253 for (int side_n = 0; side_n < 2; side_n++)
18254 for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18255 {
18256 ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18257 //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18258 //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18259 while (touching_node->ParentNode != node)
18260 {
18261 if (touching_node->ParentNode->SplitAxis == axis)
18262 {
18263 // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18264 ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18265 node_to_preserve->WantLockSizeOnce = true;
18266 //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18267 //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18268 }
18269 touching_node = touching_node->ParentNode;
18270 }
18271 }
18272
18273 DockNodeTreeUpdatePosSize(node: child_0, pos: child_0->Pos, size: child_0->Size);
18274 DockNodeTreeUpdatePosSize(node: child_1, pos: child_1->Pos, size: child_1->Size);
18275 MarkIniSettingsDirty();
18276 }
18277 }
18278 PopID();
18279 }
18280 }
18281
18282 if (child_0->IsVisible)
18283 DockNodeTreeUpdateSplitter(node: child_0);
18284 if (child_1->IsVisible)
18285 DockNodeTreeUpdateSplitter(node: child_1);
18286}
18287
18288ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18289{
18290 if (node->IsLeafNode())
18291 return node;
18292 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node: node->ChildNodes[0]))
18293 return leaf_node;
18294 if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node: node->ChildNodes[1]))
18295 return leaf_node;
18296 return NULL;
18297}
18298
18299ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18300{
18301 if (!node->IsVisible)
18302 return NULL;
18303
18304 const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18305 ImRect r(node->Pos, node->Pos + node->Size);
18306 r.Expand(amount: dock_spacing * 0.5f);
18307 bool inside = r.Contains(p: pos);
18308 if (!inside)
18309 return NULL;
18310
18311 if (node->IsLeafNode())
18312 return node;
18313 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node: node->ChildNodes[0], pos))
18314 return hovered_node;
18315 if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node: node->ChildNodes[1], pos))
18316 return hovered_node;
18317
18318 // This means we are hovering over the splitter/spacing of a parent node
18319 return node;
18320}
18321
18322//-----------------------------------------------------------------------------
18323// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18324//-----------------------------------------------------------------------------
18325// - SetWindowDock() [Internal]
18326// - DockSpace()
18327// - DockSpaceOverViewport()
18328//-----------------------------------------------------------------------------
18329
18330// [Internal] Called via SetNextWindowDockID()
18331void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18332{
18333 // Test condition (NB: bit 0 is always true) and clear flags for next time
18334 if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18335 return;
18336 window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18337
18338 if (window->DockId == dock_id)
18339 return;
18340
18341 // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18342 ImGuiContext& g = *GImGui;
18343 if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx: &g, id: dock_id))
18344 if (new_node->IsSplitNode())
18345 {
18346 // Policy: Find central node or latest focused node. We first move back to our root node.
18347 new_node = DockNodeGetRootNode(node: new_node);
18348 if (new_node->CentralNode)
18349 {
18350 IM_ASSERT(new_node->CentralNode->IsCentralNode());
18351 dock_id = new_node->CentralNode->ID;
18352 }
18353 else
18354 {
18355 dock_id = new_node->LastFocusedNodeId;
18356 }
18357 }
18358
18359 if (window->DockId == dock_id)
18360 return;
18361
18362 if (window->DockNode)
18363 DockNodeRemoveWindow(node: window->DockNode, window, save_dock_id: 0);
18364 window->DockId = dock_id;
18365}
18366
18367// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18368// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18369// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18370// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18371ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18372{
18373 ImGuiContext& g = *GImGui;
18374 ImGuiWindow* window = GetCurrentWindowRead();
18375 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18376 return 0;
18377
18378 // Early out if parent window is hidden/collapsed
18379 // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18380 // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18381 if (window->SkipItems)
18382 flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18383 if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18384 window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18385
18386 IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18387 IM_ASSERT(id != 0);
18388 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id);
18389 if (!node)
18390 {
18391 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18392 node = DockContextAddNode(ctx: &g, id);
18393 node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18394 }
18395 if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18396 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18397 node->SharedFlags = flags;
18398 node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18399
18400 // When a DockSpace transitioned form implicit to explicit this may be called a second time
18401 // 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.
18402 if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18403 {
18404 IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18405 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18406 return id;
18407 }
18408 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18409
18410 // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18411 if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18412 {
18413 node->LastFrameAlive = g.FrameCount;
18414 return id;
18415 }
18416
18417 const ImVec2 content_avail = GetContentRegionAvail();
18418 ImVec2 size = ImTrunc(v: size_arg);
18419 if (size.x <= 0.0f)
18420 size.x = ImMax(lhs: content_avail.x + size.x, rhs: 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18421 if (size.y <= 0.0f)
18422 size.y = ImMax(lhs: content_avail.y + size.y, rhs: 4.0f);
18423 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18424
18425 node->Pos = window->DC.CursorPos;
18426 node->Size = node->SizeRef = size;
18427 SetNextWindowPos(pos: node->Pos);
18428 SetNextWindowSize(size: node->Size);
18429 g.NextWindowData.PosUndock = false;
18430
18431 // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18432 // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18433 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18434 window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18435 window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18436 window_flags |= ImGuiWindowFlags_NoBackground;
18437
18438 char title[256];
18439 ImFormatString(buf: title, IM_ARRAYSIZE(title), fmt: "%s/DockSpace_%08X", window->Name, id);
18440
18441 PushStyleVar(idx: ImGuiStyleVar_ChildBorderSize, val: 0.0f);
18442 Begin(name: title, NULL, flags: window_flags);
18443 PopStyleVar();
18444
18445 ImGuiWindow* host_window = g.CurrentWindow;
18446 DockNodeSetupHostWindow(node, host_window);
18447 host_window->ChildId = window->GetID(str: title);
18448 node->OnlyNodeWithWindows = NULL;
18449
18450 IM_ASSERT(node->IsRootNode());
18451
18452 // We need to handle the rare case were a central node is missing.
18453 // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18454 // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18455 // 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.
18456 // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18457 // as it doesn't make sense for an empty dockspace to not have this property.
18458 if (node->IsLeafNode() && !node->IsCentralNode())
18459 node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18460
18461 // Update the node
18462 DockNodeUpdate(node);
18463
18464 End();
18465
18466 ImRect bb(node->Pos, node->Pos + size);
18467 ItemSize(size);
18468 ItemAdd(bb, id, NULL, extra_flags: ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18469 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(window: g.HoveredWindow, potential_parent: host_window, popup_hierarchy: false, dock_hierarchy: true)) // To fullfill IsItemHovered(), similar to EndChild()
18470 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18471
18472 return id;
18473}
18474
18475// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18476// The limitation with this call is that your window won't have a menu bar.
18477// 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.
18478// But you can also use BeginMainMenuBar(). 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.
18479ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18480{
18481 if (viewport == NULL)
18482 viewport = GetMainViewport();
18483
18484 SetNextWindowPos(pos: viewport->WorkPos);
18485 SetNextWindowSize(size: viewport->WorkSize);
18486 SetNextWindowViewport(viewport->ID);
18487
18488 ImGuiWindowFlags host_window_flags = 0;
18489 host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18490 host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18491 if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18492 host_window_flags |= ImGuiWindowFlags_NoBackground;
18493
18494 char label[32];
18495 ImFormatString(buf: label, IM_ARRAYSIZE(label), fmt: "DockSpaceViewport_%08X", viewport->ID);
18496
18497 PushStyleVar(idx: ImGuiStyleVar_WindowRounding, val: 0.0f);
18498 PushStyleVar(idx: ImGuiStyleVar_WindowBorderSize, val: 0.0f);
18499 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: ImVec2(0.0f, 0.0f));
18500 Begin(name: label, NULL, flags: host_window_flags);
18501 PopStyleVar(count: 3);
18502
18503 ImGuiID dockspace_id = GetID(str_id: "DockSpace");
18504 DockSpace(id: dockspace_id, size_arg: ImVec2(0.0f, 0.0f), flags: dockspace_flags, window_class);
18505 End();
18506
18507 return dockspace_id;
18508}
18509
18510//-----------------------------------------------------------------------------
18511// Docking: Builder Functions
18512//-----------------------------------------------------------------------------
18513// Very early end-user API to manipulate dock nodes.
18514// Only available in imgui_internal.h. Expect this API to change/break!
18515// It is expected that those functions are all called _before_ the dockspace node submission.
18516//-----------------------------------------------------------------------------
18517// - DockBuilderDockWindow()
18518// - DockBuilderGetNode()
18519// - DockBuilderSetNodePos()
18520// - DockBuilderSetNodeSize()
18521// - DockBuilderAddNode()
18522// - DockBuilderRemoveNode()
18523// - DockBuilderRemoveNodeChildNodes()
18524// - DockBuilderRemoveNodeDockedWindows()
18525// - DockBuilderSplitNode()
18526// - DockBuilderCopyNodeRec()
18527// - DockBuilderCopyNode()
18528// - DockBuilderCopyWindowSettings()
18529// - DockBuilderCopyDockSpace()
18530// - DockBuilderFinish()
18531//-----------------------------------------------------------------------------
18532
18533void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18534{
18535 // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18536 ImGuiContext& g = *GImGui; IM_UNUSED(g);
18537 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18538 ImGuiID window_id = ImHashStr(data_p: window_name);
18539 if (ImGuiWindow* window = FindWindowByID(id: window_id))
18540 {
18541 // Apply to created window
18542 ImGuiID prev_node_id = window->DockId;
18543 SetWindowDock(window, dock_id: node_id, cond: ImGuiCond_Always);
18544 if (window->DockId != prev_node_id)
18545 window->DockOrder = -1;
18546 }
18547 else
18548 {
18549 // Apply to settings
18550 ImGuiWindowSettings* settings = FindWindowSettingsByID(id: window_id);
18551 if (settings == NULL)
18552 settings = CreateNewWindowSettings(name: window_name);
18553 if (settings->DockId != node_id)
18554 settings->DockOrder = -1;
18555 settings->DockId = node_id;
18556 }
18557}
18558
18559ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18560{
18561 ImGuiContext& g = *GImGui;
18562 return DockContextFindNodeByID(ctx: &g, id: node_id);
18563}
18564
18565void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18566{
18567 ImGuiContext& g = *GImGui;
18568 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: node_id);
18569 if (node == NULL)
18570 return;
18571 node->Pos = pos;
18572 node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18573}
18574
18575void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18576{
18577 ImGuiContext& g = *GImGui;
18578 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: node_id);
18579 if (node == NULL)
18580 return;
18581 IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18582 node->Size = node->SizeRef = size;
18583 node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18584}
18585
18586// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18587// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18588// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18589// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18590// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18591// - Use (id == 0) to let the system allocate a node identifier.
18592// - Existing node with a same id will be removed.
18593ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18594{
18595 ImGuiContext& g = *GImGui; IM_UNUSED(g);
18596 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18597
18598 if (node_id != 0)
18599 DockBuilderRemoveNode(node_id);
18600
18601 ImGuiDockNode* node = NULL;
18602 if (flags & ImGuiDockNodeFlags_DockSpace)
18603 {
18604 DockSpace(id: node_id, size_arg: ImVec2(0, 0), flags: (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18605 node = DockContextFindNodeByID(ctx: &g, id: node_id);
18606 }
18607 else
18608 {
18609 node = DockContextAddNode(ctx: &g, id: node_id);
18610 node->SetLocalFlags(flags);
18611 }
18612 node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
18613 return node->ID;
18614}
18615
18616void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18617{
18618 ImGuiContext& g = *GImGui; IM_UNUSED(g);
18619 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18620
18621 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: node_id);
18622 if (node == NULL)
18623 return;
18624 DockBuilderRemoveNodeDockedWindows(node_id, clear_settings_refs: true);
18625 DockBuilderRemoveNodeChildNodes(node_id);
18626 // Node may have moved or deleted if e.g. any merge happened
18627 node = DockContextFindNodeByID(ctx: &g, id: node_id);
18628 if (node == NULL)
18629 return;
18630 if (node->IsCentralNode() && node->ParentNode)
18631 node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18632 DockContextRemoveNode(ctx: &g, node, merge_sibling_into_parent_node: true);
18633}
18634
18635// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18636void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18637{
18638 ImGuiContext& g = *GImGui;
18639 ImGuiDockContext* dc = &g.DockContext;
18640
18641 ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx: &g, id: root_id) : NULL;
18642 if (root_id && root_node == NULL)
18643 return;
18644 bool has_central_node = false;
18645
18646 ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18647 ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18648
18649 // Process active windows
18650 ImVector<ImGuiDockNode*> nodes_to_remove;
18651 for (int n = 0; n < dc->Nodes.Data.Size; n++)
18652 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18653 {
18654 bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18655 if (want_removal)
18656 {
18657 if (node->IsCentralNode())
18658 has_central_node = true;
18659 if (root_id != 0)
18660 DockContextQueueNotifyRemovedNode(ctx: &g, node);
18661 if (root_node)
18662 {
18663 DockNodeMoveWindows(dst_node: root_node, src_node: node);
18664 DockSettingsRenameNodeReferences(old_node_id: node->ID, new_node_id: root_node->ID);
18665 }
18666 nodes_to_remove.push_back(v: node);
18667 }
18668 }
18669
18670 // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18671 // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18672 if (root_node)
18673 {
18674 root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18675 root_node->AuthorityForSize = backup_root_node_authority_for_size;
18676 }
18677
18678 // Apply to settings
18679 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
18680 if (ImGuiID window_settings_dock_id = settings->DockId)
18681 for (int n = 0; n < nodes_to_remove.Size; n++)
18682 if (nodes_to_remove[n]->ID == window_settings_dock_id)
18683 {
18684 settings->DockId = root_id;
18685 break;
18686 }
18687
18688 // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18689 if (nodes_to_remove.Size > 1)
18690 ImQsort(base: nodes_to_remove.Data, count: nodes_to_remove.Size, size_of_element: sizeof(ImGuiDockNode*), compare_func: DockNodeComparerDepthMostFirst);
18691 for (int n = 0; n < nodes_to_remove.Size; n++)
18692 DockContextRemoveNode(ctx: &g, node: nodes_to_remove[n], merge_sibling_into_parent_node: false);
18693
18694 if (root_id == 0)
18695 {
18696 dc->Nodes.Clear();
18697 dc->Requests.clear();
18698 }
18699 else if (has_central_node)
18700 {
18701 root_node->CentralNode = root_node;
18702 root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18703 }
18704}
18705
18706void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18707{
18708 // Clear references in settings
18709 ImGuiContext& g = *GImGui;
18710 if (clear_settings_refs)
18711 {
18712 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
18713 {
18714 bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18715 if (!want_removal && settings->DockId != 0)
18716 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id: settings->DockId))
18717 if (DockNodeGetRootNode(node)->ID == root_id)
18718 want_removal = true;
18719 if (want_removal)
18720 settings->DockId = 0;
18721 }
18722 }
18723
18724 // Clear references in windows
18725 for (int n = 0; n < g.Windows.Size; n++)
18726 {
18727 ImGuiWindow* window = g.Windows[n];
18728 bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(node: window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18729 if (want_removal)
18730 {
18731 const ImGuiID backup_dock_id = window->DockId;
18732 IM_UNUSED(backup_dock_id);
18733 DockContextProcessUndockWindow(ctx: &g, window, clear_persistent_docking_ref: clear_settings_refs);
18734 if (!clear_settings_refs)
18735 IM_ASSERT(window->DockId == backup_dock_id);
18736 }
18737 }
18738}
18739
18740// 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.
18741// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18742// FIXME-DOCK: We are not exposing nor using split_outer.
18743ImGuiID 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)
18744{
18745 ImGuiContext& g = *GImGui;
18746 IM_ASSERT(split_dir != ImGuiDir_None);
18747 IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18748
18749 ImGuiDockNode* node = DockContextFindNodeByID(ctx: &g, id);
18750 if (node == NULL)
18751 {
18752 IM_ASSERT(node != NULL);
18753 return 0;
18754 }
18755
18756 IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18757
18758 ImGuiDockRequest req;
18759 req.Type = ImGuiDockRequestType_Split;
18760 req.DockTargetWindow = NULL;
18761 req.DockTargetNode = node;
18762 req.DockPayload = NULL;
18763 req.DockSplitDir = split_dir;
18764 req.DockSplitRatio = ImSaturate(f: (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18765 req.DockSplitOuter = false;
18766 DockContextProcessDock(ctx: &g, req: &req);
18767
18768 ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18769 ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18770 if (out_id_at_dir)
18771 *out_id_at_dir = id_at_dir;
18772 if (out_id_at_opposite_dir)
18773 *out_id_at_opposite_dir = id_at_opposite_dir;
18774 return id_at_dir;
18775}
18776
18777static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18778{
18779 ImGuiContext& g = *GImGui;
18780 ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx: &g, id: dst_node_id_if_known);
18781 dst_node->SharedFlags = src_node->SharedFlags;
18782 dst_node->LocalFlags = src_node->LocalFlags;
18783 dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18784 dst_node->Pos = src_node->Pos;
18785 dst_node->Size = src_node->Size;
18786 dst_node->SizeRef = src_node->SizeRef;
18787 dst_node->SplitAxis = src_node->SplitAxis;
18788 dst_node->UpdateMergedFlags();
18789
18790 out_node_remap_pairs->push_back(v: src_node->ID);
18791 out_node_remap_pairs->push_back(v: dst_node->ID);
18792
18793 for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18794 if (src_node->ChildNodes[child_n])
18795 {
18796 dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node: src_node->ChildNodes[child_n], dst_node_id_if_known: 0, out_node_remap_pairs);
18797 dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18798 }
18799
18800 IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18801 return dst_node;
18802}
18803
18804void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18805{
18806 ImGuiContext& g = *GImGui;
18807 IM_ASSERT(src_node_id != 0);
18808 IM_ASSERT(dst_node_id != 0);
18809 IM_ASSERT(out_node_remap_pairs != NULL);
18810
18811 DockBuilderRemoveNode(node_id: dst_node_id);
18812
18813 ImGuiDockNode* src_node = DockContextFindNodeByID(ctx: &g, id: src_node_id);
18814 IM_ASSERT(src_node != NULL);
18815
18816 out_node_remap_pairs->clear();
18817 DockBuilderCopyNodeRec(src_node, dst_node_id_if_known: dst_node_id, out_node_remap_pairs);
18818
18819 IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18820}
18821
18822void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18823{
18824 ImGuiWindow* src_window = FindWindowByName(name: src_name);
18825 if (src_window == NULL)
18826 return;
18827 if (ImGuiWindow* dst_window = FindWindowByName(name: dst_name))
18828 {
18829 dst_window->Pos = src_window->Pos;
18830 dst_window->Size = src_window->Size;
18831 dst_window->SizeFull = src_window->SizeFull;
18832 dst_window->Collapsed = src_window->Collapsed;
18833 }
18834 else
18835 {
18836 ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(id: ImHashStr(data_p: dst_name));
18837 if (!dst_settings)
18838 dst_settings = CreateNewWindowSettings(name: dst_name);
18839 ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18840 if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18841 {
18842 dst_settings->ViewportPos = window_pos_2ih;
18843 dst_settings->ViewportId = src_window->ViewportId;
18844 dst_settings->Pos = ImVec2ih(0, 0);
18845 }
18846 else
18847 {
18848 dst_settings->Pos = window_pos_2ih;
18849 }
18850 dst_settings->Size = ImVec2ih(src_window->SizeFull);
18851 dst_settings->Collapsed = src_window->Collapsed;
18852 }
18853}
18854
18855// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18856void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18857{
18858 ImGuiContext& g = *GImGui;
18859 IM_ASSERT(src_dockspace_id != 0);
18860 IM_ASSERT(dst_dockspace_id != 0);
18861 IM_ASSERT(in_window_remap_pairs != NULL);
18862 IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18863
18864 // Duplicate entire dock
18865 // 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,
18866 // whereas we could attempt to at least keep them together in a new, same floating node.
18867 ImVector<ImGuiID> node_remap_pairs;
18868 DockBuilderCopyNode(src_node_id: src_dockspace_id, dst_node_id: dst_dockspace_id, out_node_remap_pairs: &node_remap_pairs);
18869
18870 // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18871 // (The windows associated to src_dockspace_id are staying in place)
18872 ImVector<ImGuiID> src_windows;
18873 for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18874 {
18875 const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18876 const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18877 ImGuiID src_window_id = ImHashStr(data_p: src_window_name);
18878 src_windows.push_back(v: src_window_id);
18879
18880 // Search in the remapping tables
18881 ImGuiID src_dock_id = 0;
18882 if (ImGuiWindow* src_window = FindWindowByID(id: src_window_id))
18883 src_dock_id = src_window->DockId;
18884 else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(id: src_window_id))
18885 src_dock_id = src_window_settings->DockId;
18886 ImGuiID dst_dock_id = 0;
18887 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18888 if (node_remap_pairs[dock_remap_n] == src_dock_id)
18889 {
18890 dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18891 //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18892 break;
18893 }
18894
18895 if (dst_dock_id != 0)
18896 {
18897 // Docked windows gets redocked into the new node hierarchy.
18898 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);
18899 DockBuilderDockWindow(window_name: dst_window_name, node_id: dst_dock_id);
18900 }
18901 else
18902 {
18903 // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18904 // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18905 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18906 DockBuilderCopyWindowSettings(src_name: src_window_name, dst_name: dst_window_name);
18907 }
18908 }
18909
18910 // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18911 // Find those windows and move to them to the cloned dock node. This may be optional?
18912 // Dock those are a second step as undocking would invalidate source dock nodes.
18913 struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18914 ImVector<DockRemainingWindowTask> dock_remaining_windows;
18915 for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18916 if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18917 {
18918 ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18919 ImGuiDockNode* node = DockBuilderGetNode(node_id: src_dock_id);
18920 for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18921 {
18922 ImGuiWindow* window = node->Windows[window_n];
18923 if (src_windows.contains(v: window->ID))
18924 continue;
18925
18926 // Docked windows gets redocked into the new node hierarchy.
18927 IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18928 dock_remaining_windows.push_back(v: DockRemainingWindowTask(window, dst_dock_id));
18929 }
18930 }
18931 for (const DockRemainingWindowTask& task : dock_remaining_windows)
18932 DockBuilderDockWindow(window_name: task.Window->Name, node_id: task.DockId);
18933}
18934
18935// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18936void ImGui::DockBuilderFinish(ImGuiID root_id)
18937{
18938 ImGuiContext& g = *GImGui;
18939 //DockContextRebuild(&g);
18940 DockContextBuildAddWindowsToNodes(ctx: &g, root_id);
18941}
18942
18943//-----------------------------------------------------------------------------
18944// Docking: Begin/End Support Functions (called from Begin/End)
18945//-----------------------------------------------------------------------------
18946// - GetWindowAlwaysWantOwnTabBar()
18947// - DockContextBindNodeToWindow()
18948// - BeginDocked()
18949// - BeginDockableDragDropSource()
18950// - BeginDockableDragDropTarget()
18951//-----------------------------------------------------------------------------
18952
18953bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18954{
18955 ImGuiContext& g = *GImGui;
18956 if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18957 if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18958 if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18959 return true;
18960 return false;
18961}
18962
18963static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18964{
18965 ImGuiContext& g = *ctx;
18966 ImGuiDockNode* node = DockContextFindNodeByID(ctx, id: window->DockId);
18967 IM_ASSERT(window->DockNode == NULL);
18968
18969 // We should not be docking into a split node (SetWindowDock should avoid this)
18970 if (node && node->IsSplitNode())
18971 {
18972 DockContextProcessUndockWindow(ctx, window);
18973 return NULL;
18974 }
18975
18976 // Create node
18977 if (node == NULL)
18978 {
18979 node = DockContextAddNode(ctx, id: window->DockId);
18980 node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18981 node->LastFrameAlive = g.FrameCount;
18982 }
18983
18984 // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18985 // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18986 // 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.
18987 // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18988 if (!node->IsVisible)
18989 {
18990 ImGuiDockNode* ancestor_node = node;
18991 while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18992 ancestor_node = ancestor_node->ParentNode;
18993 IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18994 DockNodeUpdateHasCentralNodeChild(node: DockNodeGetRootNode(node: ancestor_node));
18995 DockNodeTreeUpdatePosSize(node: ancestor_node, pos: ancestor_node->Pos, size: ancestor_node->Size, only_write_to_single_node: node);
18996 }
18997
18998 // Add window to node
18999 bool node_was_visible = node->IsVisible;
19000 DockNodeAddWindow(node, window, add_to_tab_bar: true);
19001 node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19002 IM_ASSERT(node == window->DockNode);
19003 return node;
19004}
19005
19006void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19007{
19008 ImGuiContext& g = *GImGui;
19009
19010 // Clear fields ahead so most early-out paths don't have to do it
19011 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19012
19013 const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19014 if (auto_dock_node)
19015 {
19016 if (window->DockId == 0)
19017 {
19018 IM_ASSERT(window->DockNode == NULL);
19019 window->DockId = DockContextGenNodeID(ctx: &g);
19020 }
19021 }
19022 else
19023 {
19024 // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19025 bool want_undock = false;
19026 want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19027 want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19028 if (want_undock)
19029 {
19030 DockContextProcessUndockWindow(ctx: &g, window);
19031 return;
19032 }
19033 }
19034
19035 // Bind to our dock node
19036 ImGuiDockNode* node = window->DockNode;
19037 if (node != NULL)
19038 IM_ASSERT(window->DockId == node->ID);
19039 if (window->DockId != 0 && node == NULL)
19040 {
19041 node = DockContextBindNodeToWindow(ctx: &g, window);
19042 if (node == NULL)
19043 return;
19044 }
19045
19046#if 0
19047 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19048 if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19049 {
19050 DockContextProcessUndockWindow(ctx, window);
19051 return;
19052 }
19053#endif
19054
19055 // Undock if our dockspace node disappeared
19056 // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19057 if (node->LastFrameAlive < g.FrameCount)
19058 {
19059 // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19060 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19061 if (root_node->LastFrameAlive < g.FrameCount)
19062 DockContextProcessUndockWindow(ctx: &g, window);
19063 else
19064 window->DockIsActive = true;
19065 return;
19066 }
19067
19068 // Store style overrides
19069 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19070 window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(in: g.Style.Colors[GWindowDockStyleColors[color_n]]);
19071
19072 // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19073 // and never create neither a host window neither a tab bar.
19074 // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19075 if (node->HostWindow == NULL)
19076 {
19077 if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19078 window->DockIsActive = true;
19079 if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19080 DockNodeHideWindowDuringHostWindowCreation(window);
19081 return;
19082 }
19083
19084 // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19085 IM_ASSERT(node->HostWindow);
19086 IM_ASSERT(node->IsLeafNode());
19087 IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19088 node->State = ImGuiDockNodeState_HostWindowVisible;
19089
19090 // Undock if we are submitted earlier than the host window
19091 if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19092 {
19093 DockContextProcessUndockWindow(ctx: &g, window);
19094 return;
19095 }
19096
19097 // Position/Size window
19098 SetNextWindowPos(pos: node->Pos);
19099 SetNextWindowSize(size: node->Size);
19100 g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19101 window->DockIsActive = true;
19102 window->DockNodeIsVisible = true;
19103 window->DockTabIsVisible = false;
19104 if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19105 return;
19106
19107 // When the window is selected we mark it as visible.
19108 if (node->VisibleWindow == window)
19109 window->DockTabIsVisible = true;
19110
19111 // Update window flag
19112 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19113 window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19114 window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19115 if (node->IsHiddenTabBar() || node->IsNoTabBar())
19116 window->Flags |= ImGuiWindowFlags_NoTitleBar;
19117 else
19118 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!
19119
19120 // Save new dock order only if the window has been visible once already
19121 // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19122 if (node->TabBar && window->WasActive)
19123 window->DockOrder = (short)DockNodeGetTabOrder(window);
19124
19125 if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19126 *p_open = false;
19127
19128 // Update ChildId to allow returning from Child to Parent with Escape
19129 ImGuiWindow* parent_window = window->DockNode->HostWindow;
19130 window->ChildId = parent_window->GetID(str: window->Name);
19131}
19132
19133void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19134{
19135 ImGuiContext& g = *GImGui;
19136 IM_ASSERT(g.ActiveId == window->MoveId);
19137 IM_ASSERT(g.MovingWindow == window);
19138 IM_ASSERT(g.CurrentWindow == window);
19139
19140 // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19141 if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19142 {
19143 // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19144 // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19145 // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19146 if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19147 SetTooltip("%s", LocalizeGetMsg(key: ImGuiLocKey_DockingHoldShiftToDock));
19148 return;
19149 }
19150
19151 g.LastItemData.ID = window->MoveId;
19152 window = window->RootWindowDockTree;
19153 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19154 bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(p: g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19155 if (is_drag_docking && BeginDragDropSource(flags: ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
19156 {
19157 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, data: &window, data_size: sizeof(window));
19158 EndDragDropSource();
19159
19160 // Store style overrides
19161 for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19162 window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(in: g.Style.Colors[GWindowDockStyleColors[color_n]]);
19163 }
19164}
19165
19166void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19167{
19168 ImGuiContext& g = *GImGui;
19169
19170 //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19171 IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19172 if (!g.DragDropActive)
19173 return;
19174 //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19175 if (!BeginDragDropTargetCustom(bb: window->Rect(), id: window->ID))
19176 return;
19177
19178 // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19179 // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19180 const ImGuiPayload* payload = &g.DragDropPayload;
19181 if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(host_window: window, root_payload: *(ImGuiWindow**)payload->Data))
19182 {
19183 EndDragDropTarget();
19184 return;
19185 }
19186
19187 ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19188 if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, flags: ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19189 {
19190 // Select target node
19191 // (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)
19192 bool dock_into_floating_window = false;
19193 ImGuiDockNode* node = NULL;
19194 if (window->DockNodeAsHost)
19195 {
19196 // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19197 node = DockNodeTreeFindVisibleNodeByPos(node: window->DockNodeAsHost, pos: g.IO.MousePos);
19198
19199 // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19200 // In this case we need to fallback into any leaf mode, possibly the central node.
19201 // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19202 if (node && node->IsDockSpace() && node->IsRootNode())
19203 node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19204 }
19205 else
19206 {
19207 if (window->DockNode)
19208 node = window->DockNode;
19209 else
19210 dock_into_floating_window = true; // Dock into a regular window
19211 }
19212
19213 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()));
19214 const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(r_min: explicit_target_rect.Min, r_max: explicit_target_rect.Max);
19215
19216 // Preview docking request and find out split direction/ratio
19217 //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.
19218 const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19219 if (do_preview && (node != NULL || dock_into_floating_window))
19220 {
19221 // 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.
19222 ImGuiDockPreviewData split_inner;
19223 ImGuiDockPreviewData split_outer;
19224 ImGuiDockPreviewData* split_data = &split_inner;
19225 if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19226 if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19227 {
19228 DockNodePreviewDockSetup(host_window: window, host_node: root_node, payload_window, NULL, data: &split_outer, is_explicit_target, is_outer_docking: true);
19229 if (split_outer.IsSplitDirExplicit)
19230 split_data = &split_outer;
19231 }
19232 if (!node || node->IsLeafNode())
19233 DockNodePreviewDockSetup(host_window: window, host_node: node, payload_window, NULL, data: &split_inner, is_explicit_target, is_outer_docking: false);
19234 if (split_data == &split_outer)
19235 split_inner.IsDropAllowed = false;
19236
19237 // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19238 DockNodePreviewDockRender(host_window: window, host_node: node, root_payload: payload_window, data: &split_inner);
19239 DockNodePreviewDockRender(host_window: window, host_node: node, root_payload: payload_window, data: &split_outer);
19240
19241 // Queue docking request
19242 if (split_data->IsDropAllowed && payload->IsDelivery())
19243 DockContextQueueDock(ctx: &g, target: window, target_node: split_data->SplitNode, payload: payload_window, split_dir: split_data->SplitDir, split_ratio: split_data->SplitRatio, split_outer: split_data == &split_outer);
19244 }
19245 }
19246 EndDragDropTarget();
19247}
19248
19249//-----------------------------------------------------------------------------
19250// Docking: Settings
19251//-----------------------------------------------------------------------------
19252// - DockSettingsRenameNodeReferences()
19253// - DockSettingsRemoveNodeReferences()
19254// - DockSettingsFindNodeSettings()
19255// - DockSettingsHandler_ApplyAll()
19256// - DockSettingsHandler_ReadOpen()
19257// - DockSettingsHandler_ReadLine()
19258// - DockSettingsHandler_DockNodeToSettings()
19259// - DockSettingsHandler_WriteAll()
19260//-----------------------------------------------------------------------------
19261
19262static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19263{
19264 ImGuiContext& g = *GImGui;
19265 IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19266 for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19267 {
19268 ImGuiWindow* window = g.Windows[window_n];
19269 if (window->DockId == old_node_id && window->DockNode == NULL)
19270 window->DockId = new_node_id;
19271 }
19272 //// FIXME-OPT: We could remove this loop by storing the index in the map
19273 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
19274 if (settings->DockId == old_node_id)
19275 settings->DockId = new_node_id;
19276}
19277
19278// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19279static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19280{
19281 ImGuiContext& g = *GImGui;
19282 int found = 0;
19283 //// FIXME-OPT: We could remove this loop by storing the index in the map
19284 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
19285 for (int node_n = 0; node_n < node_ids_count; node_n++)
19286 if (settings->DockId == node_ids[node_n])
19287 {
19288 settings->DockId = 0;
19289 settings->DockOrder = -1;
19290 if (++found < node_ids_count)
19291 break;
19292 return;
19293 }
19294}
19295
19296static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19297{
19298 // FIXME-OPT
19299 ImGuiDockContext* dc = &ctx->DockContext;
19300 for (int n = 0; n < dc->NodesSettings.Size; n++)
19301 if (dc->NodesSettings[n].ID == id)
19302 return &dc->NodesSettings[n];
19303 return NULL;
19304}
19305
19306// Clear settings data
19307static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19308{
19309 ImGuiDockContext* dc = &ctx->DockContext;
19310 dc->NodesSettings.clear();
19311 DockContextClearNodes(ctx, root_id: 0, clear_settings_refs: true);
19312}
19313
19314// Recreate nodes based on settings data
19315static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19316{
19317 // Prune settings at boot time only
19318 ImGuiDockContext* dc = &ctx->DockContext;
19319 if (ctx->Windows.Size == 0)
19320 DockContextPruneUnusedSettingsNodes(ctx);
19321 DockContextBuildNodesFromSettings(ctx, node_settings_array: dc->NodesSettings.Data, node_settings_count: dc->NodesSettings.Size);
19322 DockContextBuildAddWindowsToNodes(ctx, root_id: 0);
19323}
19324
19325static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19326{
19327 if (strcmp(s1: name, s2: "Data") != 0)
19328 return NULL;
19329 return (void*)1;
19330}
19331
19332static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19333{
19334 char c = 0;
19335 int x = 0, y = 0;
19336 int r = 0;
19337
19338 // Parsing, e.g.
19339 // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19340 // " DockNode ID=0x00000002 Parent=0x00000001 "
19341 // Important: this code expect currently fields in a fixed order.
19342 ImGuiDockNodeSettings node;
19343 line = ImStrSkipBlank(str: line);
19344 if (strncmp(s1: line, s2: "DockNode", n: 8) == 0) { line = ImStrSkipBlank(str: line + strlen(s: "DockNode")); }
19345 else if (strncmp(s1: line, s2: "DockSpace", n: 9) == 0) { line = ImStrSkipBlank(str: line + strlen(s: "DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19346 else return;
19347 if (sscanf(s: line, format: "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
19348 if (sscanf(s: line, format: " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
19349 if (sscanf(s: line, format: " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19350 if (node.ParentNodeId == 0)
19351 {
19352 if (sscanf(s: line, format: " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19353 if (sscanf(s: line, format: " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19354 }
19355 else
19356 {
19357 if (sscanf(s: line, format: " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19358 }
19359 if (sscanf(s: line, format: " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19360 if (sscanf(s: line, format: " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19361 if (sscanf(s: line, format: " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19362 if (sscanf(s: line, format: " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19363 if (sscanf(s: line, format: " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19364 if (sscanf(s: line, format: " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19365 if (sscanf(s: line, format: " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19366 if (sscanf(s: line, format: " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19367 if (node.ParentNodeId != 0)
19368 if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, id: node.ParentNodeId))
19369 node.Depth = parent_settings->Depth + 1;
19370 ctx->DockContext.NodesSettings.push_back(v: node);
19371}
19372
19373static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19374{
19375 ImGuiDockNodeSettings node_settings;
19376 IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19377 node_settings.ID = node->ID;
19378 node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19379 node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19380 node_settings.SelectedTabId = node->SelectedTabId;
19381 node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19382 node_settings.Depth = (char)depth;
19383 node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19384 node_settings.Pos = ImVec2ih(node->Pos);
19385 node_settings.Size = ImVec2ih(node->Size);
19386 node_settings.SizeRef = ImVec2ih(node->SizeRef);
19387 dc->NodesSettings.push_back(v: node_settings);
19388 if (node->ChildNodes[0])
19389 DockSettingsHandler_DockNodeToSettings(dc, node: node->ChildNodes[0], depth: depth + 1);
19390 if (node->ChildNodes[1])
19391 DockSettingsHandler_DockNodeToSettings(dc, node: node->ChildNodes[1], depth: depth + 1);
19392}
19393
19394static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19395{
19396 ImGuiContext& g = *ctx;
19397 ImGuiDockContext* dc = &ctx->DockContext;
19398 if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19399 return;
19400
19401 // Gather settings data
19402 // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19403 dc->NodesSettings.resize(new_size: 0);
19404 dc->NodesSettings.reserve(new_capacity: dc->Nodes.Data.Size);
19405 for (int n = 0; n < dc->Nodes.Data.Size; n++)
19406 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19407 if (node->IsRootNode())
19408 DockSettingsHandler_DockNodeToSettings(dc, node, depth: 0);
19409
19410 int max_depth = 0;
19411 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19412 max_depth = ImMax(lhs: (int)dc->NodesSettings[node_n].Depth, rhs: max_depth);
19413
19414 // Write to text buffer
19415 buf->appendf(fmt: "[%s][Data]\n", handler->TypeName);
19416 for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19417 {
19418 const int line_start_pos = buf->size(); (void)line_start_pos;
19419 const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19420 buf->appendf(fmt: "%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file
19421 buf->appendf(fmt: " ID=0x%08X", node_settings->ID);
19422 if (node_settings->ParentNodeId)
19423 {
19424 buf->appendf(fmt: " Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19425 }
19426 else
19427 {
19428 if (node_settings->ParentWindowId)
19429 buf->appendf(fmt: " Window=0x%08X", node_settings->ParentWindowId);
19430 buf->appendf(fmt: " Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19431 }
19432 if (node_settings->SplitAxis != ImGuiAxis_None)
19433 buf->appendf(fmt: " Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19434 if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19435 buf->appendf(fmt: " NoResize=1");
19436 if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19437 buf->appendf(fmt: " CentralNode=1");
19438 if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19439 buf->appendf(fmt: " NoTabBar=1");
19440 if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19441 buf->appendf(fmt: " HiddenTabBar=1");
19442 if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19443 buf->appendf(fmt: " NoWindowMenuButton=1");
19444 if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19445 buf->appendf(fmt: " NoCloseButton=1");
19446 if (node_settings->SelectedTabId)
19447 buf->appendf(fmt: " Selected=0x%08X", node_settings->SelectedTabId);
19448
19449 // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19450 if (g.IO.ConfigDebugIniSettings)
19451 if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, id: node_settings->ID))
19452 {
19453 buf->appendf(fmt: "%*s", ImMax(lhs: 2, rhs: (line_start_pos + 92) - buf->size()), ""); // Align everything
19454 if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19455 buf->appendf(fmt: " ; in '%s'", node->HostWindow->ParentWindow->Name);
19456 // Iterate settings so we can give info about windows that didn't exist during the session.
19457 int contains_window = 0;
19458 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
19459 if (settings->DockId == node_settings->ID)
19460 {
19461 if (contains_window++ == 0)
19462 buf->appendf(fmt: " ; contains ");
19463 buf->appendf(fmt: "'%s' ", settings->GetName());
19464 }
19465 }
19466
19467 buf->appendf(fmt: "\n");
19468 }
19469 buf->appendf(fmt: "\n");
19470}
19471
19472
19473//-----------------------------------------------------------------------------
19474// [SECTION] PLATFORM DEPENDENT HELPERS
19475//-----------------------------------------------------------------------------
19476
19477#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19478
19479#ifdef _MSC_VER
19480#pragma comment(lib, "user32")
19481#pragma comment(lib, "kernel32")
19482#endif
19483
19484// Win32 clipboard implementation
19485// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19486static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19487{
19488 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19489 g.ClipboardHandlerData.clear();
19490 if (!::OpenClipboard(NULL))
19491 return NULL;
19492 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19493 if (wbuf_handle == NULL)
19494 {
19495 ::CloseClipboard();
19496 return NULL;
19497 }
19498 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19499 {
19500 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19501 g.ClipboardHandlerData.resize(buf_len);
19502 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19503 }
19504 ::GlobalUnlock(wbuf_handle);
19505 ::CloseClipboard();
19506 return g.ClipboardHandlerData.Data;
19507}
19508
19509static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19510{
19511 if (!::OpenClipboard(NULL))
19512 return;
19513 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19514 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19515 if (wbuf_handle == NULL)
19516 {
19517 ::CloseClipboard();
19518 return;
19519 }
19520 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19521 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19522 ::GlobalUnlock(wbuf_handle);
19523 ::EmptyClipboard();
19524 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19525 ::GlobalFree(wbuf_handle);
19526 ::CloseClipboard();
19527}
19528
19529#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19530
19531#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
19532static PasteboardRef main_clipboard = 0;
19533
19534// OSX clipboard implementation
19535// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19536static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19537{
19538 if (!main_clipboard)
19539 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19540 PasteboardClear(main_clipboard);
19541 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19542 if (cf_data)
19543 {
19544 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19545 CFRelease(cf_data);
19546 }
19547}
19548
19549static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19550{
19551 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19552 if (!main_clipboard)
19553 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19554 PasteboardSynchronize(main_clipboard);
19555
19556 ItemCount item_count = 0;
19557 PasteboardGetItemCount(main_clipboard, &item_count);
19558 for (ItemCount i = 0; i < item_count; i++)
19559 {
19560 PasteboardItemID item_id = 0;
19561 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19562 CFArrayRef flavor_type_array = 0;
19563 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19564 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19565 {
19566 CFDataRef cf_data;
19567 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19568 {
19569 g.ClipboardHandlerData.clear();
19570 int length = (int)CFDataGetLength(cf_data);
19571 g.ClipboardHandlerData.resize(length + 1);
19572 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19573 g.ClipboardHandlerData[length] = 0;
19574 CFRelease(cf_data);
19575 return g.ClipboardHandlerData.Data;
19576 }
19577 }
19578 }
19579 return NULL;
19580}
19581
19582#else
19583
19584// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19585static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19586{
19587 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19588 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19589}
19590
19591static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19592{
19593 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19594 g.ClipboardHandlerData.clear();
19595 const char* text_end = text + strlen(s: text);
19596 g.ClipboardHandlerData.resize(new_size: (int)(text_end - text) + 1);
19597 memcpy(dest: &g.ClipboardHandlerData[0], src: text, n: (size_t)(text_end - text));
19598 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19599}
19600
19601#endif
19602
19603// Win32 API IME support (for Asian languages, etc.)
19604#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19605
19606#include <imm.h>
19607#ifdef _MSC_VER
19608#pragma comment(lib, "imm32")
19609#endif
19610
19611static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19612{
19613 // Notify OS Input Method Editor of text input position
19614 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19615 if (hwnd == 0)
19616 return;
19617
19618 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19619 if (HIMC himc = ::ImmGetContext(hwnd))
19620 {
19621 COMPOSITIONFORM composition_form = {};
19622 composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19623 composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19624 composition_form.dwStyle = CFS_FORCE_POSITION;
19625 ::ImmSetCompositionWindow(himc, &composition_form);
19626 CANDIDATEFORM candidate_form = {};
19627 candidate_form.dwStyle = CFS_CANDIDATEPOS;
19628 candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19629 candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19630 ::ImmSetCandidateWindow(himc, &candidate_form);
19631 ::ImmReleaseContext(hwnd, himc);
19632 }
19633}
19634
19635#else
19636
19637static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19638
19639#endif
19640
19641//-----------------------------------------------------------------------------
19642// [SECTION] METRICS/DEBUGGER WINDOW
19643//-----------------------------------------------------------------------------
19644// - DebugRenderViewportThumbnail() [Internal]
19645// - RenderViewportsThumbnails() [Internal]
19646// - DebugTextEncoding()
19647// - MetricsHelpMarker() [Internal]
19648// - ShowFontAtlas() [Internal]
19649// - ShowMetricsWindow()
19650// - DebugNodeColumns() [Internal]
19651// - DebugNodeDockNode() [Internal]
19652// - DebugNodeDrawList() [Internal]
19653// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19654// - DebugNodeFont() [Internal]
19655// - DebugNodeFontGlyph() [Internal]
19656// - DebugNodeStorage() [Internal]
19657// - DebugNodeTabBar() [Internal]
19658// - DebugNodeViewport() [Internal]
19659// - DebugNodeWindow() [Internal]
19660// - DebugNodeWindowSettings() [Internal]
19661// - DebugNodeWindowsList() [Internal]
19662// - DebugNodeWindowsListByBeginStackParent() [Internal]
19663//-----------------------------------------------------------------------------
19664
19665#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19666
19667void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19668{
19669 ImGuiContext& g = *GImGui;
19670 ImGuiWindow* window = g.CurrentWindow;
19671
19672 ImVec2 scale = bb.GetSize() / viewport->Size;
19673 ImVec2 off = bb.Min - viewport->Pos * scale;
19674 float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19675 window->DrawList->AddRectFilled(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul: alpha_mul * 0.40f));
19676 for (ImGuiWindow* thumb_window : g.Windows)
19677 {
19678 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19679 continue;
19680 if (thumb_window->Viewport != viewport)
19681 continue;
19682
19683 ImRect thumb_r = thumb_window->Rect();
19684 ImRect title_r = thumb_window->TitleBarRect();
19685 thumb_r = ImRect(ImTrunc(v: off + thumb_r.Min * scale), ImTrunc(v: off + thumb_r.Max * scale));
19686 title_r = ImRect(ImTrunc(v: off + title_r.Min * scale), ImTrunc(v: off + ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
19687 thumb_r.ClipWithFull(r: bb);
19688 title_r.ClipWithFull(r: bb);
19689 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19690 window->DrawList->AddRectFilled(p_min: thumb_r.Min, p_max: thumb_r.Max, col: GetColorU32(idx: ImGuiCol_WindowBg, alpha_mul));
19691 window->DrawList->AddRectFilled(p_min: title_r.Min, p_max: title_r.Max, col: GetColorU32(idx: window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19692 window->DrawList->AddRect(p_min: thumb_r.Min, p_max: thumb_r.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul));
19693 window->DrawList->AddText(font: g.Font, font_size: g.FontSize * 1.0f, pos: title_r.Min, col: GetColorU32(idx: ImGuiCol_Text, alpha_mul), text_begin: thumb_window->Name, text_end: FindRenderedTextEnd(text: thumb_window->Name));
19694 }
19695 draw_list->AddRect(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul));
19696 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
19697 window->DrawList->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
19698}
19699
19700static void RenderViewportsThumbnails()
19701{
19702 ImGuiContext& g = *GImGui;
19703 ImGuiWindow* window = g.CurrentWindow;
19704
19705 // Draw monitor and calculate their boundaries
19706 float SCALE = 1.0f / 8.0f;
19707 ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19708 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19709 bb_full.Add(r: ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
19710 ImVec2 p = window->DC.CursorPos;
19711 ImVec2 off = p - bb_full.Min * SCALE;
19712 for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19713 {
19714 ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
19715 window->DrawList->AddRect(p_min: monitor_draw_bb.Min, p_max: monitor_draw_bb.Max, col: (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(it: &monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(idx: ImGuiCol_Border), rounding: 4.0f);
19716 window->DrawList->AddRectFilled(p_min: monitor_draw_bb.Min, p_max: monitor_draw_bb.Max, col: ImGui::GetColorU32(idx: ImGuiCol_Border, alpha_mul: 0.10f), rounding: 4.0f);
19717 }
19718
19719 // Draw viewports
19720 for (ImGuiViewportP* viewport : g.Viewports)
19721 {
19722 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19723 ImGui::DebugRenderViewportThumbnail(draw_list: window->DrawList, viewport, bb: viewport_draw_bb);
19724 }
19725 ImGui::Dummy(size: bb_full.GetSize() * SCALE);
19726}
19727
19728static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19729{
19730 const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19731 const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19732 return b->LastFocusedStampCount - a->LastFocusedStampCount;
19733}
19734
19735// Draw an arbitrary US keyboard layout to visualize translated keys
19736void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19737{
19738 const float scale = ImGui::GetFontSize() / 13.0f;
19739 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
19740 const float key_rounding = 3.0f * scale;
19741 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
19742 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
19743 const float key_face_rounding = 2.0f * scale;
19744 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
19745 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19746 const float key_row_offset = 9.0f * scale;
19747
19748 ImVec2 board_min = GetCursorScreenPos();
19749 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);
19750 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19751
19752 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19753 const KeyLayoutData keys_to_display[] =
19754 {
19755 { .Row: 0, .Col: 0, .Label: "", .Key: ImGuiKey_Tab }, { .Row: 0, .Col: 1, .Label: "Q", .Key: ImGuiKey_Q }, { .Row: 0, .Col: 2, .Label: "W", .Key: ImGuiKey_W }, { .Row: 0, .Col: 3, .Label: "E", .Key: ImGuiKey_E }, { .Row: 0, .Col: 4, .Label: "R", .Key: ImGuiKey_R },
19756 { .Row: 1, .Col: 0, .Label: "", .Key: ImGuiKey_CapsLock }, { .Row: 1, .Col: 1, .Label: "A", .Key: ImGuiKey_A }, { .Row: 1, .Col: 2, .Label: "S", .Key: ImGuiKey_S }, { .Row: 1, .Col: 3, .Label: "D", .Key: ImGuiKey_D }, { .Row: 1, .Col: 4, .Label: "F", .Key: ImGuiKey_F },
19757 { .Row: 2, .Col: 0, .Label: "", .Key: ImGuiKey_LeftShift },{ .Row: 2, .Col: 1, .Label: "Z", .Key: ImGuiKey_Z }, { .Row: 2, .Col: 2, .Label: "X", .Key: ImGuiKey_X }, { .Row: 2, .Col: 3, .Label: "C", .Key: ImGuiKey_C }, { .Row: 2, .Col: 4, .Label: "V", .Key: ImGuiKey_V }
19758 };
19759
19760 // Elements rendered manually via ImDrawList API are not clipped automatically.
19761 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19762 Dummy(size: board_max - board_min);
19763 if (!IsItemVisible())
19764 return;
19765 draw_list->PushClipRect(clip_rect_min: board_min, clip_rect_max: board_max, intersect_with_current_clip_rect: true);
19766 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19767 {
19768 const KeyLayoutData* key_data = &keys_to_display[n];
19769 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);
19770 ImVec2 key_max = key_min + key_size;
19771 draw_list->AddRectFilled(p_min: key_min, p_max: key_max, IM_COL32(204, 204, 204, 255), rounding: key_rounding);
19772 draw_list->AddRect(p_min: key_min, p_max: key_max, IM_COL32(24, 24, 24, 255), rounding: key_rounding);
19773 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19774 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19775 draw_list->AddRect(p_min: face_min, p_max: face_max, IM_COL32(193, 193, 193, 255), rounding: key_face_rounding, flags: ImDrawFlags_None, thickness: 2.0f);
19776 draw_list->AddRectFilled(p_min: face_min, p_max: face_max, IM_COL32(252, 252, 252, 255), rounding: key_face_rounding);
19777 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19778 draw_list->AddText(pos: label_min, IM_COL32(64, 64, 64, 255), text_begin: key_data->Label);
19779 if (IsKeyDown(key: key_data->Key))
19780 draw_list->AddRectFilled(p_min: key_min, p_max: key_max, IM_COL32(255, 0, 0, 128), rounding: key_rounding);
19781 }
19782 draw_list->PopClipRect();
19783}
19784
19785// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19786void ImGui::DebugTextEncoding(const char* str)
19787{
19788 Text(fmt: "Text: \"%s\"", str);
19789 if (!BeginTable(str_id: "##DebugTextEncoding", column: 4, flags: ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19790 return;
19791 TableSetupColumn(label: "Offset");
19792 TableSetupColumn(label: "UTF-8");
19793 TableSetupColumn(label: "Glyph");
19794 TableSetupColumn(label: "Codepoint");
19795 TableHeadersRow();
19796 for (const char* p = str; *p != 0; )
19797 {
19798 unsigned int c;
19799 const int c_utf8_len = ImTextCharFromUtf8(out_char: &c, in_text: p, NULL);
19800 TableNextColumn();
19801 Text(fmt: "%d", (int)(p - str));
19802 TableNextColumn();
19803 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19804 {
19805 if (byte_index > 0)
19806 SameLine();
19807 Text(fmt: "0x%02X", (int)(unsigned char)p[byte_index]);
19808 }
19809 TableNextColumn();
19810 if (GetFont()->FindGlyphNoFallback(c: (ImWchar)c))
19811 TextUnformatted(text: p, text_end: p + c_utf8_len);
19812 else
19813 TextUnformatted(text: (c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19814 TableNextColumn();
19815 Text(fmt: "U+%04X", (int)c);
19816 p += c_utf8_len;
19817 }
19818 EndTable();
19819}
19820
19821static void DebugFlashStyleColorStop()
19822{
19823 ImGuiContext& g = *GImGui;
19824 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
19825 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
19826 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
19827}
19828
19829// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
19830void ImGui::DebugFlashStyleColor(ImGuiCol idx)
19831{
19832 ImGuiContext& g = *GImGui;
19833 DebugFlashStyleColorStop();
19834 g.DebugFlashStyleColorTime = 0.5f;
19835 g.DebugFlashStyleColorIdx = idx;
19836 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
19837}
19838
19839void ImGui::UpdateDebugToolFlashStyleColor()
19840{
19841 ImGuiContext& g = *GImGui;
19842 if (g.DebugFlashStyleColorTime <= 0.0f)
19843 return;
19844 ColorConvertHSVtoRGB(h: cosf(x: g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, s: 0.5f, v: 0.5f, out_r&: g.Style.Colors[g.DebugFlashStyleColorIdx].x, out_g&: g.Style.Colors[g.DebugFlashStyleColorIdx].y, out_b&: g.Style.Colors[g.DebugFlashStyleColorIdx].z);
19845 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
19846 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
19847 DebugFlashStyleColorStop();
19848}
19849
19850// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19851static void MetricsHelpMarker(const char* desc)
19852{
19853 ImGui::TextDisabled(fmt: "(?)");
19854 if (ImGui::BeginItemTooltip())
19855 {
19856 ImGui::PushTextWrapPos(wrap_pos_x: ImGui::GetFontSize() * 35.0f);
19857 ImGui::TextUnformatted(text: desc);
19858 ImGui::PopTextWrapPos();
19859 ImGui::EndTooltip();
19860 }
19861}
19862
19863// [DEBUG] List fonts in a font atlas and display its texture
19864void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19865{
19866 for (ImFont* font : atlas->Fonts)
19867 {
19868 PushID(ptr_id: font);
19869 DebugNodeFont(font);
19870 PopID();
19871 }
19872 if (TreeNode(str_id: "Font Atlas", fmt: "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19873 {
19874 ImGuiContext& g = *GImGui;
19875 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19876 Checkbox(label: "Tint with Text Color", v: &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19877 ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(idx: ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19878 ImVec4 border_col = GetStyleColorVec4(idx: ImGuiCol_Border);
19879 Image(user_texture_id: atlas->TexID, image_size: ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), uv0: ImVec2(0.0f, 0.0f), uv1: ImVec2(1.0f, 1.0f), tint_col, border_col);
19880 TreePop();
19881 }
19882}
19883
19884void ImGui::ShowMetricsWindow(bool* p_open)
19885{
19886 ImGuiContext& g = *GImGui;
19887 ImGuiIO& io = g.IO;
19888 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19889 if (cfg->ShowDebugLog)
19890 ShowDebugLogWindow(p_open: &cfg->ShowDebugLog);
19891 if (cfg->ShowIDStackTool)
19892 ShowIDStackToolWindow(p_open: &cfg->ShowIDStackTool);
19893
19894 if (!Begin(name: "Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19895 {
19896 End();
19897 return;
19898 }
19899
19900 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
19901 DebugBreakClearData();
19902
19903 // Basic info
19904 Text(fmt: "Dear ImGui %s", GetVersion());
19905 Text(fmt: "Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19906 Text(fmt: "%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19907 Text(fmt: "%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19908 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19909
19910 Separator();
19911
19912 // Debugging enums
19913 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19914 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19915 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
19916 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19917 if (cfg->ShowWindowsRectsType < 0)
19918 cfg->ShowWindowsRectsType = WRT_WorkRect;
19919 if (cfg->ShowTablesRectsType < 0)
19920 cfg->ShowTablesRectsType = TRT_WorkRect;
19921
19922 struct Funcs
19923 {
19924 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19925 {
19926 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent); // Always using last submitted instance
19927 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
19928 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
19929 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
19930 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
19931 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
19932 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
19933 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); }
19934 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); }
19935 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19936 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
19937 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); }
19938 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); }
19939 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); }
19940 IM_ASSERT(0);
19941 return ImRect();
19942 }
19943
19944 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19945 {
19946 if (rect_type == WRT_OuterRect) { return window->Rect(); }
19947 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
19948 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
19949 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
19950 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
19951 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19952 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19953 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
19954 IM_ASSERT(0);
19955 return ImRect();
19956 }
19957 };
19958
19959 // Tools
19960 if (TreeNode(label: "Tools"))
19961 {
19962 // Debug Break features
19963 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19964 SeparatorTextEx(id: 0, label: "Debug breaks", NULL, extra_width: CalcTextSize(text: "(?)").x + g.Style.SeparatorTextPadding.x);
19965 SameLine();
19966 MetricsHelpMarker(desc: "Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19967 if (Checkbox(label: "Show Item Picker", v: &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19968 DebugStartItemPicker();
19969 Checkbox(label: "Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", v: &g.IO.ConfigDebugIsDebuggerPresent);
19970
19971 SeparatorText(label: "Visualize");
19972
19973 Checkbox(label: "Show Debug Log", v: &cfg->ShowDebugLog);
19974 SameLine();
19975 MetricsHelpMarker(desc: "You can also call ImGui::ShowDebugLogWindow() from your code.");
19976
19977 Checkbox(label: "Show ID Stack Tool", v: &cfg->ShowIDStackTool);
19978 SameLine();
19979 MetricsHelpMarker(desc: "You can also call ImGui::ShowIDStackToolWindow() from your code.");
19980
19981 Checkbox(label: "Show windows begin order", v: &cfg->ShowWindowsBeginOrder);
19982 Checkbox(label: "Show windows rectangles", v: &cfg->ShowWindowsRects);
19983 SameLine();
19984 SetNextItemWidth(GetFontSize() * 12);
19985 cfg->ShowWindowsRects |= Combo(label: "##show_windows_rect_type", current_item: &cfg->ShowWindowsRectsType, items: wrt_rects_names, items_count: WRT_Count, popup_max_height_in_items: WRT_Count);
19986 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19987 {
19988 BulletText(fmt: "'%s':", g.NavWindow->Name);
19989 Indent();
19990 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19991 {
19992 ImRect r = Funcs::GetWindowRect(window: g.NavWindow, rect_type: rect_n);
19993 Text(fmt: "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19994 }
19995 Unindent();
19996 }
19997
19998 Checkbox(label: "Show tables rectangles", v: &cfg->ShowTablesRects);
19999 SameLine();
20000 SetNextItemWidth(GetFontSize() * 12);
20001 cfg->ShowTablesRects |= Combo(label: "##show_table_rects_type", current_item: &cfg->ShowTablesRectsType, items: trt_rects_names, items_count: TRT_Count, popup_max_height_in_items: TRT_Count);
20002 if (cfg->ShowTablesRects && g.NavWindow != NULL)
20003 {
20004 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20005 {
20006 ImGuiTable* table = g.Tables.TryGetMapData(n: table_n);
20007 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20008 continue;
20009
20010 BulletText(fmt: "Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20011 if (IsItemHovered())
20012 GetForegroundDrawList()->AddRect(p_min: table->OuterRect.Min - ImVec2(1, 1), p_max: table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), rounding: 0.0f, flags: 0, thickness: 2.0f);
20013 Indent();
20014 char buf[128];
20015 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20016 {
20017 if (rect_n >= TRT_ColumnsRect)
20018 {
20019 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20020 continue;
20021 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20022 {
20023 ImRect r = Funcs::GetTableRect(table, rect_type: rect_n, n: column_n);
20024 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20025 Selectable(label: buf);
20026 if (IsItemHovered())
20027 GetForegroundDrawList()->AddRect(p_min: r.Min - ImVec2(1, 1), p_max: r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), rounding: 0.0f, flags: 0, thickness: 2.0f);
20028 }
20029 }
20030 else
20031 {
20032 ImRect r = Funcs::GetTableRect(table, rect_type: rect_n, n: -1);
20033 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20034 Selectable(label: buf);
20035 if (IsItemHovered())
20036 GetForegroundDrawList()->AddRect(p_min: r.Min - ImVec2(1, 1), p_max: r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), rounding: 0.0f, flags: 0, thickness: 2.0f);
20037 }
20038 }
20039 Unindent();
20040 }
20041 }
20042 Checkbox(label: "Show groups rectangles", v: &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20043
20044 SeparatorText(label: "Validate");
20045
20046 Checkbox(label: "Debug Begin/BeginChild return value", v: &io.ConfigDebugBeginReturnValueLoop);
20047 SameLine();
20048 MetricsHelpMarker(desc: "Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20049
20050 Checkbox(label: "UTF-8 Encoding viewer", v: &cfg->ShowTextEncodingViewer);
20051 SameLine();
20052 MetricsHelpMarker(desc: "You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20053 if (cfg->ShowTextEncodingViewer)
20054 {
20055 static char buf[64] = "";
20056 SetNextItemWidth(-FLT_MIN);
20057 InputText(label: "##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20058 if (buf[0] != 0)
20059 DebugTextEncoding(str: buf);
20060 }
20061
20062 TreePop();
20063 }
20064
20065 // Windows
20066 if (TreeNode(str_id: "Windows", fmt: "Windows (%d)", g.Windows.Size))
20067 {
20068 //SetNextItemOpen(true, ImGuiCond_Once);
20069 DebugNodeWindowsList(windows: &g.Windows, label: "By display order");
20070 DebugNodeWindowsList(windows: &g.WindowsFocusOrder, label: "By focus order (root windows)");
20071 if (TreeNode(label: "By submission order (begin stack)"))
20072 {
20073 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20074 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20075 temp_buffer.resize(new_size: 0);
20076 for (ImGuiWindow* window : g.Windows)
20077 if (window->LastFrameActive + 1 >= g.FrameCount)
20078 temp_buffer.push_back(v: window);
20079 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); } };
20080 ImQsort(base: temp_buffer.Data, count: (size_t)temp_buffer.Size, size_of_element: sizeof(ImGuiWindow*), compare_func: Func::WindowComparerByBeginOrder);
20081 DebugNodeWindowsListByBeginStackParent(windows: temp_buffer.Data, windows_size: temp_buffer.Size, NULL);
20082 TreePop();
20083 }
20084
20085 TreePop();
20086 }
20087
20088 // DrawLists
20089 int drawlist_count = 0;
20090 for (ImGuiViewportP* viewport : g.Viewports)
20091 drawlist_count += viewport->DrawDataP.CmdLists.Size;
20092 if (TreeNode(str_id: "DrawLists", fmt: "DrawLists (%d)", drawlist_count))
20093 {
20094 Checkbox(label: "Show ImDrawCmd mesh when hovering", v: &cfg->ShowDrawCmdMesh);
20095 Checkbox(label: "Show ImDrawCmd bounding boxes when hovering", v: &cfg->ShowDrawCmdBoundingBoxes);
20096 for (ImGuiViewportP* viewport : g.Viewports)
20097 {
20098 bool viewport_has_drawlist = false;
20099 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20100 {
20101 if (!viewport_has_drawlist)
20102 Text(fmt: "Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20103 viewport_has_drawlist = true;
20104 DebugNodeDrawList(NULL, viewport, draw_list, label: "DrawList");
20105 }
20106 }
20107 TreePop();
20108 }
20109
20110 // Viewports
20111 if (TreeNode(str_id: "Viewports", fmt: "Viewports (%d)", g.Viewports.Size))
20112 {
20113 cfg->HighlightMonitorIdx = -1;
20114 bool open = TreeNode(str_id: "Monitors", fmt: "Monitors (%d)", g.PlatformIO.Monitors.Size);
20115 SameLine();
20116 MetricsHelpMarker(desc: "Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20117 if (open)
20118 {
20119 for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20120 {
20121 const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20122 BulletText(fmt: "Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20123 i, mon.DpiScale * 100.0f,
20124 mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20125 mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20126 if (IsItemHovered())
20127 cfg->HighlightMonitorIdx = i;
20128 }
20129 TreePop();
20130 }
20131
20132 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
20133 if (TreeNode(label: "Windows Minimap"))
20134 {
20135 RenderViewportsThumbnails();
20136 TreePop();
20137 }
20138 cfg->HighlightViewportID = 0;
20139
20140 BulletText(fmt: "MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20141 if (TreeNode(label: "Inferred Z order (front-to-back)"))
20142 {
20143 static ImVector<ImGuiViewportP*> viewports;
20144 viewports.resize(new_size: g.Viewports.Size);
20145 memcpy(dest: viewports.Data, src: g.Viewports.Data, n: g.Viewports.size_in_bytes());
20146 if (viewports.Size > 1)
20147 ImQsort(base: viewports.Data, count: viewports.Size, size_of_element: sizeof(ImGuiViewport*), compare_func: ViewportComparerByLastFocusedStampCount);
20148 for (ImGuiViewportP* viewport : viewports)
20149 {
20150 BulletText(fmt: "Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20151 viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20152 (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20153 viewport->Window ? viewport->Window->Name : "N/A");
20154 if (IsItemHovered())
20155 cfg->HighlightViewportID = viewport->ID;
20156 }
20157 TreePop();
20158 }
20159
20160 for (ImGuiViewportP* viewport : g.Viewports)
20161 DebugNodeViewport(viewport);
20162 TreePop();
20163 }
20164
20165 // Details for Popups
20166 if (TreeNode(str_id: "Popups", fmt: "Popups (%d)", g.OpenPopupStack.Size))
20167 {
20168 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20169 {
20170 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20171 ImGuiWindow* window = popup_data.Window;
20172 BulletText(fmt: "PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20173 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20174 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20175 }
20176 TreePop();
20177 }
20178
20179 // Details for TabBars
20180 if (TreeNode(str_id: "TabBars", fmt: "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20181 {
20182 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20183 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20184 {
20185 PushID(ptr_id: tab_bar);
20186 DebugNodeTabBar(tab_bar, label: "TabBar");
20187 PopID();
20188 }
20189 TreePop();
20190 }
20191
20192 // Details for Tables
20193 if (TreeNode(str_id: "Tables", fmt: "Tables (%d)", g.Tables.GetAliveCount()))
20194 {
20195 for (int n = 0; n < g.Tables.GetMapSize(); n++)
20196 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20197 DebugNodeTable(table);
20198 TreePop();
20199 }
20200
20201 // Details for Fonts
20202 ImFontAtlas* atlas = g.IO.Fonts;
20203 if (TreeNode(str_id: "Fonts", fmt: "Fonts (%d)", atlas->Fonts.Size))
20204 {
20205 ShowFontAtlas(atlas);
20206 TreePop();
20207 }
20208
20209 // Details for InputText
20210 if (TreeNode(label: "InputText"))
20211 {
20212 DebugNodeInputTextState(state: &g.InputTextState);
20213 TreePop();
20214 }
20215
20216 // Details for TypingSelect
20217 if (TreeNode(str_id: "TypingSelect", fmt: "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20218 {
20219 DebugNodeTypingSelectState(state: &g.TypingSelectState);
20220 TreePop();
20221 }
20222
20223 // Details for Docking
20224#ifdef IMGUI_HAS_DOCK
20225 if (TreeNode(label: "Docking"))
20226 {
20227 static bool root_nodes_only = true;
20228 ImGuiDockContext* dc = &g.DockContext;
20229 Checkbox(label: "List root nodes", v: &root_nodes_only);
20230 Checkbox(label: "Ctrl shows window dock info", v: &cfg->ShowDockingNodes);
20231 if (SmallButton(label: "Clear nodes")) { DockContextClearNodes(ctx: &g, root_id: 0, clear_settings_refs: true); }
20232 SameLine();
20233 if (SmallButton(label: "Rebuild all")) { dc->WantFullRebuild = true; }
20234 for (int n = 0; n < dc->Nodes.Data.Size; n++)
20235 if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20236 if (!root_nodes_only || node->IsRootNode())
20237 DebugNodeDockNode(node, label: "Node");
20238 TreePop();
20239 }
20240#endif // #ifdef IMGUI_HAS_DOCK
20241
20242 // Settings
20243 if (TreeNode(label: "Settings"))
20244 {
20245 if (SmallButton(label: "Clear"))
20246 ClearIniSettings();
20247 SameLine();
20248 if (SmallButton(label: "Save to memory"))
20249 SaveIniSettingsToMemory();
20250 SameLine();
20251 if (SmallButton(label: "Save to disk"))
20252 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
20253 SameLine();
20254 if (g.IO.IniFilename)
20255 Text(fmt: "\"%s\"", g.IO.IniFilename);
20256 else
20257 TextUnformatted(text: "<NULL>");
20258 Checkbox(label: "io.ConfigDebugIniSettings", v: &io.ConfigDebugIniSettings);
20259 Text(fmt: "SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20260 if (TreeNode(str_id: "SettingsHandlers", fmt: "Settings handlers: (%d)", g.SettingsHandlers.Size))
20261 {
20262 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20263 BulletText(fmt: "\"%s\"", handler.TypeName);
20264 TreePop();
20265 }
20266 if (TreeNode(str_id: "SettingsWindows", fmt: "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20267 {
20268 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
20269 DebugNodeWindowSettings(settings);
20270 TreePop();
20271 }
20272
20273 if (TreeNode(str_id: "SettingsTables", fmt: "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20274 {
20275 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(p: settings))
20276 DebugNodeTableSettings(settings);
20277 TreePop();
20278 }
20279
20280#ifdef IMGUI_HAS_DOCK
20281 if (TreeNode(str_id: "SettingsDocking", fmt: "Settings packed data: Docking"))
20282 {
20283 ImGuiDockContext* dc = &g.DockContext;
20284 Text(fmt: "In SettingsWindows:");
20285 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
20286 if (settings->DockId != 0)
20287 BulletText(fmt: "Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20288 Text(fmt: "In SettingsNodes:");
20289 for (int n = 0; n < dc->NodesSettings.Size; n++)
20290 {
20291 ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20292 const char* selected_tab_name = NULL;
20293 if (settings->SelectedTabId)
20294 {
20295 if (ImGuiWindow* window = FindWindowByID(id: settings->SelectedTabId))
20296 selected_tab_name = window->Name;
20297 else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(id: settings->SelectedTabId))
20298 selected_tab_name = window_settings->GetName();
20299 }
20300 BulletText(fmt: "Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20301 }
20302 TreePop();
20303 }
20304#endif // #ifdef IMGUI_HAS_DOCK
20305
20306 if (TreeNode(str_id: "SettingsIniData", fmt: "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20307 {
20308 InputTextMultiline(label: "##Ini", buf: (char*)(void*)g.SettingsIniData.c_str(), buf_size: g.SettingsIniData.Buf.Size, size: ImVec2(-FLT_MIN, GetTextLineHeight() * 20), flags: ImGuiInputTextFlags_ReadOnly);
20309 TreePop();
20310 }
20311 TreePop();
20312 }
20313
20314 // Settings
20315 if (TreeNode(label: "Memory allocations"))
20316 {
20317 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20318 Text(fmt: "%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20319 if (SmallButton(label: "GC now")) { g.GcCompactAll = true; }
20320 Text(fmt: "Recent frames with allocations:");
20321 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20322 for (int n = buf_size - 1; n >= 0; n--)
20323 {
20324 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20325 BulletText(fmt: "Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20326 }
20327 TreePop();
20328 }
20329
20330 if (TreeNode(label: "Inputs"))
20331 {
20332 Text(fmt: "KEYBOARD/GAMEPAD/MOUSE KEYS");
20333 {
20334 // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20335 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20336 Indent();
20337#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20338 struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20339#else
20340 struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20341 //Text("Legacy raw:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20342#endif
20343 Text(fmt: "Keys down:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue; SameLine(); Text(fmt: IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text(fmt: "(%.02f)", GetKeyData(key)->DownDuration); }
20344 Text(fmt: "Keys pressed:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue; SameLine(); Text(fmt: IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20345 Text(fmt: "Keys released:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(fmt: IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20346 Text(fmt: "Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20347 Text(fmt: "Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text(fmt: "\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20348 DebugRenderKeyboardPreview(draw_list: GetWindowDrawList());
20349 Unindent();
20350 }
20351
20352 Text(fmt: "MOUSE STATE");
20353 {
20354 Indent();
20355 if (IsMousePosValid())
20356 Text(fmt: "Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20357 else
20358 Text(fmt: "Mouse pos: <INVALID>");
20359 Text(fmt: "Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20360 int count = IM_ARRAYSIZE(io.MouseDown);
20361 Text(fmt: "Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(button: i)) { SameLine(); Text(fmt: "b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20362 Text(fmt: "Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(button: i)) { SameLine(); Text(fmt: "b%d (%d)", i, io.MouseClickedCount[i]); }
20363 Text(fmt: "Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(button: i)) { SameLine(); Text(fmt: "b%d", i); }
20364 Text(fmt: "Mouse wheel: %.1f", io.MouseWheel);
20365 Text(fmt: "MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20366 Text(fmt: "Mouse source: %s", GetMouseSourceName(source: io.MouseSource));
20367 Text(fmt: "Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20368 Unindent();
20369 }
20370
20371 Text(fmt: "MOUSE WHEELING");
20372 {
20373 Indent();
20374 Text(fmt: "WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20375 Text(fmt: "WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20376 Text(fmt: "WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20377 Unindent();
20378 }
20379
20380 Text(fmt: "KEY OWNERS");
20381 {
20382 Indent();
20383 if (BeginChild(str_id: "##owners", size_arg: ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), child_flags: ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, window_flags: ImGuiWindowFlags_NoSavedSettings))
20384 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20385 {
20386 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
20387 if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
20388 continue;
20389 Text(fmt: "%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20390 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20391 DebugLocateItemOnHover(target_id: owner_data->OwnerCurr);
20392 }
20393 EndChild();
20394 Unindent();
20395 }
20396 Text(fmt: "SHORTCUT ROUTING");
20397 SameLine();
20398 MetricsHelpMarker(desc: "Declared shortcut routes automatically set key owner when mods matches.");
20399 {
20400 Indent();
20401 if (BeginChild(str_id: "##routes", size_arg: ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), child_flags: ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, window_flags: ImGuiWindowFlags_NoSavedSettings))
20402 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20403 {
20404 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20405 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20406 {
20407 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20408 ImGuiKeyChord key_chord = key | routing_data->Mods;
20409 Text(fmt: "%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20410 DebugLocateItemOnHover(target_id: routing_data->RoutingCurr);
20411 if (g.IO.ConfigDebugIsDebuggerPresent)
20412 {
20413 SameLine();
20414 if (DebugBreakButton(label: "**DebugBreak**", description_of_location: "in SetShortcutRouting() for this KeyChord"))
20415 g.DebugBreakInShortcutRouting = key_chord;
20416 }
20417 idx = routing_data->NextEntryIndex;
20418 }
20419 }
20420 EndChild();
20421 Text(fmt: "(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20422 Unindent();
20423 }
20424 TreePop();
20425 }
20426
20427 if (TreeNode(label: "Internal state"))
20428 {
20429 Text(fmt: "WINDOWING");
20430 Indent();
20431 Text(fmt: "HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20432 Text(fmt: "HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20433 Text(fmt: "HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20434 Text(fmt: "HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20435 Text(fmt: "MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20436 Text(fmt: "MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20437 Unindent();
20438
20439 Text(fmt: "ITEMS");
20440 Indent();
20441 Text(fmt: "ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(source: g.ActiveIdSource));
20442 DebugLocateItemOnHover(target_id: g.ActiveId);
20443 Text(fmt: "ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20444 Text(fmt: "ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20445 Text(fmt: "HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20446 Text(fmt: "HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20447 Text(fmt: "DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20448 DebugLocateItemOnHover(target_id: g.DragDropPayload.SourceId);
20449 Unindent();
20450
20451 Text(fmt: "NAV,FOCUS");
20452 Indent();
20453 Text(fmt: "NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20454 Text(fmt: "NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20455 DebugLocateItemOnHover(target_id: g.NavId);
20456 Text(fmt: "NavInputSource: %s", GetInputSourceName(source: g.NavInputSource));
20457 Text(fmt: "NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20458 Text(fmt: "NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20459 Text(fmt: "NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20460 Text(fmt: "NavActivateFlags: %04X", g.NavActivateFlags);
20461 Text(fmt: "NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20462 Text(fmt: "NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20463 Text(fmt: "NavFocusRoute[] = ");
20464 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20465 {
20466 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20467 SameLine(offset_from_start_x: 0.0f, spacing_w: 0.0f);
20468 Text(fmt: "0x%08X/", focus_scope.ID);
20469 SetItemTooltip("In window \"%s\"", FindWindowByID(id: focus_scope.WindowID)->Name);
20470 }
20471 Text(fmt: "NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20472 Unindent();
20473
20474 TreePop();
20475 }
20476
20477 // Overlay: Display windows Rectangles and Begin Order
20478 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20479 {
20480 for (ImGuiWindow* window : g.Windows)
20481 {
20482 if (!window->WasActive)
20483 continue;
20484 ImDrawList* draw_list = GetForegroundDrawList(window);
20485 if (cfg->ShowWindowsRects)
20486 {
20487 ImRect r = Funcs::GetWindowRect(window, rect_type: cfg->ShowWindowsRectsType);
20488 draw_list->AddRect(p_min: r.Min, p_max: r.Max, IM_COL32(255, 0, 128, 255));
20489 }
20490 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20491 {
20492 char buf[32];
20493 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "%d", window->BeginOrderWithinContext);
20494 float font_size = GetFontSize();
20495 draw_list->AddRectFilled(p_min: window->Pos, p_max: window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20496 draw_list->AddText(pos: window->Pos, IM_COL32(255, 255, 255, 255), text_begin: buf);
20497 }
20498 }
20499 }
20500
20501 // Overlay: Display Tables Rectangles
20502 if (cfg->ShowTablesRects)
20503 {
20504 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20505 {
20506 ImGuiTable* table = g.Tables.TryGetMapData(n: table_n);
20507 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20508 continue;
20509 ImDrawList* draw_list = GetForegroundDrawList(window: table->OuterWindow);
20510 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20511 {
20512 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20513 {
20514 ImRect r = Funcs::GetTableRect(table, rect_type: cfg->ShowTablesRectsType, n: column_n);
20515 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20516 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20517 draw_list->AddRect(p_min: r.Min, p_max: r.Max, col, rounding: 0.0f, flags: 0, thickness);
20518 }
20519 }
20520 else
20521 {
20522 ImRect r = Funcs::GetTableRect(table, rect_type: cfg->ShowTablesRectsType, n: -1);
20523 draw_list->AddRect(p_min: r.Min, p_max: r.Max, IM_COL32(255, 0, 128, 255));
20524 }
20525 }
20526 }
20527
20528#ifdef IMGUI_HAS_DOCK
20529 // Overlay: Display Docking info
20530 if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20531 {
20532 char buf[64] = "";
20533 char* p = buf;
20534 ImGuiDockNode* node = g.DebugHoveredDockNode;
20535 ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(window: node->HostWindow) : GetForegroundDrawList(viewport: GetMainViewport());
20536 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20537 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "WindowClass: %08X\n", node->WindowClass.ClassId);
20538 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20539 p += ImFormatString(buf: p, buf_size: buf + IM_ARRAYSIZE(buf) - p, fmt: "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20540 int depth = DockNodeGetDepth(node);
20541 overlay_draw_list->AddRect(p_min: node->Pos + ImVec2(3, 3) * (float)depth, p_max: node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20542 ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20543 overlay_draw_list->AddRectFilled(p_min: pos - ImVec2(1, 1), p_max: pos + CalcTextSize(text: buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20544 overlay_draw_list->AddText(NULL, font_size: 0.0f, pos, IM_COL32(255, 255, 255, 255), text_begin: buf);
20545 }
20546#endif // #ifdef IMGUI_HAS_DOCK
20547
20548 End();
20549}
20550
20551void ImGui::DebugBreakClearData()
20552{
20553 // Those fields are scattered in their respective subsystem to stay in hot-data locations
20554 ImGuiContext& g = *GImGui;
20555 g.DebugBreakInWindow = 0;
20556 g.DebugBreakInTable = 0;
20557 g.DebugBreakInShortcutRouting = ImGuiKey_None;
20558}
20559
20560void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
20561{
20562 if (!BeginItemTooltip())
20563 return;
20564 Text(fmt: "To call IM_DEBUG_BREAK() %s:", description_of_location);
20565 Separator();
20566 TextUnformatted(text: keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
20567 Separator();
20568 TextUnformatted(text: "Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
20569 EndTooltip();
20570}
20571
20572// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
20573// In order to reduce interferences with the contents we are trying to debug into.
20574bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
20575{
20576 ImGuiWindow* window = GetCurrentWindow();
20577 if (window->SkipItems)
20578 return false;
20579
20580 ImGuiContext& g = *GImGui;
20581 const ImGuiID id = window->GetID(str: label);
20582 const ImVec2 label_size = CalcTextSize(text: label, NULL, hide_text_after_double_hash: true);
20583 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
20584 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
20585
20586 const ImRect bb(pos, pos + size);
20587 ItemSize(size, text_baseline_y: 0.0f);
20588 if (!ItemAdd(bb, id))
20589 return false;
20590
20591 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
20592 bool hovered = ItemHoverable(bb, id, item_flags: g.CurrentItemFlags);
20593 bool pressed = hovered && (IsKeyChordPressed(key_chord: g.DebugBreakKeyChord) || IsMouseClicked(button: 0) || g.NavActivateId == id);
20594 DebugBreakButtonTooltip(keyboard_only: false, description_of_location);
20595
20596 ImVec4 col4f = GetStyleColorVec4(idx: hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
20597 ImVec4 hsv;
20598 ColorConvertRGBtoHSV(r: col4f.x, g: col4f.y, b: col4f.z, out_h&: hsv.x, out_s&: hsv.y, out_v&: hsv.z);
20599 ColorConvertHSVtoRGB(h: hsv.x + 0.20f, s: hsv.y, v: hsv.z, out_r&: col4f.x, out_g&: col4f.y, out_b&: col4f.z);
20600
20601 RenderNavHighlight(bb, id);
20602 RenderFrame(p_min: bb.Min, p_max: bb.Max, fill_col: GetColorU32(col: col4f), border: true, rounding: g.Style.FrameRounding);
20603 RenderTextClipped(pos_min: bb.Min, pos_max: bb.Max, text: label, NULL, text_size_if_known: &label_size, align: g.Style.ButtonTextAlign, clip_rect: &bb);
20604
20605 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
20606 return pressed;
20607}
20608
20609// [DEBUG] Display contents of Columns
20610void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20611{
20612 if (!TreeNode(ptr_id: (void*)(uintptr_t)columns->ID, fmt: "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20613 return;
20614 BulletText(fmt: "Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20615 for (ImGuiOldColumnData& column : columns->Columns)
20616 BulletText(fmt: "Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(it: &column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, offset_norm: column.OffsetNorm));
20617 TreePop();
20618}
20619
20620static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20621{
20622 using namespace ImGui;
20623 PushID(str_id: label);
20624 PushStyleVar(idx: ImGuiStyleVar_FramePadding, val: ImVec2(0.0f, 0.0f));
20625 Text(fmt: "%s:", label);
20626 if (!enabled)
20627 BeginDisabled();
20628 CheckboxFlags(label: "NoResize", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoResize);
20629 CheckboxFlags(label: "NoResizeX", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoResizeX);
20630 CheckboxFlags(label: "NoResizeY",flags: p_flags, flags_value: ImGuiDockNodeFlags_NoResizeY);
20631 CheckboxFlags(label: "NoTabBar", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoTabBar);
20632 CheckboxFlags(label: "HiddenTabBar", flags: p_flags, flags_value: ImGuiDockNodeFlags_HiddenTabBar);
20633 CheckboxFlags(label: "NoWindowMenuButton", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoWindowMenuButton);
20634 CheckboxFlags(label: "NoCloseButton", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoCloseButton);
20635 CheckboxFlags(label: "DockedWindowsInFocusRoute", flags: p_flags, flags_value: ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
20636 CheckboxFlags(label: "NoDocking", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDocking); // Multiple flags
20637 CheckboxFlags(label: "NoDockingSplit", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingSplit);
20638 CheckboxFlags(label: "NoDockingSplitOther", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingSplitOther);
20639 CheckboxFlags(label: "NoDockingOver", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingOverMe);
20640 CheckboxFlags(label: "NoDockingOverOther", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingOverOther);
20641 CheckboxFlags(label: "NoDockingOverEmpty", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoDockingOverEmpty);
20642 CheckboxFlags(label: "NoUndocking", flags: p_flags, flags_value: ImGuiDockNodeFlags_NoUndocking);
20643 if (!enabled)
20644 EndDisabled();
20645 PopStyleVar();
20646 PopID();
20647}
20648
20649// [DEBUG] Display contents of ImDockNode
20650void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20651{
20652 ImGuiContext& g = *GImGui;
20653 const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20654 const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted
20655 if (!is_alive) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
20656 bool open;
20657 ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20658 if (node->Windows.Size > 0)
20659 open = TreeNodeEx(ptr_id: (void*)(intptr_t)node->ID, flags: tree_node_flags, fmt: "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20660 else
20661 open = TreeNodeEx(ptr_id: (void*)(intptr_t)node->ID, flags: tree_node_flags, fmt: "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20662 if (!is_alive) { PopStyleColor(); }
20663 if (is_active && IsItemHovered())
20664 if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20665 GetForegroundDrawList(window)->AddRect(p_min: node->Pos, p_max: node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20666 if (open)
20667 {
20668 IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20669 IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20670 BulletText(fmt: "Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20671 node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20672 DebugNodeWindow(window: node->HostWindow, label: "HostWindow");
20673 DebugNodeWindow(window: node->VisibleWindow, label: "VisibleWindow");
20674 BulletText(fmt: "SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20675 BulletText(fmt: "Misc:%s%s%s%s%s%s%s",
20676 node->IsDockSpace() ? " IsDockSpace" : "",
20677 node->IsCentralNode() ? " IsCentralNode" : "",
20678 is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20679 node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20680 node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20681 if (TreeNode(str_id: "flags", fmt: "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20682 {
20683 if (BeginTable(str_id: "flags", column: 4))
20684 {
20685 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->MergedFlags, label: "MergedFlags", enabled: false);
20686 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->LocalFlags, label: "LocalFlags", enabled: true);
20687 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->LocalFlagsInWindows, label: "LocalFlagsInWindows", enabled: false);
20688 TableNextColumn(); DebugNodeDockNodeFlags(p_flags: &node->SharedFlags, label: "SharedFlags", enabled: true);
20689 EndTable();
20690 }
20691 TreePop();
20692 }
20693 if (node->ParentNode)
20694 DebugNodeDockNode(node: node->ParentNode, label: "ParentNode");
20695 if (node->ChildNodes[0])
20696 DebugNodeDockNode(node: node->ChildNodes[0], label: "Child[0]");
20697 if (node->ChildNodes[1])
20698 DebugNodeDockNode(node: node->ChildNodes[1], label: "Child[1]");
20699 if (node->TabBar)
20700 DebugNodeTabBar(tab_bar: node->TabBar, label: "TabBar");
20701 DebugNodeWindowsList(windows: &node->Windows, label: "Windows");
20702
20703 TreePop();
20704 }
20705}
20706
20707static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
20708{
20709 union { void* ptr; int integer; } tex_id_opaque;
20710 memcpy(dest: &tex_id_opaque, src: &tex_id, n: ImMin(lhs: sizeof(void*), rhs: sizeof(tex_id)));
20711 if (sizeof(tex_id) >= sizeof(void*))
20712 ImFormatString(buf, buf_size, fmt: "0x%p", tex_id_opaque.ptr);
20713 else
20714 ImFormatString(buf, buf_size, fmt: "0x%04X", tex_id_opaque.integer);
20715}
20716
20717// [DEBUG] Display contents of ImDrawList
20718// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20719void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20720{
20721 ImGuiContext& g = *GImGui;
20722 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20723 int cmd_count = draw_list->CmdBuffer.Size;
20724 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20725 cmd_count--;
20726 bool node_open = TreeNode(ptr_id: draw_list, fmt: "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20727 if (draw_list == GetWindowDrawList())
20728 {
20729 SameLine();
20730 TextColored(col: ImVec4(1.0f, 0.4f, 0.4f, 1.0f), fmt: "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20731 if (node_open)
20732 TreePop();
20733 return;
20734 }
20735
20736 ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20737 if (window && IsItemHovered() && fg_draw_list)
20738 fg_draw_list->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20739 if (!node_open)
20740 return;
20741
20742 if (window && !window->WasActive)
20743 TextDisabled(fmt: "Warning: owning Window is inactive. This DrawList is not being rendered!");
20744
20745 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20746 {
20747 if (pcmd->UserCallback)
20748 {
20749 BulletText(fmt: "Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20750 continue;
20751 }
20752
20753 char texid_desc[20];
20754 FormatTextureIDForDebugDisplay(buf: texid_desc, IM_ARRAYSIZE(texid_desc), tex_id: pcmd->TextureId);
20755 char buf[300];
20756 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20757 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20758 bool pcmd_node_open = TreeNode(ptr_id: (void*)(pcmd - draw_list->CmdBuffer.begin()), fmt: "%s", buf);
20759 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20760 DebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list: fg_draw_list, draw_list, draw_cmd: pcmd, show_mesh: cfg->ShowDrawCmdMesh, show_aabb: cfg->ShowDrawCmdBoundingBoxes);
20761 if (!pcmd_node_open)
20762 continue;
20763
20764 // Calculate approximate coverage area (touched pixel count)
20765 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20766 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20767 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20768 float total_area = 0.0f;
20769 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20770 {
20771 ImVec2 triangle[3];
20772 for (int n = 0; n < 3; n++, idx_n++)
20773 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20774 total_area += ImTriangleArea(a: triangle[0], b: triangle[1], c: triangle[2]);
20775 }
20776
20777 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20778 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20779 Selectable(label: buf);
20780 if (IsItemHovered() && fg_draw_list)
20781 DebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list: fg_draw_list, draw_list, draw_cmd: pcmd, show_mesh: true, show_aabb: false);
20782
20783 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20784 ImGuiListClipper clipper;
20785 clipper.Begin(items_count: pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20786 while (clipper.Step())
20787 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20788 {
20789 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20790 ImVec2 triangle[3];
20791 for (int n = 0; n < 3; n++, idx_i++)
20792 {
20793 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20794 triangle[n] = v.pos;
20795 buf_p += ImFormatString(buf: buf_p, buf_size: buf_end - buf_p, fmt: "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20796 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20797 }
20798
20799 Selectable(label: buf, selected: false);
20800 if (fg_draw_list && IsItemHovered())
20801 {
20802 ImDrawListFlags backup_flags = fg_draw_list->Flags;
20803 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20804 fg_draw_list->AddPolyline(points: triangle, num_points: 3, IM_COL32(255, 255, 0, 255), flags: ImDrawFlags_Closed, thickness: 1.0f);
20805 fg_draw_list->Flags = backup_flags;
20806 }
20807 }
20808 TreePop();
20809 }
20810 TreePop();
20811}
20812
20813// [DEBUG] Display mesh/aabb of a ImDrawCmd
20814void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20815{
20816 IM_ASSERT(show_mesh || show_aabb);
20817
20818 // Draw wire-frame version of all triangles
20819 ImRect clip_rect = draw_cmd->ClipRect;
20820 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20821 ImDrawListFlags backup_flags = out_draw_list->Flags;
20822 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20823 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20824 {
20825 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
20826 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20827
20828 ImVec2 triangle[3];
20829 for (int n = 0; n < 3; n++, idx_n++)
20830 vtxs_rect.Add(p: (triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20831 if (show_mesh)
20832 out_draw_list->AddPolyline(points: triangle, num_points: 3, IM_COL32(255, 255, 0, 255), flags: ImDrawFlags_Closed, thickness: 1.0f); // In yellow: mesh triangles
20833 }
20834 // Draw bounding boxes
20835 if (show_aabb)
20836 {
20837 out_draw_list->AddRect(p_min: ImTrunc(v: clip_rect.Min), p_max: ImTrunc(v: clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20838 out_draw_list->AddRect(p_min: ImTrunc(v: vtxs_rect.Min), p_max: ImTrunc(v: vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20839 }
20840 out_draw_list->Flags = backup_flags;
20841}
20842
20843// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20844void ImGui::DebugNodeFont(ImFont* font)
20845{
20846 bool opened = TreeNode(ptr_id: font, fmt: "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20847 font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20848 SameLine();
20849 if (SmallButton(label: "Set as default"))
20850 GetIO().FontDefault = font;
20851 if (!opened)
20852 return;
20853
20854 // Display preview text
20855 PushFont(font);
20856 Text(fmt: "The quick brown fox jumps over the lazy dog");
20857 PopFont();
20858
20859 // Display details
20860 SetNextItemWidth(GetFontSize() * 8);
20861 DragFloat(label: "Font scale", v: &font->Scale, v_speed: 0.005f, v_min: 0.3f, v_max: 2.0f, format: "%.1f");
20862 SameLine(); MetricsHelpMarker(
20863 desc: "Note that the default embedded font is NOT meant to be scaled.\n\n"
20864 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20865 "You may oversample them to get some flexibility with scaling. "
20866 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20867 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20868 Text(fmt: "Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20869 char c_str[5];
20870 Text(fmt: "Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(out_buf: c_str, c: font->FallbackChar), font->FallbackChar);
20871 Text(fmt: "Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(out_buf: c_str, c: font->EllipsisChar), font->EllipsisChar);
20872 const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20873 Text(fmt: "Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20874 for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20875 if (font->ConfigData)
20876 if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20877 BulletText(fmt: "Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20878 config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20879
20880 // Display all glyphs of the fonts in separate pages of 256 characters
20881 if (TreeNode(str_id: "Glyphs", fmt: "Glyphs (%d)", font->Glyphs.Size))
20882 {
20883 ImDrawList* draw_list = GetWindowDrawList();
20884 const ImU32 glyph_col = GetColorU32(idx: ImGuiCol_Text);
20885 const float cell_size = font->FontSize * 1;
20886 const float cell_spacing = GetStyle().ItemSpacing.y;
20887 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20888 {
20889 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20890 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20891 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20892 if (!(base & 4095) && font->IsGlyphRangeUnused(c_begin: base, c_last: base + 4095))
20893 {
20894 base += 4096 - 256;
20895 continue;
20896 }
20897
20898 int count = 0;
20899 for (unsigned int n = 0; n < 256; n++)
20900 if (font->FindGlyphNoFallback(c: (ImWchar)(base + n)))
20901 count++;
20902 if (count <= 0)
20903 continue;
20904 if (!TreeNode(ptr_id: (void*)(intptr_t)base, fmt: "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20905 continue;
20906
20907 // Draw a 16x16 grid of glyphs
20908 ImVec2 base_pos = GetCursorScreenPos();
20909 for (unsigned int n = 0; n < 256; n++)
20910 {
20911 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20912 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20913 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20914 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20915 const ImFontGlyph* glyph = font->FindGlyphNoFallback(c: (ImWchar)(base + n));
20916 draw_list->AddRect(p_min: cell_p1, p_max: cell_p2, col: glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20917 if (!glyph)
20918 continue;
20919 font->RenderChar(draw_list, size: cell_size, pos: cell_p1, col: glyph_col, c: (ImWchar)(base + n));
20920 if (IsMouseHoveringRect(r_min: cell_p1, r_max: cell_p2) && BeginTooltip())
20921 {
20922 DebugNodeFontGlyph(font, glyph);
20923 EndTooltip();
20924 }
20925 }
20926 Dummy(size: ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20927 TreePop();
20928 }
20929 TreePop();
20930 }
20931 TreePop();
20932}
20933
20934void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20935{
20936 Text(fmt: "Codepoint: U+%04X", glyph->Codepoint);
20937 Separator();
20938 Text(fmt: "Visible: %d", glyph->Visible);
20939 Text(fmt: "AdvanceX: %.1f", glyph->AdvanceX);
20940 Text(fmt: "Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20941 Text(fmt: "UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20942}
20943
20944// [DEBUG] Display contents of ImGuiStorage
20945void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20946{
20947 if (!TreeNode(str_id: label, fmt: "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20948 return;
20949 for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20950 BulletText(fmt: "Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20951 TreePop();
20952}
20953
20954// [DEBUG] Display contents of ImGuiTabBar
20955void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20956{
20957 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20958 char buf[256];
20959 char* p = buf;
20960 const char* buf_end = buf + IM_ARRAYSIZE(buf);
20961 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20962 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20963 for (int tab_n = 0; tab_n < ImMin(lhs: tab_bar->Tabs.Size, rhs: 3); tab_n++)
20964 {
20965 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20966 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20967 }
20968 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20969 if (!is_active) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
20970 bool open = TreeNode(str_id: label, fmt: "%s", buf);
20971 if (!is_active) { PopStyleColor(); }
20972 if (is_active && IsItemHovered())
20973 {
20974 ImDrawList* draw_list = GetForegroundDrawList();
20975 draw_list->AddRect(p_min: tab_bar->BarRect.Min, p_max: tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20976 draw_list->AddLine(p1: ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), p2: ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20977 draw_list->AddLine(p1: ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), p2: ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20978 }
20979 if (open)
20980 {
20981 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20982 {
20983 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20984 PushID(ptr_id: tab);
20985 if (SmallButton(label: "<")) { TabBarQueueReorder(tab_bar, tab, offset: -1); } SameLine(offset_from_start_x: 0, spacing_w: 2);
20986 if (SmallButton(label: ">")) { TabBarQueueReorder(tab_bar, tab, offset: +1); } SameLine();
20987 Text(fmt: "%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20988 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20989 PopID();
20990 }
20991 TreePop();
20992 }
20993}
20994
20995void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20996{
20997 ImGuiContext& g = *GImGui;
20998 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
20999 bool open = TreeNode(ptr_id: (void*)(intptr_t)viewport->ID, fmt: "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21000 if (IsItemHovered())
21001 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21002 if (open)
21003 {
21004 ImGuiWindowFlags flags = viewport->Flags;
21005 BulletText(fmt: "Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21006 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21007 viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21008 viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21009 if (viewport->Idx > 0) { SameLine(); if (SmallButton(label: "Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21010 BulletText(fmt: "Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21011 //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21012 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21013 (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21014 (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21015 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21016 (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21017 (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21018 (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21019 (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21020 (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21021 (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21022 (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21023 (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21024 (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21025 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21026 DebugNodeDrawList(NULL, viewport, draw_list, label: "DrawList");
21027 TreePop();
21028 }
21029}
21030
21031void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21032{
21033 if (window == NULL)
21034 {
21035 BulletText(fmt: "%s: NULL", label);
21036 return;
21037 }
21038
21039 ImGuiContext& g = *GImGui;
21040 const bool is_active = window->WasActive;
21041 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21042 if (!is_active) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
21043 const bool open = TreeNodeEx(str_id: label, flags: tree_node_flags, fmt: "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21044 if (!is_active) { PopStyleColor(); }
21045 if (IsItemHovered() && is_active)
21046 GetForegroundDrawList(window)->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21047 if (!open)
21048 return;
21049
21050 if (window->MemoryCompacted)
21051 TextDisabled(fmt: "Note: some memory buffers have been compacted/freed.");
21052
21053 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton(label: "**DebugBreak**", description_of_location: "in Begin()"))
21054 g.DebugBreakInWindow = window->ID;
21055
21056 ImGuiWindowFlags flags = window->Flags;
21057 DebugNodeDrawList(window, viewport: window->Viewport, draw_list: window->DrawList, label: "DrawList");
21058 BulletText(fmt: "Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21059 BulletText(fmt: "Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21060 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21061 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21062 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21063 BulletText(fmt: "WindowClassId: 0x%08X", window->WindowClass.ClassId);
21064 BulletText(fmt: "Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21065 BulletText(fmt: "Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21066 BulletText(fmt: "Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21067 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21068 {
21069 ImRect r = window->NavRectRel[layer];
21070 if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21071 BulletText(fmt: "NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21072 else
21073 BulletText(fmt: "NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21074 DebugLocateItemOnHover(target_id: window->NavLastIds[layer]);
21075 }
21076 const ImVec2* pr = window->NavPreferredScoringPosRel;
21077 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21078 BulletText(fmt: "NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21079 BulletText(fmt: "NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21080
21081 BulletText(fmt: "Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21082 BulletText(fmt: "ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21083 BulletText(fmt: "DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21084 if (window->DockNode || window->DockNodeAsHost)
21085 DebugNodeDockNode(node: window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, label: window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21086
21087 if (window->RootWindow != window) { DebugNodeWindow(window: window->RootWindow, label: "RootWindow"); }
21088 if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window: window->RootWindowDockTree, label: "RootWindowDockTree"); }
21089 if (window->ParentWindow != NULL) { DebugNodeWindow(window: window->ParentWindow, label: "ParentWindow"); }
21090 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window: window->ParentWindowForFocusRoute, label: "ParentWindowForFocusRoute"); }
21091 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(windows: &window->DC.ChildWindows, label: "ChildWindows"); }
21092 if (window->ColumnsStorage.Size > 0 && TreeNode(str_id: "Columns", fmt: "Columns sets (%d)", window->ColumnsStorage.Size))
21093 {
21094 for (ImGuiOldColumns& columns : window->ColumnsStorage)
21095 DebugNodeColumns(columns: &columns);
21096 TreePop();
21097 }
21098 DebugNodeStorage(storage: &window->StateStorage, label: "Storage");
21099 TreePop();
21100}
21101
21102void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21103{
21104 if (settings->WantDelete)
21105 BeginDisabled();
21106 Text(fmt: "0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21107 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21108 if (settings->WantDelete)
21109 EndDisabled();
21110}
21111
21112void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21113{
21114 if (!TreeNode(str_id: label, fmt: "%s (%d)", label, windows->Size))
21115 return;
21116 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21117 {
21118 PushID(ptr_id: (*windows)[i]);
21119 DebugNodeWindow(window: (*windows)[i], label: "Window");
21120 PopID();
21121 }
21122 TreePop();
21123}
21124
21125// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21126void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21127{
21128 for (int i = 0; i < windows_size; i++)
21129 {
21130 ImGuiWindow* window = windows[i];
21131 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21132 continue;
21133 char buf[20];
21134 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "[%04d] Window", window->BeginOrderWithinContext);
21135 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21136 DebugNodeWindow(window, label: buf);
21137 Indent();
21138 DebugNodeWindowsListByBeginStackParent(windows: windows + i + 1, windows_size: windows_size - i - 1, parent_in_begin_stack: window);
21139 Unindent();
21140 }
21141}
21142
21143//-----------------------------------------------------------------------------
21144// [SECTION] DEBUG LOG WINDOW
21145//-----------------------------------------------------------------------------
21146
21147void ImGui::DebugLog(const char* fmt, ...)
21148{
21149 va_list args;
21150 va_start(args, fmt);
21151 DebugLogV(fmt, args);
21152 va_end(args);
21153}
21154
21155void ImGui::DebugLogV(const char* fmt, va_list args)
21156{
21157 ImGuiContext& g = *GImGui;
21158 const int old_size = g.DebugLogBuf.size();
21159 g.DebugLogBuf.appendf(fmt: "[%05d] ", g.FrameCount);
21160 g.DebugLogBuf.appendfv(fmt, args);
21161 g.DebugLogIndex.append(base: g.DebugLogBuf.c_str(), old_size, new_size: g.DebugLogBuf.size());
21162 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21163 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21164#ifdef IMGUI_ENABLE_TEST_ENGINE
21165 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21166 IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
21167#endif
21168}
21169
21170// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21171static void SameLineOrWrap(const ImVec2& size)
21172{
21173 ImGuiContext& g = *GImGui;
21174 ImGuiWindow* window = g.CurrentWindow;
21175 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21176 if (window->ClipRect.Contains(r: ImRect(pos, pos + size)))
21177 ImGui::SameLine();
21178}
21179
21180static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21181{
21182 ImGuiContext& g = *GImGui;
21183 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(text: name).x, ImGui::GetFrameHeight());
21184 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21185 if (ImGui::CheckboxFlags(label: name, flags: &g.DebugLogFlags, flags_value: flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21186 {
21187 g.DebugLogAutoDisableFrames = 2;
21188 g.DebugLogAutoDisableFlags |= flags;
21189 }
21190 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21191}
21192
21193void ImGui::ShowDebugLogWindow(bool* p_open)
21194{
21195 ImGuiContext& g = *GImGui;
21196 if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21197 SetNextWindowSize(size: ImVec2(0.0f, GetFontSize() * 12.0f), cond: ImGuiCond_FirstUseEver);
21198 if (!Begin(name: "Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21199 {
21200 End();
21201 return;
21202 }
21203
21204 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21205 CheckboxFlags(label: "All", flags: &g.DebugLogFlags, flags_value: all_enable_flags);
21206 SetItemTooltip("(except InputRouting which is spammy)");
21207
21208 ShowDebugLogFlag(name: "ActiveId", flags: ImGuiDebugLogFlags_EventActiveId);
21209 ShowDebugLogFlag(name: "Clipper", flags: ImGuiDebugLogFlags_EventClipper);
21210 ShowDebugLogFlag(name: "Docking", flags: ImGuiDebugLogFlags_EventDocking);
21211 ShowDebugLogFlag(name: "Focus", flags: ImGuiDebugLogFlags_EventFocus);
21212 ShowDebugLogFlag(name: "IO", flags: ImGuiDebugLogFlags_EventIO);
21213 ShowDebugLogFlag(name: "Nav", flags: ImGuiDebugLogFlags_EventNav);
21214 ShowDebugLogFlag(name: "Popup", flags: ImGuiDebugLogFlags_EventPopup);
21215 //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21216 ShowDebugLogFlag(name: "Viewport", flags: ImGuiDebugLogFlags_EventViewport);
21217 ShowDebugLogFlag(name: "InputRouting", flags: ImGuiDebugLogFlags_EventInputRouting);
21218
21219 if (SmallButton(label: "Clear"))
21220 {
21221 g.DebugLogBuf.clear();
21222 g.DebugLogIndex.clear();
21223 }
21224 SameLine();
21225 if (SmallButton(label: "Copy"))
21226 SetClipboardText(g.DebugLogBuf.c_str());
21227 BeginChild(str_id: "##log", size_arg: ImVec2(0.0f, 0.0f), child_flags: ImGuiChildFlags_Border, window_flags: ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21228
21229 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21230 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21231
21232 ImGuiListClipper clipper;
21233 clipper.Begin(items_count: g.DebugLogIndex.size());
21234 while (clipper.Step())
21235 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21236 {
21237 const char* line_begin = g.DebugLogIndex.get_line_begin(base: g.DebugLogBuf.c_str(), n: line_no);
21238 const char* line_end = g.DebugLogIndex.get_line_end(base: g.DebugLogBuf.c_str(), n: line_no);
21239 TextUnformatted(text: line_begin, text_end: line_end); // Display line
21240 ImRect text_rect = g.LastItemData.Rect;
21241 if (IsItemHovered())
21242 for (const char* p = line_begin; p <= line_end - 10; p++) // Search for 0x???????? identifiers
21243 {
21244 ImGuiID id = 0;
21245 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(s: p + 2, format: "%X", &id) != 1)
21246 continue;
21247 ImVec2 p0 = CalcTextSize(text: line_begin, text_end: p);
21248 ImVec2 p1 = CalcTextSize(text: p, text_end: p + 10);
21249 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21250 if (IsMouseHoveringRect(r_min: g.LastItemData.Rect.Min, r_max: g.LastItemData.Rect.Max, clip: true))
21251 DebugLocateItemOnHover(target_id: id);
21252 p += 10;
21253 }
21254 }
21255 g.DebugLogFlags = backup_log_flags;
21256 if (GetScrollY() >= GetScrollMaxY())
21257 SetScrollHereY(1.0f);
21258 EndChild();
21259
21260 End();
21261}
21262
21263//-----------------------------------------------------------------------------
21264// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21265//-----------------------------------------------------------------------------
21266
21267// Draw a small cross at current CursorPos in current window's DrawList
21268void ImGui::DebugDrawCursorPos(ImU32 col)
21269{
21270 ImGuiContext& g = *GImGui;
21271 ImGuiWindow* window = g.CurrentWindow;
21272 ImVec2 pos = window->DC.CursorPos;
21273 window->DrawList->AddLine(p1: ImVec2(pos.x, pos.y - 3.0f), p2: ImVec2(pos.x, pos.y + 4.0f), col, thickness: 1.0f);
21274 window->DrawList->AddLine(p1: ImVec2(pos.x - 3.0f, pos.y), p2: ImVec2(pos.x + 4.0f, pos.y), col, thickness: 1.0f);
21275}
21276
21277// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21278void ImGui::DebugDrawLineExtents(ImU32 col)
21279{
21280 ImGuiContext& g = *GImGui;
21281 ImGuiWindow* window = g.CurrentWindow;
21282 float curr_x = window->DC.CursorPos.x;
21283 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21284 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21285 window->DrawList->AddLine(p1: ImVec2(curr_x - 5.0f, line_y1), p2: ImVec2(curr_x + 5.0f, line_y1), col, thickness: 1.0f);
21286 window->DrawList->AddLine(p1: ImVec2(curr_x - 0.5f, line_y1), p2: ImVec2(curr_x - 0.5f, line_y2), col, thickness: 1.0f);
21287 window->DrawList->AddLine(p1: ImVec2(curr_x - 5.0f, line_y2), p2: ImVec2(curr_x + 5.0f, line_y2), col, thickness: 1.0f);
21288}
21289
21290// Draw last item rect in ForegroundDrawList (so it is always visible)
21291void ImGui::DebugDrawItemRect(ImU32 col)
21292{
21293 ImGuiContext& g = *GImGui;
21294 ImGuiWindow* window = g.CurrentWindow;
21295 GetForegroundDrawList(window)->AddRect(p_min: g.LastItemData.Rect.Min, p_max: g.LastItemData.Rect.Max, col);
21296}
21297
21298// [DEBUG] Locate item position/rectangle given an ID.
21299static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
21300
21301void ImGui::DebugLocateItem(ImGuiID target_id)
21302{
21303 ImGuiContext& g = *GImGui;
21304 g.DebugLocateId = target_id;
21305 g.DebugLocateFrames = 2;
21306 g.DebugBreakInLocateId = false;
21307}
21308
21309// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21310void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21311{
21312 if (target_id == 0 || !IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21313 return;
21314 ImGuiContext& g = *GImGui;
21315 DebugLocateItem(target_id);
21316 GetForegroundDrawList(window: g.CurrentWindow)->AddRect(p_min: g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), p_max: g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), col: DEBUG_LOCATE_ITEM_COLOR);
21317
21318 // Can't easily use a context menu here because it will mess with focus, active id etc.
21319 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21320 {
21321 DebugBreakButtonTooltip(keyboard_only: false, description_of_location: "in ItemAdd()");
21322 if (IsKeyChordPressed(key_chord: g.DebugBreakKeyChord))
21323 g.DebugBreakInLocateId = true;
21324 }
21325}
21326
21327void ImGui::DebugLocateItemResolveWithLastItem()
21328{
21329 ImGuiContext& g = *GImGui;
21330
21331 // [DEBUG] Debug break requested by user
21332 if (g.DebugBreakInLocateId)
21333 IM_DEBUG_BREAK();
21334
21335 ImGuiLastItemData item_data = g.LastItemData;
21336 g.DebugLocateId = 0;
21337 ImDrawList* draw_list = GetForegroundDrawList(window: g.CurrentWindow);
21338 ImRect r = item_data.Rect;
21339 r.Expand(amount: 3.0f);
21340 ImVec2 p1 = g.IO.MousePos;
21341 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);
21342 draw_list->AddRect(p_min: r.Min, p_max: r.Max, col: DEBUG_LOCATE_ITEM_COLOR);
21343 draw_list->AddLine(p1, p2, col: DEBUG_LOCATE_ITEM_COLOR);
21344}
21345
21346void ImGui::DebugStartItemPicker()
21347{
21348 ImGuiContext& g = *GImGui;
21349 g.DebugItemPickerActive = true;
21350}
21351
21352// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21353void ImGui::UpdateDebugToolItemPicker()
21354{
21355 ImGuiContext& g = *GImGui;
21356 g.DebugItemPickerBreakId = 0;
21357 if (!g.DebugItemPickerActive)
21358 return;
21359
21360 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21361 SetMouseCursor(ImGuiMouseCursor_Hand);
21362 if (IsKeyPressed(key: ImGuiKey_Escape))
21363 g.DebugItemPickerActive = false;
21364 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21365 if (!change_mapping && IsMouseClicked(button: g.DebugItemPickerMouseButton) && hovered_id)
21366 {
21367 g.DebugItemPickerBreakId = hovered_id;
21368 g.DebugItemPickerActive = false;
21369 }
21370 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21371 if (change_mapping && IsMouseClicked(button: mouse_button))
21372 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21373 SetNextWindowBgAlpha(0.70f);
21374 if (!BeginTooltip())
21375 return;
21376 Text(fmt: "HoveredId: 0x%08X", hovered_id);
21377 Text(fmt: "Press ESC to abort picking.");
21378 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21379 if (change_mapping)
21380 Text(fmt: "Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21381 else
21382 TextColored(col: GetStyleColorVec4(idx: hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), fmt: "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21383 EndTooltip();
21384}
21385
21386// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21387void ImGui::UpdateDebugToolStackQueries()
21388{
21389 ImGuiContext& g = *GImGui;
21390 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21391
21392 // Clear hook when id stack tool is not visible
21393 g.DebugHookIdInfo = 0;
21394 if (g.FrameCount != tool->LastActiveFrame + 1)
21395 return;
21396
21397 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21398 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21399 const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21400 if (tool->QueryId != query_id)
21401 {
21402 tool->QueryId = query_id;
21403 tool->StackLevel = -1;
21404 tool->Results.resize(new_size: 0);
21405 }
21406 if (query_id == 0)
21407 return;
21408
21409 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21410 int stack_level = tool->StackLevel;
21411 if (stack_level >= 0 && stack_level < tool->Results.Size)
21412 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21413 tool->StackLevel++;
21414
21415 // Update hook
21416 stack_level = tool->StackLevel;
21417 if (stack_level == -1)
21418 g.DebugHookIdInfo = query_id;
21419 if (stack_level >= 0 && stack_level < tool->Results.Size)
21420 {
21421 g.DebugHookIdInfo = tool->Results[stack_level].ID;
21422 tool->Results[stack_level].QueryFrameCount++;
21423 }
21424}
21425
21426// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21427void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21428{
21429 ImGuiContext& g = *GImGui;
21430 ImGuiWindow* window = g.CurrentWindow;
21431 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21432
21433 // Step 0: stack query
21434 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21435 if (tool->StackLevel == -1)
21436 {
21437 tool->StackLevel++;
21438 tool->Results.resize(new_size: window->IDStack.Size + 1, v: ImGuiStackLevelInfo());
21439 for (int n = 0; n < window->IDStack.Size + 1; n++)
21440 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21441 return;
21442 }
21443
21444 // Step 1+: query for individual level
21445 IM_ASSERT(tool->StackLevel >= 0);
21446 if (tool->StackLevel != window->IDStack.Size)
21447 return;
21448 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21449 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21450
21451 switch (data_type)
21452 {
21453 case ImGuiDataType_S32:
21454 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "%d", (int)(intptr_t)data_id);
21455 break;
21456 case ImGuiDataType_String:
21457 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen(s: (const char*)data_id), (const char*)data_id);
21458 break;
21459 case ImGuiDataType_Pointer:
21460 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "(void*)0x%p", data_id);
21461 break;
21462 case ImGuiDataType_ID:
21463 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.
21464 return;
21465 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "0x%08X [override]", id);
21466 break;
21467 default:
21468 IM_ASSERT(0);
21469 }
21470 info->QuerySuccess = true;
21471 info->DataType = data_type;
21472}
21473
21474static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21475{
21476 ImGuiStackLevelInfo* info = &tool->Results[n];
21477 ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(id: info->ID) : NULL;
21478 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21479 return ImFormatString(buf, buf_size, fmt: format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21480 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21481 return ImFormatString(buf, buf_size, fmt: (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21482 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21483 return (*buf = 0);
21484#ifdef IMGUI_ENABLE_TEST_ENGINE
21485 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
21486 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21487#endif
21488 return ImFormatString(buf, buf_size, fmt: "???");
21489}
21490
21491// ID Stack Tool: Display UI
21492void ImGui::ShowIDStackToolWindow(bool* p_open)
21493{
21494 ImGuiContext& g = *GImGui;
21495 if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21496 SetNextWindowSize(size: ImVec2(0.0f, GetFontSize() * 8.0f), cond: ImGuiCond_FirstUseEver);
21497 if (!Begin(name: "Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
21498 {
21499 End();
21500 return;
21501 }
21502
21503 // Display hovered/active status
21504 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21505 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21506 const ImGuiID active_id = g.ActiveId;
21507#ifdef IMGUI_ENABLE_TEST_ENGINE
21508 Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
21509#else
21510 Text(fmt: "HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
21511#endif
21512 SameLine();
21513 MetricsHelpMarker(desc: "Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21514
21515 // CTRL+C to copy path
21516 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21517 Checkbox(label: "Ctrl+C: copy path to clipboard", v: &tool->CopyToClipboardOnCtrlC);
21518 SameLine();
21519 TextColored(col: (time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), fmt: "*COPIED*");
21520 if (tool->CopyToClipboardOnCtrlC && Shortcut(key_chord: ImGuiMod_Ctrl | ImGuiKey_C, owner_id: 0, flags: ImGuiInputFlags_RouteGlobal))
21521 {
21522 tool->CopyToClipboardLastTime = (float)g.Time;
21523 char* p = g.TempBuffer.Data;
21524 char* p_end = p + g.TempBuffer.Size;
21525 for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21526 {
21527 *p++ = '/';
21528 char level_desc[256];
21529 StackToolFormatLevelInfo(tool, n: stack_n, format_for_ui: false, buf: level_desc, IM_ARRAYSIZE(level_desc));
21530 for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21531 {
21532 if (level_desc[n] == '/')
21533 *p++ = '\\';
21534 *p++ = level_desc[n];
21535 }
21536 }
21537 *p = '\0';
21538 SetClipboardText(g.TempBuffer.Data);
21539 }
21540
21541 // Display decorated stack
21542 tool->LastActiveFrame = g.FrameCount;
21543 if (tool->Results.Size > 0 && BeginTable(str_id: "##table", column: 3, flags: ImGuiTableFlags_Borders))
21544 {
21545 const float id_width = CalcTextSize(text: "0xDDDDDDDD").x;
21546 TableSetupColumn(label: "Seed", flags: ImGuiTableColumnFlags_WidthFixed, init_width_or_weight: id_width);
21547 TableSetupColumn(label: "PushID", flags: ImGuiTableColumnFlags_WidthStretch);
21548 TableSetupColumn(label: "Result", flags: ImGuiTableColumnFlags_WidthFixed, init_width_or_weight: id_width);
21549 TableHeadersRow();
21550 for (int n = 0; n < tool->Results.Size; n++)
21551 {
21552 ImGuiStackLevelInfo* info = &tool->Results[n];
21553 TableNextColumn();
21554 Text(fmt: "0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21555 TableNextColumn();
21556 StackToolFormatLevelInfo(tool, n, format_for_ui: true, buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size);
21557 TextUnformatted(text: g.TempBuffer.Data);
21558 TableNextColumn();
21559 Text(fmt: "0x%08X", info->ID);
21560 if (n == tool->Results.Size - 1)
21561 TableSetBgColor(target: ImGuiTableBgTarget_CellBg, color: GetColorU32(idx: ImGuiCol_Header));
21562 }
21563 EndTable();
21564 }
21565 End();
21566}
21567
21568#else
21569
21570void ImGui::ShowMetricsWindow(bool*) {}
21571void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21572void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21573void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21574void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21575void ImGui::DebugNodeFont(ImFont*) {}
21576void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21577void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21578void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21579void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21580void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21581void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21582
21583void ImGui::DebugLog(const char*, ...) {}
21584void ImGui::DebugLogV(const char*, va_list) {}
21585void ImGui::ShowDebugLogWindow(bool*) {}
21586void ImGui::ShowIDStackToolWindow(bool*) {}
21587void ImGui::DebugStartItemPicker() {}
21588void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21589
21590#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21591
21592//-----------------------------------------------------------------------------
21593
21594// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21595// 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.
21596#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21597#include "imgui_user.inl"
21598#endif
21599
21600//-----------------------------------------------------------------------------
21601
21602#endif // #ifndef IMGUI_DISABLE
21603

source code of imgui/imgui.cpp