1// dear imgui, v1.91.0
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/7503 (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] PLATFORM DEPENDENT HELPERS
95// [SECTION] METRICS/DEBUGGER WINDOW
96// [SECTION] DEBUG LOG WINDOW
97// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
98
99*/
100
101//-----------------------------------------------------------------------------
102// DOCUMENTATION
103//-----------------------------------------------------------------------------
104
105/*
106
107 MISSION STATEMENT
108 =================
109
110 - Easy to use to create code-driven and data-driven tools.
111 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
112 - Easy to hack and improve.
113 - Minimize setup and maintenance.
114 - Minimize state storage on user side.
115 - Minimize state synchronization.
116 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
117 - Efficient runtime and memory consumption.
118
119 Designed primarily for developers and content-creators, not the typical end-user!
120 Some of the current weaknesses (which we aim to address in the future) includes:
121
122 - Doesn't look fancy.
123 - Limited layout features, intricate layouts are typically crafted in code.
124
125
126 CONTROLS GUIDE
127 ==============
128
129 - MOUSE CONTROLS
130 - Mouse wheel: Scroll vertically.
131 - SHIFT+Mouse wheel: Scroll horizontally.
132 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
133 - Click ^, Double-Click title: Collapse window.
134 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
135 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
136 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
137
138 - TEXT EDITOR
139 - Hold SHIFT or Drag Mouse: Select text.
140 - CTRL+Left/Right: Word jump.
141 - CTRL+Shift+Left/Right: Select words.
142 - CTRL+A or Double-Click: Select All.
143 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
144 - CTRL+Z, CTRL+Y: Undo, Redo.
145 - ESCAPE: Revert text to its original value.
146 - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
147
148 - KEYBOARD CONTROLS
149 - Basic:
150 - Tab, SHIFT+Tab Cycle through text editable fields.
151 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
152 - CTRL+Click Input text into a Slider or Drag widget.
153 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
154 - Tab, SHIFT+Tab: Cycle through every items.
155 - Arrow keys Move through items using directional navigation. Tweak value.
156 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
157 - Enter Activate item (prefer text input when possible).
158 - Space Activate item (prefer tweaking with arrows when possible).
159 - Escape Deactivate item, leave child window, close popup.
160 - Page Up, Page Down Previous page, next page.
161 - Home, End Scroll to top, scroll to bottom.
162 - Alt Toggle between scrolling layer and menu layer.
163 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
164 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
165 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
166 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
167 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
168
169 - GAMEPAD CONTROLS
170 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
171 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
172 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
173 - Backend support: backend needs to:
174 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
175 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
176 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.).
177 - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
178 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
179 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
180
181 - REMOTE INPUTS SHARING & MOUSE EMULATION
182 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
183 - 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)
184 in order to share your PC mouse/keyboard.
185 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
186 - 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.
187 Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
188 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.
189 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.
190 (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!)
191 (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
192 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
193
194
195 PROGRAMMER GUIDE
196 ================
197
198 READ FIRST
199 ----------
200 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
201 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
202 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
203 data retention on your side, less state duplication, less state synchronization, fewer bugs.
204 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
205 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
206 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
207 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
208 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
209 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
210 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,
211 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
212 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
213 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
214 If you get an assert, read the messages and comments around the assert.
215 - This codebase aims to be highly optimized:
216 - A typical idle frame should never call malloc/free.
217 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
218 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
219 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
220 - This codebase aims to be both highly opinionated and highly flexible:
221 - This code works because of the things it choose to solve or not solve.
222 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
223 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
224 This is to increase compatibility, increase maintainability and facilitate use from other languages.
225 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
226 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
227 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
228 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
229 (so don't use ImVector in your code or at our own risk!).
230 - Building: We don't use nor mandate a build system for the main library.
231 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
232 This is also because providing a build system for the main library would be of little-value.
233 The build problems are almost never coming from the main library but from specific backends.
234
235
236 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
237 ----------------------------------------------
238 - Update submodule or copy/overwrite every file.
239 - About imconfig.h:
240 - You may modify your copy of imconfig.h, in this case don't overwrite it.
241 - or you may locally branch to modify imconfig.h and merge/rebase latest.
242 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
243 specify a custom path for your imconfig.h file and instead not have to modify the default one.
244
245 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
246 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
247 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
248 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
249 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
250 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
251 likely be a comment about it. Please report any issue to the GitHub page!
252 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
253 - Try to keep your copy of Dear ImGui reasonably up to date!
254
255
256 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
257 ---------------------------------------------------------------
258 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
259 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
260 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
261 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
262 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
263 - 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.
264 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
265 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
266 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
267 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
268 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
269 - 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.
270
271
272 HOW A SIMPLE APPLICATION MAY LOOK LIKE
273 --------------------------------------
274 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
275 The sub-folders in examples/ contain examples applications following this structure.
276
277 // Application init: create a dear imgui context, setup some options, load fonts
278 ImGui::CreateContext();
279 ImGuiIO& io = ImGui::GetIO();
280 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
281 // TODO: Fill optional fields of the io structure later.
282 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
283
284 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
285 ImGui_ImplWin32_Init(hwnd);
286 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
287
288 // Application main loop
289 while (true)
290 {
291 // Feed inputs to dear imgui, start new frame
292 ImGui_ImplDX11_NewFrame();
293 ImGui_ImplWin32_NewFrame();
294 ImGui::NewFrame();
295
296 // Any application code here
297 ImGui::Text("Hello, world!");
298
299 // Render dear imgui into screen
300 ImGui::Render();
301 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
302 g_pSwapChain->Present(1, 0);
303 }
304
305 // Shutdown
306 ImGui_ImplDX11_Shutdown();
307 ImGui_ImplWin32_Shutdown();
308 ImGui::DestroyContext();
309
310 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
311
312 // Application init: create a dear imgui context, setup some options, load fonts
313 ImGui::CreateContext();
314 ImGuiIO& io = ImGui::GetIO();
315 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
316 // TODO: Fill optional fields of the io structure later.
317 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
318
319 // Build and load the texture atlas into a texture
320 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
321 int width, height;
322 unsigned char* pixels = nullptr;
323 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
324
325 // At this point you've got the texture data and you need to upload that to your graphic system:
326 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
327 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
328 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
329 io.Fonts->SetTexID((void*)texture);
330
331 // Application main loop
332 while (true)
333 {
334 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
335 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
336 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
337 io.DisplaySize.x = 1920.0f; // set the current display width
338 io.DisplaySize.y = 1280.0f; // set the current display height here
339 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
340 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
341 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
342
343 // Call NewFrame(), after this point you can use ImGui::* functions anytime
344 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
345 ImGui::NewFrame();
346
347 // Most of your application code here
348 ImGui::Text("Hello, world!");
349 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
350 MyGameRender(); // may use any Dear ImGui functions as well!
351
352 // Render dear imgui, swap buffers
353 // (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)
354 ImGui::EndFrame();
355 ImGui::Render();
356 ImDrawData* draw_data = ImGui::GetDrawData();
357 MyImGuiRenderFunction(draw_data);
358 SwapBuffers();
359 }
360
361 // Shutdown
362 ImGui::DestroyContext();
363
364 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
365 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
366 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
367
368
369 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
370 ---------------------------------------------
371 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
372
373 void MyImGuiRenderFunction(ImDrawData* draw_data)
374 {
375 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
376 // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
377 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
378 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
380 ImVec2 clip_off = draw_data->DisplayPos;
381 for (int n = 0; n < draw_data->CmdListsCount; n++)
382 {
383 const ImDrawList* cmd_list = draw_data->CmdLists[n];
384 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
385 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
386 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
387 {
388 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
389 if (pcmd->UserCallback)
390 {
391 pcmd->UserCallback(cmd_list, pcmd);
392 }
393 else
394 {
395 // Project scissor/clipping rectangles into framebuffer space
396 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
397 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
398 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
399 continue;
400
401 // We are using scissoring to clip some objects. All low-level graphics API should support it.
402 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
403 // (some elements visible outside their bounds) but you can fix that once everything else works!
404 // - Clipping coordinates are provided in imgui coordinates space:
405 // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
406 // - 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.
407 // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
408 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
409 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
410 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
411
412 // The texture for the draw call is specified by pcmd->GetTexID().
413 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
414 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
415
416 // Render 'pcmd->ElemCount/3' indexed triangles.
417 // 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.
418 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
419 }
420 }
421 }
422 }
423
424
425 API BREAKING CHANGES
426 ====================
427
428 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
429 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.
430 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.
431 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
432
433 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
434 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
435 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
436 - you can use: GetContentRegionAvail().x
437 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
438 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
439 - instead of: GetContentRegionMax()
440 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
441 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
442 - you can use: GetContentRegionAvail() // when called from left edge of window
443 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
444 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
445 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
446 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
447 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
448 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
449 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
450 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
451 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
452 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
453 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
454 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
455 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
456 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
457 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
458 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
459 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
460 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
461 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
462 - old: CaptureKeyboardFromApp(bool)
463 - new: SetNextFrameWantCaptureKeyboard(bool)
464 - old: CaptureMouseFromApp(bool)
465 - new: SetNextFrameWantCaptureMouse(bool)
466 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
467 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
468 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
469 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
470 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
471 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
472 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
473 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
474 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
475 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
476 for various reasons those changes makes sense. They are being made because making some of those API public.
477 only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
478 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
479 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
480 - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
481 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
482 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
483 - old: TreeNode("##Hidden"); SameLine(); Text("Hello"); // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
484 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
485 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
486 You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
487 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
488 - 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)
489 - 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)
490 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
491 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
492 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
493 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
494 - 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.
495 - 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.
496 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
497 - 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).
498 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.
499 - 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.
500 - old: BeginChild("Name", size, true)
501 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
502 - old: BeginChild("Name", size, false)
503 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
504 - 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.
505 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
506 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
507 - 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).
508 - 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)
509 - 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).
510 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
511 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
512 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
513 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
514 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
515 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
516 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
517 - 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
518 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
519 - 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)
520 - 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).
521 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
522 - 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.
523 - 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)
524 - 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.
525 - 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.
526 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
527 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
528 - ListBoxFooter() -> use EndListBox()
529 - 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().
530 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
531 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
532 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
533 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
534 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
535 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
536 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
537 - 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.
538 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
539 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
540 it has been frequently requested by people to use our own. We had an opt-in define which was
541 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
542 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
543 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
544 - 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.
545 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
546 - 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.
547 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
548 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
549 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
550 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
551 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
552 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
553 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
554 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.
555 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
556 this will require uses of legacy backend-dependent indices to be casted, e.g.
557 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
558 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
559 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
560 - 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);
561 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
562 - 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.
563 - 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.
564 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
565 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
566 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
567 - previously this would make the window content size ~200x200:
568 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
569 - instead, please submit an item:
570 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
571 - alternative:
572 Begin(...) + Dummy(ImVec2(200,200)) + End();
573 - content size is now only extended when submitting an item!
574 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
575 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
576 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
577 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
578 - 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));
579 - 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.
580 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
581 - 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));
582 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
583 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
584 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
585 - Official backends from 1.87+ -> no issue.
586 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
587 - Custom backends not writing to io.NavInputs[] -> no issue.
588 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
589 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
590 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
591 - 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.
592 - 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.
593 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
594 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
595 - 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).
596 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
597 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
598 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
599 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
600 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
601 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
602 read https://github.com/ocornut/imgui/issues/4921 for details.
603 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
604 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
605 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
606 - 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).
607 - 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.*
608 - 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.
609 - 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.
610 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
611 - 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'.
612 - 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)
613 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
614 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
615 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
616 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
617 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
618 - 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
619 - 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.
620 - 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.
621 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
622 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
623 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
624 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
625 - if you are using official backends from the source tree: you have nothing to do.
626 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
627 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
628 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
629 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
630 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
631 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
632 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
633 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
634 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
635 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
636 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
637 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
638 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.
639 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).
640 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
641 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
642 - 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.
643 - 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.
644 - 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'.
645 - 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.
646 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
647 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
648 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
649 - 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.
650 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
651 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
652 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
653 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
654 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
655 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
656 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
657 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
658 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
659 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
660 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
661 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
662 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
663 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
664 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
665 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
666 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
667 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
668 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
669 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
670 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
671 - 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).
672 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
673 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
674 - 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.
675 - 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.
676 - 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!
677 - 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().
678 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
679 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
680 - if you omitted the 'power' parameter (likely!), you are not affected.
681 - 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.
682 - 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.
683 see https://github.com/ocornut/imgui/issues/3361 for all details.
684 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.
685 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
686 - 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.
687 - 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.
688 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
689 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
690 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
691 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
692 - 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.
693 - 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.
694 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
695 - ShowTestWindow() -> use ShowDemoWindow()
696 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
697 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
698 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
699 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
700 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
701 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
702 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
703 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
704 - 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.
705 - 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).
706 - 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.
707 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
708 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
709 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
710 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
711 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
712 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
713 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
714 - ImFont::Glyph -> use ImFontGlyph
715 - 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.
716 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.
717 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).
718 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
719 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
720 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
721 - 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.
722 - 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
723 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.
724 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.
725 Please reach out if you are affected.
726 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
727 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
728 - 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.
729 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
730 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
731 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
732 - 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!
733 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
734 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
735 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
736 - 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.
737 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
738 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
739 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
740 - 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.
741 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
742 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
743 - 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.
744 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
745 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
746 - 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).
747 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
748 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
749 - 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.
750 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
751 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
752 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
753 - 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.).
754 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
755 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
756 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
757 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
758 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
759 - 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.
760 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
761 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.
762 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.
763 - 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",
764 consistent with other functions. Kept redirection functions (will obsolete).
765 - 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.
766 - 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).
767 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
768 - 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.
769 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
770 - 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.
771 - 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.
772 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
773 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
774 - removed Shutdown() function, as DestroyContext() serve this purpose.
775 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
776 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
777 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
778 - 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.
779 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
780 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
781 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
782 - 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.
783 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
784 - 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
785 - 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.
786 - 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.
787 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
788 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
789 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
790 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
791 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
792 - 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.
793 - 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.
794 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.
795 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
796 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
797 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
798 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
799 - 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.
800 - 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.
801 - 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.
802 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
803 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
804 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
805 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
806 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
807 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
808 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
809 - 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).
810 - 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)".
811 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
812 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
813 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
814 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
815 - 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.
816 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
817 - 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.
818 - 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).
819 - 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).
820 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
821 - 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.
822 - 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.
823 - 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))'
824 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
825 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
826 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
827 - 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().
828 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
829 - 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.
830 - 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.
831 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
832 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.
833 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:
834 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); }
835 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.
836 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
837 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
838 - 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).
839 - 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.
840 - 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).
841 - 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)
842 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
843 - 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.
844 - 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.
845 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
846 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
847 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
848 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.
849 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!
850 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
851 - 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.
852 - 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
853 - 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.
854 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
855 - 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.
856 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
857 - 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.
858 - the signature of the io.RenderDrawListsFn handler has changed!
859 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
860 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
861 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
862 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
863 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
864 - 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.
865 - 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!
866 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
867 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
868 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
869 - 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.
870 - 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
871 - 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!
872 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
873 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
874 - 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.
875 - 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.
876 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
877 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
878 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
879 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
880 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
881 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
882 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
883 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
884 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
885 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
886 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
887 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
888 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
889 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
890 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
891 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
892 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
893 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
894 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
895 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
896 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.
897 - 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()
898 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
899 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
900 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
901 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
902 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
903 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
904 - 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)
905 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
906 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
907 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
908 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
909 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
910 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
911
912
913 FREQUENTLY ASKED QUESTIONS (FAQ)
914 ================================
915
916 Read all answers online:
917 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
918 Read all answers locally (with a text editor or ideally a Markdown viewer):
919 docs/FAQ.md
920 Some answers are copied down here to facilitate searching in code.
921
922 Q&A: Basics
923 ===========
924
925 Q: Where is the documentation?
926 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
927 - Run the examples/ applications and explore them.
928 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
929 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
930 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
931 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
932 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
933 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
934 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
935 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
936 - Your programming IDE is your friend, find the type or function declaration to find comments
937 associated with it.
938
939 Q: What is this library called?
940 Q: Which version should I get?
941 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
942 >> See https://www.dearimgui.com/faq for details.
943
944 Q&A: Integration
945 ================
946
947 Q: How to get started?
948 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
949
950 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
951 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
952 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
953
954 Q. How can I enable keyboard or gamepad controls?
955 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
956 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
957 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
958 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
959 >> See https://www.dearimgui.com/faq
960
961 Q&A: Usage
962 ----------
963
964 Q: About the ID Stack system..
965 - Why is my widget not reacting when I click on it?
966 - How can I have widgets with an empty label?
967 - How can I have multiple widgets with the same label?
968 - How can I have multiple windows with the same label?
969 Q: How can I display an image? What is ImTextureID, how does it work?
970 Q: How can I use my own math types instead of ImVec2?
971 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
972 Q: How can I display custom shapes? (using low-level ImDrawList API)
973 >> See https://www.dearimgui.com/faq
974
975 Q&A: Fonts, Text
976 ================
977
978 Q: How should I handle DPI in my application?
979 Q: How can I load a different font than the default?
980 Q: How can I easily use icons in my application?
981 Q: How can I load multiple fonts?
982 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
983 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
984
985 Q&A: Concerns
986 =============
987
988 Q: Who uses Dear ImGui?
989 Q: Can you create elaborate/serious tools with Dear ImGui?
990 Q: Can you reskin the look of Dear ImGui?
991 Q: Why using C++ (as opposed to C)?
992 >> See https://www.dearimgui.com/faq
993
994 Q&A: Community
995 ==============
996
997 Q: How can I help?
998 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
999 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1000 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1001 >>> See https://github.com/ocornut/imgui/wiki/Funding
1002 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1003 - 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!
1004 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1005 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1006 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1007 - 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).
1008
1009*/
1010
1011//-------------------------------------------------------------------------
1012// [SECTION] INCLUDES
1013//-------------------------------------------------------------------------
1014
1015#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1016#define _CRT_SECURE_NO_WARNINGS
1017#endif
1018
1019#ifndef IMGUI_DEFINE_MATH_OPERATORS
1020#define IMGUI_DEFINE_MATH_OPERATORS
1021#endif
1022
1023#include "imgui.h"
1024#ifndef IMGUI_DISABLE
1025#include "imgui_internal.h"
1026
1027// System includes
1028#include <stdio.h> // vsnprintf, sscanf, printf
1029#include <stdint.h> // intptr_t
1030
1031// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1032#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1033#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1034#endif
1035
1036// [Windows] OS specific includes (optional)
1037#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1038#define IMGUI_DISABLE_WIN32_FUNCTIONS
1039#endif
1040#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1041#ifndef WIN32_LEAN_AND_MEAN
1042#define WIN32_LEAN_AND_MEAN
1043#endif
1044#ifndef NOMINMAX
1045#define NOMINMAX
1046#endif
1047#ifndef __MINGW32__
1048#include <Windows.h> // _wfopen, OpenClipboard
1049#else
1050#include <windows.h>
1051#endif
1052#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1053// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1054#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1055#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1056#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1057#endif
1058#endif
1059
1060// [Apple] OS specific includes
1061#if defined(__APPLE__)
1062#include <TargetConditionals.h>
1063#endif
1064
1065// Visual Studio warnings
1066#ifdef _MSC_VER
1067#pragma warning (disable: 4127) // condition expression is constant
1068#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1069#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1070#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1071#endif
1072#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).
1073#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1074#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1075#endif
1076
1077// Clang/GCC warnings with -Weverything
1078#if defined(__clang__)
1079#if __has_warning("-Wunknown-warning-option")
1080#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!
1081#endif
1082#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1083#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1084#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.
1085#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.
1086#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.
1087#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1088#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1089#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.
1090#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1091#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1092#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.
1093#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1094#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1095#elif defined(__GNUC__)
1096// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1097#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1098#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1099#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1100#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1101#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1102#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1103#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1104#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1105#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
1106#endif
1107
1108// Debug options
1109#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
1110#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1111
1112// 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.
1113static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1114static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1115
1116static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1117
1118// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1119static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1120static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1121static 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.
1122
1123// Tooltip offset
1124static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1125
1126//-------------------------------------------------------------------------
1127// [SECTION] FORWARD DECLARATIONS
1128//-------------------------------------------------------------------------
1129
1130static void SetCurrentWindow(ImGuiWindow* window);
1131static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1132static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1133
1134static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1135
1136// Settings
1137static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1138static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1139static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1140static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1141static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1142
1143// Platform Dependents default implementation for IO functions
1144static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1145static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1146static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1147static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1148
1149namespace ImGui
1150{
1151// Item
1152static void ItemHandleShortcut(ImGuiID id);
1153
1154// Navigation
1155static void NavUpdate();
1156static void NavUpdateWindowing();
1157static void NavUpdateWindowingOverlay();
1158static void NavUpdateCancelRequest();
1159static void NavUpdateCreateMoveRequest();
1160static void NavUpdateCreateTabbingRequest();
1161static float NavUpdatePageUpPageDown();
1162static inline void NavUpdateAnyRequestFlag();
1163static void NavUpdateCreateWrappingRequest();
1164static void NavEndFrame();
1165static bool NavScoreItem(ImGuiNavItemData* result);
1166static void NavApplyItemToResult(ImGuiNavItemData* result);
1167static void NavProcessItem();
1168static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1169static ImVec2 NavCalcPreferredRefPos();
1170static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1171static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1172static void NavRestoreLayer(ImGuiNavLayer layer);
1173static int FindWindowFocusIndex(ImGuiWindow* window);
1174
1175// Error Checking and Debug Tools
1176static void ErrorCheckNewFrameSanityChecks();
1177static void ErrorCheckEndFrameSanityChecks();
1178static void UpdateDebugToolItemPicker();
1179static void UpdateDebugToolStackQueries();
1180static void UpdateDebugToolFlashStyleColor();
1181
1182// Inputs
1183static void UpdateKeyboardInputs();
1184static void UpdateMouseInputs();
1185static void UpdateMouseWheel();
1186static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1187
1188// Misc
1189static void UpdateSettings();
1190static 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);
1191static void RenderWindowOuterBorders(ImGuiWindow* window);
1192static 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);
1193static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1194static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1195static void RenderDimmedBackgrounds();
1196static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1197
1198// Viewports
1199const 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.
1200static void UpdateViewportsNewFrame();
1201
1202}
1203
1204//-----------------------------------------------------------------------------
1205// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1206//-----------------------------------------------------------------------------
1207
1208// DLL users:
1209// - Heaps and globals are not shared across DLL boundaries!
1210// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1211// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1212// - 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.
1213// - 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).
1214
1215// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1216// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1217// Change to a different context by calling ImGui::SetCurrentContext().
1218// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1219// If you want thread-safety to allow N threads to access N different contexts:
1220// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1221// struct ImGuiContext;
1222// extern thread_local ImGuiContext* MyImGuiTLS;
1223// #define GImGui MyImGuiTLS
1224// 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.
1225// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1226// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1227// - DLL users: read comments above.
1228#ifndef GImGui
1229ImGuiContext* GImGui = NULL;
1230#endif
1231
1232// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1233// - 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.
1234// - DLL users: read comments above.
1235#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1236static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size: size); }
1237static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr: ptr); }
1238#else
1239static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1240static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1241#endif
1242static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1243static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1244static void* GImAllocatorUserData = NULL;
1245
1246//-----------------------------------------------------------------------------
1247// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1248//-----------------------------------------------------------------------------
1249
1250ImGuiStyle::ImGuiStyle()
1251{
1252 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1253 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1254 WindowPadding = ImVec2(8,8); // Padding within a window
1255 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.
1256 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1257 WindowMinSize = ImVec2(32,32); // Minimum window size
1258 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1259 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1260 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1261 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1262 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1263 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1264 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1265 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1266 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1267 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1268 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1269 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1270 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!
1271 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1272 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1273 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1274 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1275 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1276 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1277 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1278 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1279 TabBorderSize = 0.0f; // Thickness of border around tabs.
1280 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.
1281 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1282 TabBarOverlineSize = 2.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1283 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1284 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1285 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1286 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1287 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.
1288 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText()
1289 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1290 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.
1291 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.
1292 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.
1293 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1294 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1295 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1296 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1297 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.
1298 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.
1299
1300 // Behaviors
1301 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1302 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1303 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1304 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1305 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1306
1307 // Default theme
1308 ImGui::StyleColorsDark(dst: this);
1309}
1310
1311// 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.
1312// 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.
1313void ImGuiStyle::ScaleAllSizes(float scale_factor)
1314{
1315 WindowPadding = ImTrunc(v: WindowPadding * scale_factor);
1316 WindowRounding = ImTrunc(f: WindowRounding * scale_factor);
1317 WindowMinSize = ImTrunc(v: WindowMinSize * scale_factor);
1318 ChildRounding = ImTrunc(f: ChildRounding * scale_factor);
1319 PopupRounding = ImTrunc(f: PopupRounding * scale_factor);
1320 FramePadding = ImTrunc(v: FramePadding * scale_factor);
1321 FrameRounding = ImTrunc(f: FrameRounding * scale_factor);
1322 ItemSpacing = ImTrunc(v: ItemSpacing * scale_factor);
1323 ItemInnerSpacing = ImTrunc(v: ItemInnerSpacing * scale_factor);
1324 CellPadding = ImTrunc(v: CellPadding * scale_factor);
1325 TouchExtraPadding = ImTrunc(v: TouchExtraPadding * scale_factor);
1326 IndentSpacing = ImTrunc(f: IndentSpacing * scale_factor);
1327 ColumnsMinSpacing = ImTrunc(f: ColumnsMinSpacing * scale_factor);
1328 ScrollbarSize = ImTrunc(f: ScrollbarSize * scale_factor);
1329 ScrollbarRounding = ImTrunc(f: ScrollbarRounding * scale_factor);
1330 GrabMinSize = ImTrunc(f: GrabMinSize * scale_factor);
1331 GrabRounding = ImTrunc(f: GrabRounding * scale_factor);
1332 LogSliderDeadzone = ImTrunc(f: LogSliderDeadzone * scale_factor);
1333 TabRounding = ImTrunc(f: TabRounding * scale_factor);
1334 TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(f: TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1335 TabBarOverlineSize = ImTrunc(f: TabBarOverlineSize * scale_factor);
1336 SeparatorTextPadding = ImTrunc(v: SeparatorTextPadding * scale_factor);
1337 DisplayWindowPadding = ImTrunc(v: DisplayWindowPadding * scale_factor);
1338 DisplaySafeAreaPadding = ImTrunc(v: DisplaySafeAreaPadding * scale_factor);
1339 MouseCursorScale = ImTrunc(f: MouseCursorScale * scale_factor);
1340}
1341
1342ImGuiIO::ImGuiIO()
1343{
1344 // Most fields are initialized with zero
1345 memset(s: this, c: 0, n: sizeof(*this));
1346 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1347
1348 // Settings
1349 ConfigFlags = ImGuiConfigFlags_None;
1350 BackendFlags = ImGuiBackendFlags_None;
1351 DisplaySize = ImVec2(-1.0f, -1.0f);
1352 DeltaTime = 1.0f / 60.0f;
1353 IniSavingRate = 5.0f;
1354 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).
1355 LogFilename = "imgui_log.txt";
1356#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1357 for (int i = 0; i < ImGuiKey_COUNT; i++)
1358 KeyMap[i] = -1;
1359#endif
1360 UserData = NULL;
1361
1362 Fonts = NULL;
1363 FontGlobalScale = 1.0f;
1364 FontDefault = NULL;
1365 FontAllowUserScaling = false;
1366 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1367
1368 MouseDoubleClickTime = 0.30f;
1369 MouseDoubleClickMaxDist = 6.0f;
1370 MouseDragThreshold = 6.0f;
1371 KeyRepeatDelay = 0.275f;
1372 KeyRepeatRate = 0.050f;
1373
1374 // Miscellaneous options
1375 MouseDrawCursor = false;
1376#ifdef __APPLE__
1377 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1378#else
1379 ConfigMacOSXBehaviors = false;
1380#endif
1381 ConfigNavSwapGamepadButtons = false;
1382 ConfigInputTrickleEventQueue = true;
1383 ConfigInputTextCursorBlink = true;
1384 ConfigInputTextEnterKeepActive = false;
1385 ConfigDragClickToInputText = false;
1386 ConfigWindowsResizeFromEdges = true;
1387 ConfigWindowsMoveFromTitleBarOnly = false;
1388 ConfigMemoryCompactTimer = 60.0f;
1389 ConfigDebugBeginReturnValueOnce = false;
1390 ConfigDebugBeginReturnValueLoop = false;
1391
1392 // Platform Functions
1393 // Note: Initialize() will setup default clipboard/ime handlers.
1394 BackendPlatformName = BackendRendererName = NULL;
1395 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1396 PlatformOpenInShellUserData = NULL;
1397 PlatformLocaleDecimalPoint = '.';
1398
1399 // Input (NB: we already have memset zero the entire structure!)
1400 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1401 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1402 MouseSource = ImGuiMouseSource_Mouse;
1403 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1404 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1405 AppAcceptingEvents = true;
1406 BackendUsingLegacyKeyArrays = (ImS8)-1;
1407 BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1408}
1409
1410// Pass in translated ASCII characters for text input.
1411// - with glfw you can get those from the callback set in glfwSetCharCallback()
1412// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1413// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1414void ImGuiIO::AddInputCharacter(unsigned int c)
1415{
1416 IM_ASSERT(Ctx != NULL);
1417 ImGuiContext& g = *Ctx;
1418 if (c == 0 || !AppAcceptingEvents)
1419 return;
1420
1421 ImGuiInputEvent e;
1422 e.Type = ImGuiInputEventType_Text;
1423 e.Source = ImGuiInputSource_Keyboard;
1424 e.EventId = g.InputEventsNextEventId++;
1425 e.Text.Char = c;
1426 g.InputEventsQueue.push_back(v: e);
1427}
1428
1429// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1430// we should save the high surrogate.
1431void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1432{
1433 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1434 return;
1435
1436 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1437 {
1438 if (InputQueueSurrogate != 0)
1439 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1440 InputQueueSurrogate = c;
1441 return;
1442 }
1443
1444 ImWchar cp = c;
1445 if (InputQueueSurrogate != 0)
1446 {
1447 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1448 {
1449 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1450 }
1451 else
1452 {
1453#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1454 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1455#else
1456 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1457#endif
1458 }
1459
1460 InputQueueSurrogate = 0;
1461 }
1462 AddInputCharacter(c: (unsigned)cp);
1463}
1464
1465void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1466{
1467 if (!AppAcceptingEvents)
1468 return;
1469 while (*utf8_chars != 0)
1470 {
1471 unsigned int c = 0;
1472 utf8_chars += ImTextCharFromUtf8(out_char: &c, in_text: utf8_chars, NULL);
1473 AddInputCharacter(c);
1474 }
1475}
1476
1477// Clear all incoming events.
1478void ImGuiIO::ClearEventsQueue()
1479{
1480 IM_ASSERT(Ctx != NULL);
1481 ImGuiContext& g = *Ctx;
1482 g.InputEventsQueue.clear();
1483}
1484
1485// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1486void ImGuiIO::ClearInputKeys()
1487{
1488#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1489 memset(s: KeysDown, c: 0, n: sizeof(KeysDown));
1490#endif
1491 for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1492 {
1493 if (ImGui::IsMouseKey(key: (ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
1494 continue;
1495 KeysData[n].Down = false;
1496 KeysData[n].DownDuration = -1.0f;
1497 KeysData[n].DownDurationPrev = -1.0f;
1498 }
1499 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1500 KeyMods = ImGuiMod_None;
1501 InputQueueCharacters.resize(new_size: 0); // Behavior of old ClearInputCharacters().
1502}
1503
1504void ImGuiIO::ClearInputMouse()
1505{
1506 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1507 {
1508 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
1509 key_data->Down = false;
1510 key_data->DownDuration = -1.0f;
1511 key_data->DownDurationPrev = -1.0f;
1512 }
1513 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1514 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1515 {
1516 MouseDown[n] = false;
1517 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1518 }
1519 MouseWheel = MouseWheelH = 0.0f;
1520}
1521
1522// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1523// Current frame character buffer is now also cleared by ClearInputKeys().
1524#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1525void ImGuiIO::ClearInputCharacters()
1526{
1527 InputQueueCharacters.resize(new_size: 0);
1528}
1529#endif
1530
1531static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1532{
1533 ImGuiContext& g = *ctx;
1534 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1535 {
1536 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1537 if (e->Type != type)
1538 continue;
1539 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1540 continue;
1541 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1542 continue;
1543 return e;
1544 }
1545 return NULL;
1546}
1547
1548// Queue a new key down/up event.
1549// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1550// - bool down: Is the key down? use false to signify a key release.
1551// - float analog_value: 0.0f..1.0f
1552// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1553// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1554void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1555{
1556 //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); }
1557 IM_ASSERT(Ctx != NULL);
1558 if (key == ImGuiKey_None || !AppAcceptingEvents)
1559 return;
1560 ImGuiContext& g = *Ctx;
1561 IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1562 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1563
1564 // MacOS: swap Cmd(Super) and Ctrl
1565 if (g.IO.ConfigMacOSXBehaviors)
1566 {
1567 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1568 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1569 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1570 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1571 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1572 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1573 }
1574
1575 // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1576#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1577 IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1578 if (BackendUsingLegacyKeyArrays == -1)
1579 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1580 IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1581 BackendUsingLegacyKeyArrays = 0;
1582#endif
1583 if (ImGui::IsGamepadKey(key))
1584 BackendUsingLegacyNavInputArray = false;
1585
1586 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1587 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)key);
1588 const ImGuiKeyData* key_data = ImGui::GetKeyData(ctx: &g, key);
1589 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1590 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1591 if (latest_key_down == down && latest_key_analog == analog_value)
1592 return;
1593
1594 // Add event
1595 ImGuiInputEvent e;
1596 e.Type = ImGuiInputEventType_Key;
1597 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1598 e.EventId = g.InputEventsNextEventId++;
1599 e.Key.Key = key;
1600 e.Key.Down = down;
1601 e.Key.AnalogValue = analog_value;
1602 g.InputEventsQueue.push_back(v: e);
1603}
1604
1605void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1606{
1607 if (!AppAcceptingEvents)
1608 return;
1609 AddKeyAnalogEvent(key, down, analog_value: down ? 1.0f : 0.0f);
1610}
1611
1612// [Optional] Call after AddKeyEvent().
1613// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1614// 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.
1615void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1616{
1617 if (key == ImGuiKey_None)
1618 return;
1619 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1620 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1621 IM_UNUSED(native_keycode); // Yet unused
1622 IM_UNUSED(native_scancode); // Yet unused
1623
1624 // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1625#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1626 const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1627 if (!ImGui::IsLegacyKey(key: (ImGuiKey)legacy_key))
1628 return;
1629 KeyMap[legacy_key] = key;
1630 KeyMap[key] = legacy_key;
1631#else
1632 IM_UNUSED(key);
1633 IM_UNUSED(native_legacy_index);
1634#endif
1635}
1636
1637// 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.
1638void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1639{
1640 AppAcceptingEvents = accepting_events;
1641}
1642
1643// Queue a mouse move event
1644void ImGuiIO::AddMousePosEvent(float x, float y)
1645{
1646 IM_ASSERT(Ctx != NULL);
1647 ImGuiContext& g = *Ctx;
1648 if (!AppAcceptingEvents)
1649 return;
1650
1651 // Apply same flooring as UpdateMouseInputs()
1652 ImVec2 pos((x > -FLT_MAX) ? ImFloor(f: x) : x, (y > -FLT_MAX) ? ImFloor(f: y) : y);
1653
1654 // Filter duplicate
1655 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MousePos);
1656 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1657 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1658 return;
1659
1660 ImGuiInputEvent e;
1661 e.Type = ImGuiInputEventType_MousePos;
1662 e.Source = ImGuiInputSource_Mouse;
1663 e.EventId = g.InputEventsNextEventId++;
1664 e.MousePos.PosX = pos.x;
1665 e.MousePos.PosY = pos.y;
1666 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1667 g.InputEventsQueue.push_back(v: e);
1668}
1669
1670void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1671{
1672 IM_ASSERT(Ctx != NULL);
1673 ImGuiContext& g = *Ctx;
1674 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1675 if (!AppAcceptingEvents)
1676 return;
1677
1678 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1679 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1680 {
1681 // Order of both statements matterns: this event will still release mouse button 1
1682 mouse_button = 1;
1683 if (!down)
1684 MouseCtrlLeftAsRightClick = false;
1685 }
1686
1687 // Filter duplicate
1688 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseButton, arg: (int)mouse_button);
1689 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1690 if (latest_button_down == down)
1691 return;
1692
1693 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1694 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1695 // - At this point we want from !down to down, so this is handling the initial press.
1696 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1697 {
1698 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)ImGuiMod_Super);
1699 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1700 {
1701 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1702 MouseCtrlLeftAsRightClick = true;
1703 AddMouseButtonEvent(mouse_button: 1, down: true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1704 return;
1705 }
1706 }
1707
1708 ImGuiInputEvent e;
1709 e.Type = ImGuiInputEventType_MouseButton;
1710 e.Source = ImGuiInputSource_Mouse;
1711 e.EventId = g.InputEventsNextEventId++;
1712 e.MouseButton.Button = mouse_button;
1713 e.MouseButton.Down = down;
1714 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1715 g.InputEventsQueue.push_back(v: e);
1716}
1717
1718// Queue a mouse wheel event (some mouse/API may only have a Y component)
1719void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1720{
1721 IM_ASSERT(Ctx != NULL);
1722 ImGuiContext& g = *Ctx;
1723
1724 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1725 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1726 return;
1727
1728 ImGuiInputEvent e;
1729 e.Type = ImGuiInputEventType_MouseWheel;
1730 e.Source = ImGuiInputSource_Mouse;
1731 e.EventId = g.InputEventsNextEventId++;
1732 e.MouseWheel.WheelX = wheel_x;
1733 e.MouseWheel.WheelY = wheel_y;
1734 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1735 g.InputEventsQueue.push_back(v: e);
1736}
1737
1738// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1739// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1740void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1741{
1742 IM_ASSERT(Ctx != NULL);
1743 ImGuiContext& g = *Ctx;
1744 g.InputEventsNextMouseSource = source;
1745}
1746
1747void ImGuiIO::AddFocusEvent(bool focused)
1748{
1749 IM_ASSERT(Ctx != NULL);
1750 ImGuiContext& g = *Ctx;
1751
1752 // Filter duplicate
1753 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Focus);
1754 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1755 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1756 return;
1757
1758 ImGuiInputEvent e;
1759 e.Type = ImGuiInputEventType_Focus;
1760 e.EventId = g.InputEventsNextEventId++;
1761 e.AppFocused.Focused = focused;
1762 g.InputEventsQueue.push_back(v: e);
1763}
1764
1765//-----------------------------------------------------------------------------
1766// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1767//-----------------------------------------------------------------------------
1768
1769ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1770{
1771 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1772 ImVec2 p_last = p1;
1773 ImVec2 p_closest;
1774 float p_closest_dist2 = FLT_MAX;
1775 float t_step = 1.0f / (float)num_segments;
1776 for (int i_step = 1; i_step <= num_segments; i_step++)
1777 {
1778 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t: t_step * i_step);
1779 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
1780 float dist2 = ImLengthSqr(lhs: p - p_line);
1781 if (dist2 < p_closest_dist2)
1782 {
1783 p_closest = p_line;
1784 p_closest_dist2 = dist2;
1785 }
1786 p_last = p_current;
1787 }
1788 return p_closest;
1789}
1790
1791// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1792static 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)
1793{
1794 float dx = x4 - x1;
1795 float dy = y4 - y1;
1796 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1797 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1798 d2 = (d2 >= 0) ? d2 : -d2;
1799 d3 = (d3 >= 0) ? d3 : -d3;
1800 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1801 {
1802 ImVec2 p_current(x4, y4);
1803 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
1804 float dist2 = ImLengthSqr(lhs: p - p_line);
1805 if (dist2 < p_closest_dist2)
1806 {
1807 p_closest = p_line;
1808 p_closest_dist2 = dist2;
1809 }
1810 p_last = p_current;
1811 }
1812 else if (level < 10)
1813 {
1814 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
1815 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
1816 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
1817 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
1818 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
1819 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1820 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);
1821 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);
1822 }
1823}
1824
1825// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1826// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1827ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1828{
1829 IM_ASSERT(tess_tol > 0.0f);
1830 ImVec2 p_last = p1;
1831 ImVec2 p_closest;
1832 float p_closest_dist2 = FLT_MAX;
1833 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);
1834 return p_closest;
1835}
1836
1837ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1838{
1839 ImVec2 ap = p - a;
1840 ImVec2 ab_dir = b - a;
1841 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1842 if (dot < 0.0f)
1843 return a;
1844 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1845 if (dot > ab_len_sqr)
1846 return b;
1847 return a + ab_dir * dot / ab_len_sqr;
1848}
1849
1850bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1851{
1852 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1853 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1854 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1855 return ((b1 == b2) && (b2 == b3));
1856}
1857
1858void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1859{
1860 ImVec2 v0 = b - a;
1861 ImVec2 v1 = c - a;
1862 ImVec2 v2 = p - a;
1863 const float denom = v0.x * v1.y - v1.x * v0.y;
1864 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1865 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1866 out_u = 1.0f - out_v - out_w;
1867}
1868
1869ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1870{
1871 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1872 ImVec2 proj_bc = ImLineClosestPoint(a: b, b: c, p);
1873 ImVec2 proj_ca = ImLineClosestPoint(a: c, b: a, p);
1874 float dist2_ab = ImLengthSqr(lhs: p - proj_ab);
1875 float dist2_bc = ImLengthSqr(lhs: p - proj_bc);
1876 float dist2_ca = ImLengthSqr(lhs: p - proj_ca);
1877 float m = ImMin(lhs: dist2_ab, rhs: ImMin(lhs: dist2_bc, rhs: dist2_ca));
1878 if (m == dist2_ab)
1879 return proj_ab;
1880 if (m == dist2_bc)
1881 return proj_bc;
1882 return proj_ca;
1883}
1884
1885//-----------------------------------------------------------------------------
1886// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1887//-----------------------------------------------------------------------------
1888
1889// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1890int ImStricmp(const char* str1, const char* str2)
1891{
1892 int d;
1893 while ((d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; }
1894 return d;
1895}
1896
1897int ImStrnicmp(const char* str1, const char* str2, size_t count)
1898{
1899 int d = 0;
1900 while (count > 0 && (d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; count--; }
1901 return d;
1902}
1903
1904void ImStrncpy(char* dst, const char* src, size_t count)
1905{
1906 if (count < 1)
1907 return;
1908 if (count > 1)
1909 strncpy(dest: dst, src: src, n: count - 1);
1910 dst[count - 1] = 0;
1911}
1912
1913char* ImStrdup(const char* str)
1914{
1915 size_t len = strlen(s: str);
1916 void* buf = IM_ALLOC(len + 1);
1917 return (char*)memcpy(dest: buf, src: (const void*)str, n: len + 1);
1918}
1919
1920char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1921{
1922 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(s: dst) + 1;
1923 size_t src_size = strlen(s: src) + 1;
1924 if (dst_buf_size < src_size)
1925 {
1926 IM_FREE(dst);
1927 dst = (char*)IM_ALLOC(src_size);
1928 if (p_dst_size)
1929 *p_dst_size = src_size;
1930 }
1931 return (char*)memcpy(dest: dst, src: (const void*)src, n: src_size);
1932}
1933
1934const char* ImStrchrRange(const char* str, const char* str_end, char c)
1935{
1936 const char* p = (const char*)memchr(s: str, c: (int)c, n: str_end - str);
1937 return p;
1938}
1939
1940int ImStrlenW(const ImWchar* str)
1941{
1942 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
1943 int n = 0;
1944 while (*str++) n++;
1945 return n;
1946}
1947
1948// Find end-of-line. Return pointer will point to either first \n, either str_end.
1949const char* ImStreolRange(const char* str, const char* str_end)
1950{
1951 const char* p = (const char*)memchr(s: str, c: '\n', n: str_end - str);
1952 return p ? p : str_end;
1953}
1954
1955const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1956{
1957 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1958 buf_mid_line--;
1959 return buf_mid_line;
1960}
1961
1962const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1963{
1964 if (!needle_end)
1965 needle_end = needle + strlen(s: needle);
1966
1967 const char un0 = (char)ImToUpper(c: *needle);
1968 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1969 {
1970 if (ImToUpper(c: *haystack) == un0)
1971 {
1972 const char* b = needle + 1;
1973 for (const char* a = haystack + 1; b < needle_end; a++, b++)
1974 if (ImToUpper(c: *a) != ImToUpper(c: *b))
1975 break;
1976 if (b == needle_end)
1977 return haystack;
1978 }
1979 haystack++;
1980 }
1981 return NULL;
1982}
1983
1984// 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.
1985void ImStrTrimBlanks(char* buf)
1986{
1987 char* p = buf;
1988 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
1989 p++;
1990 char* p_start = p;
1991 while (*p != 0) // Find end of string
1992 p++;
1993 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
1994 p--;
1995 if (p_start != buf) // Copy memory if we had leading blanks
1996 memmove(dest: buf, src: p_start, n: p - p_start);
1997 buf[p - p_start] = 0; // Zero terminate
1998}
1999
2000const char* ImStrSkipBlank(const char* str)
2001{
2002 while (str[0] == ' ' || str[0] == '\t')
2003 str++;
2004 return str;
2005}
2006
2007// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2008// 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.
2009// B) When buf==NULL vsnprintf() will return the output size.
2010#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2011
2012// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2013// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2014// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2015// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2016#ifdef IMGUI_USE_STB_SPRINTF
2017#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2018#define STB_SPRINTF_IMPLEMENTATION
2019#endif
2020#ifdef IMGUI_STB_SPRINTF_FILENAME
2021#include IMGUI_STB_SPRINTF_FILENAME
2022#else
2023#include "stb_sprintf.h"
2024#endif
2025#endif // #ifdef IMGUI_USE_STB_SPRINTF
2026
2027#if defined(_MSC_VER) && !defined(vsnprintf)
2028#define vsnprintf _vsnprintf
2029#endif
2030
2031int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2032{
2033 va_list args;
2034 va_start(args, fmt);
2035#ifdef IMGUI_USE_STB_SPRINTF
2036 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2037#else
2038 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
2039#endif
2040 va_end(args);
2041 if (buf == NULL)
2042 return w;
2043 if (w == -1 || w >= (int)buf_size)
2044 w = (int)buf_size - 1;
2045 buf[w] = 0;
2046 return w;
2047}
2048
2049int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2050{
2051#ifdef IMGUI_USE_STB_SPRINTF
2052 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2053#else
2054 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
2055#endif
2056 if (buf == NULL)
2057 return w;
2058 if (w == -1 || w >= (int)buf_size)
2059 w = (int)buf_size - 1;
2060 buf[w] = 0;
2061 return w;
2062}
2063#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2064
2065void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2066{
2067 va_list args;
2068 va_start(args, fmt);
2069 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2070 va_end(args);
2071}
2072
2073// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2074// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2075// ImGuiTempBufferToken token;
2076// ImFormatStringToTempBuffer(token, ...);
2077void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2078{
2079 ImGuiContext& g = *GImGui;
2080 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2081 {
2082 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2083 if (buf == NULL)
2084 buf = "(null)";
2085 *out_buf = buf;
2086 if (out_buf_end) { *out_buf_end = buf + strlen(s: buf); }
2087 }
2088 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2089 {
2090 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2091 const char* buf = va_arg(args, const char*);
2092 if (buf == NULL)
2093 {
2094 buf = "(null)";
2095 buf_len = ImMin(lhs: buf_len, rhs: 6);
2096 }
2097 *out_buf = buf;
2098 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2099 }
2100 else
2101 {
2102 int buf_len = ImFormatStringV(buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size, fmt, args);
2103 *out_buf = g.TempBuffer.Data;
2104 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2105 }
2106}
2107
2108// CRC32 needs a 1KB lookup table (not cache friendly)
2109// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2110// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2111static const ImU32 GCrc32LookupTable[256] =
2112{
2113 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2114 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2115 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2116 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2117 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2118 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2119 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2120 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2121 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2122 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2123 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2124 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2125 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2126 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2127 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2128 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2129};
2130
2131// Known size hash
2132// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2133// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2134ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2135{
2136 ImU32 crc = ~seed;
2137 const unsigned char* data = (const unsigned char*)data_p;
2138 const ImU32* crc32_lut = GCrc32LookupTable;
2139 while (data_size-- != 0)
2140 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2141 return ~crc;
2142}
2143
2144// Zero-terminated string hash, with support for ### to reset back to seed value
2145// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2146// Because this syntax is rarely used we are optimizing for the common case.
2147// - If we reach ### in the string we discard the hash so far and reset to the seed.
2148// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2149// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2150ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2151{
2152 seed = ~seed;
2153 ImU32 crc = seed;
2154 const unsigned char* data = (const unsigned char*)data_p;
2155 const ImU32* crc32_lut = GCrc32LookupTable;
2156 if (data_size != 0)
2157 {
2158 while (data_size-- != 0)
2159 {
2160 unsigned char c = *data++;
2161 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2162 crc = seed;
2163 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2164 }
2165 }
2166 else
2167 {
2168 while (unsigned char c = *data++)
2169 {
2170 if (c == '#' && data[0] == '#' && data[1] == '#')
2171 crc = seed;
2172 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2173 }
2174 }
2175 return ~crc;
2176}
2177
2178//-----------------------------------------------------------------------------
2179// [SECTION] MISC HELPERS/UTILITIES (File functions)
2180//-----------------------------------------------------------------------------
2181
2182// Default file functions
2183#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2184
2185ImFileHandle ImFileOpen(const char* filename, const char* mode)
2186{
2187#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2188 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2189 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2190 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2191 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2192
2193 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2194 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2195 wchar_t local_temp_stack[FILENAME_MAX];
2196 ImVector<wchar_t> local_temp_heap;
2197 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2198 local_temp_heap.resize(filename_wsize + mode_wsize);
2199 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2200 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2201 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2202 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2203 return ::_wfopen(filename_wbuf, mode_wbuf);
2204#else
2205 return fopen(filename: filename, modes: mode);
2206#endif
2207}
2208
2209// 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.
2210bool ImFileClose(ImFileHandle f) { return fclose(stream: f) == 0; }
2211ImU64 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; }
2212ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(ptr: data, size: (size_t)sz, n: (size_t)count, stream: f); }
2213ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(ptr: data, size: (size_t)sz, n: (size_t)count, s: f); }
2214#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2215
2216// Helper: Load file content into memory
2217// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2218// This can't really be used with "rt" because fseek size won't match read size.
2219void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2220{
2221 IM_ASSERT(filename && mode);
2222 if (out_file_size)
2223 *out_file_size = 0;
2224
2225 ImFileHandle f;
2226 if ((f = ImFileOpen(filename, mode)) == NULL)
2227 return NULL;
2228
2229 size_t file_size = (size_t)ImFileGetSize(f);
2230 if (file_size == (size_t)-1)
2231 {
2232 ImFileClose(f);
2233 return NULL;
2234 }
2235
2236 void* file_data = IM_ALLOC(file_size + padding_bytes);
2237 if (file_data == NULL)
2238 {
2239 ImFileClose(f);
2240 return NULL;
2241 }
2242 if (ImFileRead(data: file_data, sz: 1, count: file_size, f) != file_size)
2243 {
2244 ImFileClose(f);
2245 IM_FREE(file_data);
2246 return NULL;
2247 }
2248 if (padding_bytes > 0)
2249 memset(s: (void*)(((char*)file_data) + file_size), c: 0, n: (size_t)padding_bytes);
2250
2251 ImFileClose(f);
2252 if (out_file_size)
2253 *out_file_size = file_size;
2254
2255 return file_data;
2256}
2257
2258//-----------------------------------------------------------------------------
2259// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2260//-----------------------------------------------------------------------------
2261
2262IM_MSVC_RUNTIME_CHECKS_OFF
2263
2264// Convert UTF-8 to 32-bit character, process single character input.
2265// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2266// We handle UTF-8 decoding error by skipping forward.
2267int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2268{
2269 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 };
2270 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2271 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2272 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2273 static const int shifte[] = { 0, 6, 4, 2, 0 };
2274 int len = lengths[*(const unsigned char*)in_text >> 3];
2275 int wanted = len + (len ? 0 : 1);
2276
2277 if (in_text_end == NULL)
2278 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2279
2280 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2281 // so it is fast even with excessive branching.
2282 unsigned char s[4];
2283 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2284 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2285 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2286 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2287
2288 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2289 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2290 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2291 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2292 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2293 *out_char >>= shiftc[len];
2294
2295 // Accumulate the various error conditions.
2296 int e = 0;
2297 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2298 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2299 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
2300 e |= (s[1] & 0xc0) >> 2;
2301 e |= (s[2] & 0xc0) >> 4;
2302 e |= (s[3] ) >> 6;
2303 e ^= 0x2a; // top two bits of each tail byte correct?
2304 e >>= shifte[len];
2305
2306 if (e)
2307 {
2308 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2309 // One byte is consumed in case of invalid first byte of in_text.
2310 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2311 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2312 wanted = ImMin(lhs: wanted, rhs: !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2313 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2314 }
2315
2316 return wanted;
2317}
2318
2319int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2320{
2321 ImWchar* buf_out = buf;
2322 ImWchar* buf_end = buf + buf_size;
2323 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2324 {
2325 unsigned int c;
2326 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2327 *buf_out++ = (ImWchar)c;
2328 }
2329 *buf_out = 0;
2330 if (in_text_remaining)
2331 *in_text_remaining = in_text;
2332 return (int)(buf_out - buf);
2333}
2334
2335int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2336{
2337 int char_count = 0;
2338 while ((!in_text_end || in_text < in_text_end) && *in_text)
2339 {
2340 unsigned int c;
2341 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2342 char_count++;
2343 }
2344 return char_count;
2345}
2346
2347// Based on stb_to_utf8() from github.com/nothings/stb/
2348static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2349{
2350 if (c < 0x80)
2351 {
2352 buf[0] = (char)c;
2353 return 1;
2354 }
2355 if (c < 0x800)
2356 {
2357 if (buf_size < 2) return 0;
2358 buf[0] = (char)(0xc0 + (c >> 6));
2359 buf[1] = (char)(0x80 + (c & 0x3f));
2360 return 2;
2361 }
2362 if (c < 0x10000)
2363 {
2364 if (buf_size < 3) return 0;
2365 buf[0] = (char)(0xe0 + (c >> 12));
2366 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2367 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2368 return 3;
2369 }
2370 if (c <= 0x10FFFF)
2371 {
2372 if (buf_size < 4) return 0;
2373 buf[0] = (char)(0xf0 + (c >> 18));
2374 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2375 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2376 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2377 return 4;
2378 }
2379 // Invalid code point, the max unicode is 0x10FFFF
2380 return 0;
2381}
2382
2383const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2384{
2385 int count = ImTextCharToUtf8_inline(buf: out_buf, buf_size: 5, c);
2386 out_buf[count] = 0;
2387 return out_buf;
2388}
2389
2390// Not optimal but we very rarely use this function.
2391int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2392{
2393 unsigned int unused = 0;
2394 return ImTextCharFromUtf8(out_char: &unused, in_text, in_text_end);
2395}
2396
2397static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2398{
2399 if (c < 0x80) return 1;
2400 if (c < 0x800) return 2;
2401 if (c < 0x10000) return 3;
2402 if (c <= 0x10FFFF) return 4;
2403 return 3;
2404}
2405
2406int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2407{
2408 char* buf_p = out_buf;
2409 const char* buf_end = out_buf + out_buf_size;
2410 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2411 {
2412 unsigned int c = (unsigned int)(*in_text++);
2413 if (c < 0x80)
2414 *buf_p++ = (char)c;
2415 else
2416 buf_p += ImTextCharToUtf8_inline(buf: buf_p, buf_size: (int)(buf_end - buf_p - 1), c);
2417 }
2418 *buf_p = 0;
2419 return (int)(buf_p - out_buf);
2420}
2421
2422int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2423{
2424 int bytes_count = 0;
2425 while ((!in_text_end || in_text < in_text_end) && *in_text)
2426 {
2427 unsigned int c = (unsigned int)(*in_text++);
2428 if (c < 0x80)
2429 bytes_count++;
2430 else
2431 bytes_count += ImTextCountUtf8BytesFromChar(c);
2432 }
2433 return bytes_count;
2434}
2435
2436const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2437{
2438 while (in_text_curr > in_text_start)
2439 {
2440 in_text_curr--;
2441 if ((*in_text_curr & 0xC0) != 0x80)
2442 return in_text_curr;
2443 }
2444 return in_text_start;
2445}
2446
2447int ImTextCountLines(const char* in_text, const char* in_text_end)
2448{
2449 if (in_text_end == NULL)
2450 in_text_end = in_text + strlen(s: in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2451 int count = 0;
2452 while (in_text < in_text_end)
2453 {
2454 const char* line_end = (const char*)memchr(s: in_text, c: '\n', n: in_text_end - in_text);
2455 in_text = line_end ? line_end + 1 : in_text_end;
2456 count++;
2457 }
2458 return count;
2459}
2460
2461IM_MSVC_RUNTIME_CHECKS_RESTORE
2462
2463//-----------------------------------------------------------------------------
2464// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2465// Note: The Convert functions are early design which are not consistent with other API.
2466//-----------------------------------------------------------------------------
2467
2468IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2469{
2470 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2471 int r = ImLerp(a: (int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2472 int g = ImLerp(a: (int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2473 int b = ImLerp(a: (int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2474 return IM_COL32(r, g, b, 0xFF);
2475}
2476
2477ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2478{
2479 float s = 1.0f / 255.0f;
2480 return ImVec4(
2481 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2482 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2483 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2484 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2485}
2486
2487ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2488{
2489 ImU32 out;
2490 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2491 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2492 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2493 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2494 return out;
2495}
2496
2497// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2498// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2499void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2500{
2501 float K = 0.f;
2502 if (g < b)
2503 {
2504 ImSwap(a&: g, b);
2505 K = -1.f;
2506 }
2507 if (r < g)
2508 {
2509 ImSwap(a&: r, b&: g);
2510 K = -2.f / 6.f - K;
2511 }
2512
2513 const float chroma = r - (g < b ? g : b);
2514 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2515 out_s = chroma / (r + 1e-20f);
2516 out_v = r;
2517}
2518
2519// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2520// also http://en.wikipedia.org/wiki/HSL_and_HSV
2521void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2522{
2523 if (s == 0.0f)
2524 {
2525 // gray
2526 out_r = out_g = out_b = v;
2527 return;
2528 }
2529
2530 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2531 int i = (int)h;
2532 float f = h - (float)i;
2533 float p = v * (1.0f - s);
2534 float q = v * (1.0f - s * f);
2535 float t = v * (1.0f - s * (1.0f - f));
2536
2537 switch (i)
2538 {
2539 case 0: out_r = v; out_g = t; out_b = p; break;
2540 case 1: out_r = q; out_g = v; out_b = p; break;
2541 case 2: out_r = p; out_g = v; out_b = t; break;
2542 case 3: out_r = p; out_g = q; out_b = v; break;
2543 case 4: out_r = t; out_g = p; out_b = v; break;
2544 case 5: default: out_r = v; out_g = p; out_b = q; break;
2545 }
2546}
2547
2548//-----------------------------------------------------------------------------
2549// [SECTION] ImGuiStorage
2550// Helper: Key->value storage
2551//-----------------------------------------------------------------------------
2552
2553// std::lower_bound but without the bullshit
2554ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2555{
2556 ImGuiStoragePair* in_p = in_begin;
2557 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2558 {
2559 size_t count2 = count >> 1;
2560 ImGuiStoragePair* mid = in_p + count2;
2561 if (mid->key < key)
2562 {
2563 in_p = ++mid;
2564 count -= count2 + 1;
2565 }
2566 else
2567 {
2568 count = count2;
2569 }
2570 }
2571 return in_p;
2572}
2573
2574IM_MSVC_RUNTIME_CHECKS_OFF
2575static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2576{
2577 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2578 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2579 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2580 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2581}
2582
2583// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2584void ImGuiStorage::BuildSortByKey()
2585{
2586 ImQsort(base: Data.Data, count: (size_t)Data.Size, size_of_element: sizeof(ImGuiStoragePair), compare_func: PairComparerByID);
2587}
2588
2589int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2590{
2591 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2592 if (it == Data.Data + Data.Size || it->key != key)
2593 return default_val;
2594 return it->val_i;
2595}
2596
2597bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2598{
2599 return GetInt(key, default_val: default_val ? 1 : 0) != 0;
2600}
2601
2602float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2603{
2604 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2605 if (it == Data.Data + Data.Size || it->key != key)
2606 return default_val;
2607 return it->val_f;
2608}
2609
2610void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2611{
2612 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2613 if (it == Data.Data + Data.Size || it->key != key)
2614 return NULL;
2615 return it->val_p;
2616}
2617
2618// 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.
2619int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2620{
2621 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2622 if (it == Data.Data + Data.Size || it->key != key)
2623 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2624 return &it->val_i;
2625}
2626
2627bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2628{
2629 return (bool*)GetIntRef(key, default_val: default_val ? 1 : 0);
2630}
2631
2632float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2633{
2634 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2635 if (it == Data.Data + Data.Size || it->key != key)
2636 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2637 return &it->val_f;
2638}
2639
2640void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2641{
2642 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2643 if (it == Data.Data + Data.Size || it->key != key)
2644 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2645 return &it->val_p;
2646}
2647
2648// 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)
2649void ImGuiStorage::SetInt(ImGuiID key, int val)
2650{
2651 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2652 if (it == Data.Data + Data.Size || it->key != key)
2653 Data.insert(it, v: ImGuiStoragePair(key, val));
2654 else
2655 it->val_i = val;
2656}
2657
2658void ImGuiStorage::SetBool(ImGuiID key, bool val)
2659{
2660 SetInt(key, val: val ? 1 : 0);
2661}
2662
2663void ImGuiStorage::SetFloat(ImGuiID key, float val)
2664{
2665 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2666 if (it == Data.Data + Data.Size || it->key != key)
2667 Data.insert(it, v: ImGuiStoragePair(key, val));
2668 else
2669 it->val_f = val;
2670}
2671
2672void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2673{
2674 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2675 if (it == Data.Data + Data.Size || it->key != key)
2676 Data.insert(it, v: ImGuiStoragePair(key, val));
2677 else
2678 it->val_p = val;
2679}
2680
2681void ImGuiStorage::SetAllInt(int v)
2682{
2683 for (int i = 0; i < Data.Size; i++)
2684 Data[i].val_i = v;
2685}
2686IM_MSVC_RUNTIME_CHECKS_RESTORE
2687
2688//-----------------------------------------------------------------------------
2689// [SECTION] ImGuiTextFilter
2690//-----------------------------------------------------------------------------
2691
2692// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2693ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2694{
2695 InputBuf[0] = 0;
2696 CountGrep = 0;
2697 if (default_filter)
2698 {
2699 ImStrncpy(dst: InputBuf, src: default_filter, IM_ARRAYSIZE(InputBuf));
2700 Build();
2701 }
2702}
2703
2704bool ImGuiTextFilter::Draw(const char* label, float width)
2705{
2706 if (width != 0.0f)
2707 ImGui::SetNextItemWidth(width);
2708 bool value_changed = ImGui::InputText(label, buf: InputBuf, IM_ARRAYSIZE(InputBuf));
2709 if (value_changed)
2710 Build();
2711 return value_changed;
2712}
2713
2714void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2715{
2716 out->resize(new_size: 0);
2717 const char* wb = b;
2718 const char* we = wb;
2719 while (we < e)
2720 {
2721 if (*we == separator)
2722 {
2723 out->push_back(v: ImGuiTextRange(wb, we));
2724 wb = we + 1;
2725 }
2726 we++;
2727 }
2728 if (wb != we)
2729 out->push_back(v: ImGuiTextRange(wb, we));
2730}
2731
2732void ImGuiTextFilter::Build()
2733{
2734 Filters.resize(new_size: 0);
2735 ImGuiTextRange input_range(InputBuf, InputBuf + strlen(s: InputBuf));
2736 input_range.split(separator: ',', out: &Filters);
2737
2738 CountGrep = 0;
2739 for (ImGuiTextRange& f : Filters)
2740 {
2741 while (f.b < f.e && ImCharIsBlankA(c: f.b[0]))
2742 f.b++;
2743 while (f.e > f.b && ImCharIsBlankA(c: f.e[-1]))
2744 f.e--;
2745 if (f.empty())
2746 continue;
2747 if (f.b[0] != '-')
2748 CountGrep += 1;
2749 }
2750}
2751
2752bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2753{
2754 if (Filters.Size == 0)
2755 return true;
2756
2757 if (text == NULL)
2758 text = text_end = "";
2759
2760 for (const ImGuiTextRange& f : Filters)
2761 {
2762 if (f.b == f.e)
2763 continue;
2764 if (f.b[0] == '-')
2765 {
2766 // Subtract
2767 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b + 1, needle_end: f.e) != NULL)
2768 return false;
2769 }
2770 else
2771 {
2772 // Grep
2773 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b, needle_end: f.e) != NULL)
2774 return true;
2775 }
2776 }
2777
2778 // Implicit * grep
2779 if (CountGrep == 0)
2780 return true;
2781
2782 return false;
2783}
2784
2785//-----------------------------------------------------------------------------
2786// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2787//-----------------------------------------------------------------------------
2788
2789// On some platform vsnprintf() takes va_list by reference and modifies it.
2790// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2791#ifndef va_copy
2792#if defined(__GNUC__) || defined(__clang__)
2793#define va_copy(dest, src) __builtin_va_copy(dest, src)
2794#else
2795#define va_copy(dest, src) (dest = src)
2796#endif
2797#endif
2798
2799char ImGuiTextBuffer::EmptyString[1] = { 0 };
2800
2801void ImGuiTextBuffer::append(const char* str, const char* str_end)
2802{
2803 int len = str_end ? (int)(str_end - str) : (int)strlen(s: str);
2804
2805 // Add zero-terminator the first time
2806 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2807 const int needed_sz = write_off + len;
2808 if (write_off + len >= Buf.Capacity)
2809 {
2810 int new_capacity = Buf.Capacity * 2;
2811 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
2812 }
2813
2814 Buf.resize(new_size: needed_sz);
2815 memcpy(dest: &Buf[write_off - 1], src: str, n: (size_t)len);
2816 Buf[write_off - 1 + len] = 0;
2817}
2818
2819void ImGuiTextBuffer::appendf(const char* fmt, ...)
2820{
2821 va_list args;
2822 va_start(args, fmt);
2823 appendfv(fmt, args);
2824 va_end(args);
2825}
2826
2827// Helper: Text buffer for logging/accumulating text
2828void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2829{
2830 va_list args_copy;
2831 va_copy(args_copy, args);
2832
2833 int len = ImFormatStringV(NULL, buf_size: 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2834 if (len <= 0)
2835 {
2836 va_end(args_copy);
2837 return;
2838 }
2839
2840 // Add zero-terminator the first time
2841 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2842 const int needed_sz = write_off + len;
2843 if (write_off + len >= Buf.Capacity)
2844 {
2845 int new_capacity = Buf.Capacity * 2;
2846 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
2847 }
2848
2849 Buf.resize(new_size: needed_sz);
2850 ImFormatStringV(buf: &Buf[write_off - 1], buf_size: (size_t)len + 1, fmt, args: args_copy);
2851 va_end(args_copy);
2852}
2853
2854void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2855{
2856 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2857 if (old_size == new_size)
2858 return;
2859 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2860 LineOffsets.push_back(v: EndOffset);
2861 const char* base_end = base + new_size;
2862 for (const char* p = base + old_size; (p = (const char*)memchr(s: p, c: '\n', n: base_end - p)) != 0; )
2863 if (++p < base_end) // Don't push a trailing offset on last \n
2864 LineOffsets.push_back(v: (int)(intptr_t)(p - base));
2865 EndOffset = ImMax(lhs: EndOffset, rhs: new_size);
2866}
2867
2868//-----------------------------------------------------------------------------
2869// [SECTION] ImGuiListClipper
2870//-----------------------------------------------------------------------------
2871
2872// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2873// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2874static bool GetSkipItemForListClipping()
2875{
2876 ImGuiContext& g = *GImGui;
2877 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2878}
2879
2880static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2881{
2882 if (ranges.Size - offset <= 1)
2883 return;
2884
2885 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2886 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2887 for (int i = offset; i < sort_end + offset; ++i)
2888 if (ranges[i].Min > ranges[i + 1].Min)
2889 ImSwap(a&: ranges[i], b&: ranges[i + 1]);
2890
2891 // Now fuse ranges together as much as possible.
2892 for (int i = 1 + offset; i < ranges.Size; i++)
2893 {
2894 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2895 if (ranges[i - 1].Max < ranges[i].Min)
2896 continue;
2897 ranges[i - 1].Min = ImMin(lhs: ranges[i - 1].Min, rhs: ranges[i].Min);
2898 ranges[i - 1].Max = ImMax(lhs: ranges[i - 1].Max, rhs: ranges[i].Max);
2899 ranges.erase(it: ranges.Data + i);
2900 i--;
2901 }
2902}
2903
2904static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2905{
2906 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2907 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2908 // 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?
2909 ImGuiContext& g = *GImGui;
2910 ImGuiWindow* window = g.CurrentWindow;
2911 float off_y = pos_y - window->DC.CursorPos.y;
2912 window->DC.CursorPos.y = pos_y;
2913 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: pos_y - g.Style.ItemSpacing.y);
2914 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.
2915 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.
2916 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2917 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
2918 if (ImGuiTable* table = g.CurrentTable)
2919 {
2920 if (table->IsInsideRow)
2921 ImGui::TableEndRow(table);
2922 table->RowPosY2 = window->DC.CursorPos.y;
2923 const int row_increase = (int)((off_y / line_height) + 0.5f);
2924 //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2925 table->RowBgColorCounter += row_increase;
2926 }
2927}
2928
2929ImGuiListClipper::ImGuiListClipper()
2930{
2931 memset(s: this, c: 0, n: sizeof(*this));
2932}
2933
2934ImGuiListClipper::~ImGuiListClipper()
2935{
2936 End();
2937}
2938
2939void ImGuiListClipper::Begin(int items_count, float items_height)
2940{
2941 if (Ctx == NULL)
2942 Ctx = ImGui::GetCurrentContext();
2943
2944 ImGuiContext& g = *Ctx;
2945 ImGuiWindow* window = g.CurrentWindow;
2946 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2947
2948 if (ImGuiTable* table = g.CurrentTable)
2949 if (table->IsInsideRow)
2950 ImGui::TableEndRow(table);
2951
2952 StartPosY = window->DC.CursorPos.y;
2953 ItemsHeight = items_height;
2954 ItemsCount = items_count;
2955 DisplayStart = -1;
2956 DisplayEnd = 0;
2957
2958 // Acquire temporary buffer
2959 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2960 g.ClipperTempData.resize(new_size: g.ClipperTempDataStacked, v: ImGuiListClipperData());
2961 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2962 data->Reset(clipper: this);
2963 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2964 TempData = data;
2965 StartSeekOffsetY = data->LossynessOffset;
2966}
2967
2968void ImGuiListClipper::End()
2969{
2970 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2971 {
2972 // 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.
2973 ImGuiContext& g = *Ctx;
2974 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2975 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2976 SeekCursorForItem(item_index: ItemsCount);
2977
2978 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2979 IM_ASSERT(data->ListClipper == this);
2980 data->StepNo = data->Ranges.Size;
2981 if (--g.ClipperTempDataStacked > 0)
2982 {
2983 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2984 data->ListClipper->TempData = data;
2985 }
2986 TempData = NULL;
2987 }
2988 ItemsCount = -1;
2989}
2990
2991void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2992{
2993 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2994 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2995 IM_ASSERT(item_begin <= item_end);
2996 if (item_begin < item_end)
2997 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: item_begin, max: item_end));
2998}
2999
3000// This is already called while stepping.
3001// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand.
3002void ImGuiListClipper::SeekCursorForItem(int item_n)
3003{
3004 // - Perform the add and multiply with double to allow seeking through larger ranges.
3005 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3006 // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
3007 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3008 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, line_height: ItemsHeight);
3009}
3010
3011static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3012{
3013 ImGuiContext& g = *clipper->Ctx;
3014 ImGuiWindow* window = g.CurrentWindow;
3015 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3016 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3017
3018 ImGuiTable* table = g.CurrentTable;
3019 if (table && table->IsInsideRow)
3020 ImGui::TableEndRow(table);
3021
3022 // No items
3023 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3024 return false;
3025
3026 // While we are in frozen row state, keep displaying items one by one, unclipped
3027 // FIXME: Could be stored as a table-agnostic state.
3028 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3029 {
3030 clipper->DisplayStart = data->ItemsFrozen;
3031 clipper->DisplayEnd = ImMin(lhs: data->ItemsFrozen + 1, rhs: clipper->ItemsCount);
3032 if (clipper->DisplayStart < clipper->DisplayEnd)
3033 data->ItemsFrozen++;
3034 return true;
3035 }
3036
3037 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3038 bool calc_clipping = false;
3039 if (data->StepNo == 0)
3040 {
3041 clipper->StartPosY = window->DC.CursorPos.y;
3042 if (clipper->ItemsHeight <= 0.0f)
3043 {
3044 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3045 data->Ranges.push_front(v: ImGuiListClipperRange::FromIndices(min: data->ItemsFrozen, max: data->ItemsFrozen + 1));
3046 clipper->DisplayStart = ImMax(lhs: data->Ranges[0].Min, rhs: data->ItemsFrozen);
3047 clipper->DisplayEnd = ImMin(lhs: data->Ranges[0].Max, rhs: clipper->ItemsCount);
3048 data->StepNo = 1;
3049 return true;
3050 }
3051 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3052 }
3053
3054 // Step 1: Let the clipper infer height from first range
3055 if (clipper->ItemsHeight <= 0.0f)
3056 {
3057 IM_ASSERT(data->StepNo == 1);
3058 if (table)
3059 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3060
3061 clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3062 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(f: clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(f: window->DC.CursorPos.y);
3063 if (affected_by_floating_point_precision)
3064 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3065 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3066 return false;
3067 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3068 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3069 }
3070
3071 // Step 0 or 1: Calculate the actual ranges of visible elements.
3072 const int already_submitted = clipper->DisplayEnd;
3073 if (calc_clipping)
3074 {
3075 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3076 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3077
3078 if (g.LogEnabled)
3079 {
3080 // If logging is active, do not perform any clipping
3081 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: 0, max: clipper->ItemsCount));
3082 }
3083 else
3084 {
3085 // Add range selected to be included for navigation
3086 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3087 if (is_nav_request)
3088 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringNoClipRect.Min.y, y2: g.NavScoringNoClipRect.Max.y, off_min: 0, off_max: 0));
3089 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3090 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: clipper->ItemsCount - 1, max: clipper->ItemsCount));
3091
3092 // Add focused/active item
3093 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, r: window->NavRectRel[0]);
3094 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3095 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));
3096
3097 // Add visible range
3098 float min_y = window->ClipRect.Min.y;
3099 float max_y = window->ClipRect.Max.y;
3100
3101 // Add box selection range
3102 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3103 if (bs->IsActive && bs->Window == window)
3104 {
3105 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3106 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3107 // As a workaround we currently half ItemSpacing worth on each side.
3108 min_y -= g.Style.ItemSpacing.y;
3109 max_y += g.Style.ItemSpacing.y;
3110
3111 // Box-select on 2D area requires different clipping.
3112 if (bs->UnclipMode)
3113 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: bs->UnclipRect.Min.y, y2: bs->UnclipRect.Max.y, off_min: 0, off_max: 0));
3114 }
3115
3116 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3117 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3118 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: min_y, y2: max_y, off_min, off_max));
3119 }
3120
3121 // Convert position ranges to item index ranges
3122 // - 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.
3123 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3124 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3125 for (ImGuiListClipperRange& range : data->Ranges)
3126 if (range.PosToIndexConvert)
3127 {
3128 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3129 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3130 range.Min = ImClamp(v: already_submitted + m1 + range.PosToIndexOffsetMin, mn: already_submitted, mx: clipper->ItemsCount - 1);
3131 range.Max = ImClamp(v: already_submitted + m2 + range.PosToIndexOffsetMax, mn: range.Min + 1, mx: clipper->ItemsCount);
3132 range.PosToIndexConvert = false;
3133 }
3134 ImGuiListClipper_SortAndFuseRanges(ranges&: data->Ranges, offset: data->StepNo);
3135 }
3136
3137 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3138 while (data->StepNo < data->Ranges.Size)
3139 {
3140 clipper->DisplayStart = ImMax(lhs: data->Ranges[data->StepNo].Min, rhs: already_submitted);
3141 clipper->DisplayEnd = ImMin(lhs: data->Ranges[data->StepNo].Max, rhs: clipper->ItemsCount);
3142 if (clipper->DisplayStart > already_submitted) //-V1051
3143 clipper->SeekCursorForItem(item_n: clipper->DisplayStart);
3144 data->StepNo++;
3145 if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3146 continue;
3147 return true;
3148 }
3149
3150 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3151 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3152 if (clipper->ItemsCount < INT_MAX)
3153 clipper->SeekCursorForItem(item_n: clipper->ItemsCount);
3154
3155 return false;
3156}
3157
3158bool ImGuiListClipper::Step()
3159{
3160 ImGuiContext& g = *Ctx;
3161 bool need_items_height = (ItemsHeight <= 0.0f);
3162 bool ret = ImGuiListClipper_StepInternal(clipper: this);
3163 if (ret && (DisplayStart == DisplayEnd))
3164 ret = false;
3165 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3166 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3167 if (need_items_height && ItemsHeight > 0.0f)
3168 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3169 if (ret)
3170 {
3171 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3172 }
3173 else
3174 {
3175 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3176 End();
3177 }
3178 return ret;
3179}
3180
3181//-----------------------------------------------------------------------------
3182// [SECTION] STYLING
3183//-----------------------------------------------------------------------------
3184
3185ImGuiStyle& ImGui::GetStyle()
3186{
3187 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3188 return GImGui->Style;
3189}
3190
3191ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3192{
3193 ImGuiStyle& style = GImGui->Style;
3194 ImVec4 c = style.Colors[idx];
3195 c.w *= style.Alpha * alpha_mul;
3196 return ColorConvertFloat4ToU32(in: c);
3197}
3198
3199ImU32 ImGui::GetColorU32(const ImVec4& col)
3200{
3201 ImGuiStyle& style = GImGui->Style;
3202 ImVec4 c = col;
3203 c.w *= style.Alpha;
3204 return ColorConvertFloat4ToU32(in: c);
3205}
3206
3207const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3208{
3209 ImGuiStyle& style = GImGui->Style;
3210 return style.Colors[idx];
3211}
3212
3213ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3214{
3215 ImGuiStyle& style = GImGui->Style;
3216 alpha_mul *= style.Alpha;
3217 if (alpha_mul >= 1.0f)
3218 return col;
3219 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3220 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3221 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3222}
3223
3224// 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
3225void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3226{
3227 ImGuiContext& g = *GImGui;
3228 ImGuiColorMod backup;
3229 backup.Col = idx;
3230 backup.BackupValue = g.Style.Colors[idx];
3231 g.ColorStack.push_back(v: backup);
3232 if (g.DebugFlashStyleColorIdx != idx)
3233 g.Style.Colors[idx] = ColorConvertU32ToFloat4(in: col);
3234}
3235
3236void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3237{
3238 ImGuiContext& g = *GImGui;
3239 ImGuiColorMod backup;
3240 backup.Col = idx;
3241 backup.BackupValue = g.Style.Colors[idx];
3242 g.ColorStack.push_back(v: backup);
3243 if (g.DebugFlashStyleColorIdx != idx)
3244 g.Style.Colors[idx] = col;
3245}
3246
3247void ImGui::PopStyleColor(int count)
3248{
3249 ImGuiContext& g = *GImGui;
3250 if (g.ColorStack.Size < count)
3251 {
3252 IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3253 count = g.ColorStack.Size;
3254 }
3255 while (count > 0)
3256 {
3257 ImGuiColorMod& backup = g.ColorStack.back();
3258 g.Style.Colors[backup.Col] = backup.BackupValue;
3259 g.ColorStack.pop_back();
3260 count--;
3261 }
3262}
3263
3264static const ImGuiDataVarInfo GStyleVarInfo[] =
3265{
3266 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3267 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3268 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3269 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3270 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3271 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3272 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3273 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3274 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3275 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3276 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3277 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3278 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3279 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3280 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3281 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3282 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3283 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3284 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3285 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3286 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3287 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3288 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3289 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3290 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3291 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3292 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3293 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3294 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3295 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3296 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3297 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3298 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3299};
3300
3301const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3302{
3303 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3304 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3305 return &GStyleVarInfo[idx];
3306}
3307
3308void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3309{
3310 ImGuiContext& g = *GImGui;
3311 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3312 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3313 {
3314 float* pvar = (float*)var_info->GetVarPtr(parent: &g.Style);
3315 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3316 *pvar = val;
3317 return;
3318 }
3319 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3320}
3321
3322void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3323{
3324 ImGuiContext& g = *GImGui;
3325 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3326 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3327 {
3328 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3329 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3330 *pvar = val;
3331 return;
3332 }
3333 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3334}
3335
3336void ImGui::PopStyleVar(int count)
3337{
3338 ImGuiContext& g = *GImGui;
3339 if (g.StyleVarStack.Size < count)
3340 {
3341 IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3342 count = g.StyleVarStack.Size;
3343 }
3344 while (count > 0)
3345 {
3346 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3347 ImGuiStyleMod& backup = g.StyleVarStack.back();
3348 const ImGuiDataVarInfo* info = GetStyleVarInfo(idx: backup.VarIdx);
3349 void* data = info->GetVarPtr(parent: &g.Style);
3350 if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3351 else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3352 g.StyleVarStack.pop_back();
3353 count--;
3354 }
3355}
3356
3357const char* ImGui::GetStyleColorName(ImGuiCol idx)
3358{
3359 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3360 switch (idx)
3361 {
3362 case ImGuiCol_Text: return "Text";
3363 case ImGuiCol_TextDisabled: return "TextDisabled";
3364 case ImGuiCol_WindowBg: return "WindowBg";
3365 case ImGuiCol_ChildBg: return "ChildBg";
3366 case ImGuiCol_PopupBg: return "PopupBg";
3367 case ImGuiCol_Border: return "Border";
3368 case ImGuiCol_BorderShadow: return "BorderShadow";
3369 case ImGuiCol_FrameBg: return "FrameBg";
3370 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3371 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3372 case ImGuiCol_TitleBg: return "TitleBg";
3373 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3374 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3375 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3376 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3377 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3378 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3379 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3380 case ImGuiCol_CheckMark: return "CheckMark";
3381 case ImGuiCol_SliderGrab: return "SliderGrab";
3382 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3383 case ImGuiCol_Button: return "Button";
3384 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3385 case ImGuiCol_ButtonActive: return "ButtonActive";
3386 case ImGuiCol_Header: return "Header";
3387 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3388 case ImGuiCol_HeaderActive: return "HeaderActive";
3389 case ImGuiCol_Separator: return "Separator";
3390 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3391 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3392 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3393 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3394 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3395 case ImGuiCol_TabHovered: return "TabHovered";
3396 case ImGuiCol_Tab: return "Tab";
3397 case ImGuiCol_TabSelected: return "TabSelected";
3398 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3399 case ImGuiCol_TabDimmed: return "TabDimmed";
3400 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3401 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3402 case ImGuiCol_PlotLines: return "PlotLines";
3403 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3404 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3405 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3406 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3407 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3408 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3409 case ImGuiCol_TableRowBg: return "TableRowBg";
3410 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3411 case ImGuiCol_TextLink: return "TextLink";
3412 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3413 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3414 case ImGuiCol_NavHighlight: return "NavHighlight";
3415 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3416 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3417 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3418 }
3419 IM_ASSERT(0);
3420 return "Unknown";
3421}
3422
3423
3424//-----------------------------------------------------------------------------
3425// [SECTION] RENDER HELPERS
3426// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3427// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3428// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3429//-----------------------------------------------------------------------------
3430
3431const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3432{
3433 const char* text_display_end = text;
3434 if (!text_end)
3435 text_end = (const char*)-1;
3436
3437 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3438 text_display_end++;
3439 return text_display_end;
3440}
3441
3442// Internal ImGui functions to render text
3443// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3444void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3445{
3446 ImGuiContext& g = *GImGui;
3447 ImGuiWindow* window = g.CurrentWindow;
3448
3449 // Hide anything after a '##' string
3450 const char* text_display_end;
3451 if (hide_text_after_hash)
3452 {
3453 text_display_end = FindRenderedTextEnd(text, text_end);
3454 }
3455 else
3456 {
3457 if (!text_end)
3458 text_end = text + strlen(s: text); // FIXME-OPT
3459 text_display_end = text_end;
3460 }
3461
3462 if (text != text_display_end)
3463 {
3464 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end);
3465 if (g.LogEnabled)
3466 LogRenderedText(ref_pos: &pos, text, text_end: text_display_end);
3467 }
3468}
3469
3470void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3471{
3472 ImGuiContext& g = *GImGui;
3473 ImGuiWindow* window = g.CurrentWindow;
3474
3475 if (!text_end)
3476 text_end = text + strlen(s: text); // FIXME-OPT
3477
3478 if (text != text_end)
3479 {
3480 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end, wrap_width);
3481 if (g.LogEnabled)
3482 LogRenderedText(ref_pos: &pos, text, text_end);
3483 }
3484}
3485
3486// Default clip_rect uses (pos_min,pos_max)
3487// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3488// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3489// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3490// better advantage of the render function taking size into account for coarse clipping.
3491void 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)
3492{
3493 // Perform CPU side clipping for single clipped element to avoid using scissor state
3494 ImVec2 pos = pos_min;
3495 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);
3496
3497 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3498 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3499 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3500 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3501 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3502
3503 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3504 if (align.x > 0.0f) pos.x = ImMax(lhs: pos.x, rhs: pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3505 if (align.y > 0.0f) pos.y = ImMax(lhs: pos.y, rhs: pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3506
3507 // Render
3508 if (need_clipping)
3509 {
3510 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3511 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);
3512 }
3513 else
3514 {
3515 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);
3516 }
3517}
3518
3519void 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)
3520{
3521 // Hide anything after a '##' string
3522 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3523 const int text_len = (int)(text_display_end - text);
3524 if (text_len == 0)
3525 return;
3526
3527 ImGuiContext& g = *GImGui;
3528 ImGuiWindow* window = g.CurrentWindow;
3529 RenderTextClippedEx(draw_list: window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3530 if (g.LogEnabled)
3531 LogRenderedText(ref_pos: &pos_min, text, text_end: text_display_end);
3532}
3533
3534// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3535// 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.
3536// 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.
3537void 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)
3538{
3539 ImGuiContext& g = *GImGui;
3540 if (text_end_full == NULL)
3541 text_end_full = FindRenderedTextEnd(text);
3542 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);
3543
3544 //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));
3545 //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));
3546 //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3547 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3548 if (text_size.x > pos_max.x - pos_min.x)
3549 {
3550 // Hello wo...
3551 // | | |
3552 // min max ellipsis_max
3553 // <-> this is generally some padding value
3554
3555 const ImFont* font = draw_list->_Data->Font;
3556 const float font_size = draw_list->_Data->FontSize;
3557 const float font_scale = draw_list->_Data->FontScale;
3558 const char* text_end_ellipsis = NULL;
3559 const float ellipsis_width = font->EllipsisWidth * font_scale;
3560
3561 // We can now claim the space between pos_max.x and ellipsis_max.x
3562 const float text_avail_width = ImMax(lhs: (ImMax(lhs: pos_max.x, rhs: ellipsis_max_x) - ellipsis_width) - pos_min.x, rhs: 1.0f);
3563 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;
3564 if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3565 {
3566 // Always display at least 1 character if there's no room for character + ellipsis
3567 text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(in_text: text, in_text_end: text_end_full);
3568 text_size_clipped_x = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text, text_end: text_end_ellipsis).x;
3569 }
3570 while (text_end_ellipsis > text && ImCharIsBlankA(c: text_end_ellipsis[-1]))
3571 {
3572 // 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)
3573 text_end_ellipsis--;
3574 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
3575 }
3576
3577 // Render text, render ellipsis
3578 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));
3579 ImVec2 ellipsis_pos = ImTrunc(v: ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3580 if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3581 for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3582 font->RenderChar(draw_list, size: font_size, pos: ellipsis_pos, col: GetColorU32(idx: ImGuiCol_Text), c: font->EllipsisChar);
3583 }
3584 else
3585 {
3586 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));
3587 }
3588
3589 if (g.LogEnabled)
3590 LogRenderedText(ref_pos: &pos_min, text, text_end: text_end_full);
3591}
3592
3593// Render a rectangle shaped with optional rounding and borders
3594void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3595{
3596 ImGuiContext& g = *GImGui;
3597 ImGuiWindow* window = g.CurrentWindow;
3598 window->DrawList->AddRectFilled(p_min, p_max, col: fill_col, rounding);
3599 const float border_size = g.Style.FrameBorderSize;
3600 if (border && border_size > 0.0f)
3601 {
3602 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);
3603 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3604 }
3605}
3606
3607void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3608{
3609 ImGuiContext& g = *GImGui;
3610 ImGuiWindow* window = g.CurrentWindow;
3611 const float border_size = g.Style.FrameBorderSize;
3612 if (border_size > 0.0f)
3613 {
3614 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);
3615 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3616 }
3617}
3618
3619void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3620{
3621 ImGuiContext& g = *GImGui;
3622 if (id != g.NavId)
3623 return;
3624 if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3625 return;
3626 ImGuiWindow* window = g.CurrentWindow;
3627 if (window->DC.NavHideHighlightOneFrame)
3628 return;
3629
3630 float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3631 ImRect display_rect = bb;
3632 display_rect.ClipWith(r: window->ClipRect);
3633 const float thickness = 2.0f;
3634 if (flags & ImGuiNavHighlightFlags_Compact)
3635 {
3636 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavHighlight), rounding, flags: 0, thickness);
3637 }
3638 else
3639 {
3640 const float distance = 3.0f + thickness * 0.5f;
3641 display_rect.Expand(amount: ImVec2(distance, distance));
3642 bool fully_visible = window->ClipRect.Contains(r: display_rect);
3643 if (!fully_visible)
3644 window->DrawList->PushClipRect(clip_rect_min: display_rect.Min, clip_rect_max: display_rect.Max);
3645 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavHighlight), rounding, flags: 0, thickness);
3646 if (!fully_visible)
3647 window->DrawList->PopClipRect();
3648 }
3649}
3650
3651void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3652{
3653 ImGuiContext& g = *GImGui;
3654 IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3655 ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3656 for (ImGuiViewportP* viewport : g.Viewports)
3657 {
3658 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3659 ImVec2 offset, size, uv[4];
3660 if (!font_atlas->GetMouseCursorTexData(cursor: mouse_cursor, out_offset: &offset, out_size: &size, out_uv_border: &uv[0], out_uv_fill: &uv[2]))
3661 continue;
3662 const ImVec2 pos = base_pos - offset;
3663 const float scale = base_scale;
3664 if (!viewport->GetMainRect().Overlaps(r: ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3665 continue;
3666 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3667 ImTextureID tex_id = font_atlas->TexID;
3668 draw_list->PushTextureID(texture_id: tex_id);
3669 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);
3670 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);
3671 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);
3672 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);
3673 draw_list->PopTextureID();
3674 }
3675}
3676
3677//-----------------------------------------------------------------------------
3678// [SECTION] INITIALIZATION, SHUTDOWN
3679//-----------------------------------------------------------------------------
3680
3681// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3682// 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
3683ImGuiContext* ImGui::GetCurrentContext()
3684{
3685 return GImGui;
3686}
3687
3688void ImGui::SetCurrentContext(ImGuiContext* ctx)
3689{
3690#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3691 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3692#else
3693 GImGui = ctx;
3694#endif
3695}
3696
3697void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3698{
3699 GImAllocatorAllocFunc = alloc_func;
3700 GImAllocatorFreeFunc = free_func;
3701 GImAllocatorUserData = user_data;
3702}
3703
3704// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3705void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3706{
3707 *p_alloc_func = GImAllocatorAllocFunc;
3708 *p_free_func = GImAllocatorFreeFunc;
3709 *p_user_data = GImAllocatorUserData;
3710}
3711
3712ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3713{
3714 ImGuiContext* prev_ctx = GetCurrentContext();
3715 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3716 SetCurrentContext(ctx);
3717 Initialize();
3718 if (prev_ctx != NULL)
3719 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3720 return ctx;
3721}
3722
3723void ImGui::DestroyContext(ImGuiContext* ctx)
3724{
3725 ImGuiContext* prev_ctx = GetCurrentContext();
3726 if (ctx == NULL) //-V1051
3727 ctx = prev_ctx;
3728 SetCurrentContext(ctx);
3729 Shutdown();
3730 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3731 IM_DELETE(p: ctx);
3732}
3733
3734// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation.
3735static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3736{
3737 { .Key: ImGuiLocKey_VersionStr, .Text: "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3738 { .Key: ImGuiLocKey_TableSizeOne, .Text: "Size column to fit###SizeOne" },
3739 { .Key: ImGuiLocKey_TableSizeAllFit, .Text: "Size all columns to fit###SizeAll" },
3740 { .Key: ImGuiLocKey_TableSizeAllDefault, .Text: "Size all columns to default###SizeAll" },
3741 { .Key: ImGuiLocKey_TableResetOrder, .Text: "Reset order###ResetOrder" },
3742 { .Key: ImGuiLocKey_WindowingMainMenuBar, .Text: "(Main menu bar)" },
3743 { .Key: ImGuiLocKey_WindowingPopup, .Text: "(Popup)" },
3744 { .Key: ImGuiLocKey_WindowingUntitled, .Text: "(Untitled)" },
3745 { .Key: ImGuiLocKey_CopyLink, .Text: "Copy Link###CopyLink" },
3746};
3747
3748void ImGui::Initialize()
3749{
3750 ImGuiContext& g = *GImGui;
3751 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3752
3753 // Add .ini handle for ImGuiWindow and ImGuiTable types
3754 {
3755 ImGuiSettingsHandler ini_handler;
3756 ini_handler.TypeName = "Window";
3757 ini_handler.TypeHash = ImHashStr(data_p: "Window");
3758 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3759 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3760 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3761 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3762 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3763 AddSettingsHandler(handler: &ini_handler);
3764 }
3765 TableSettingsAddSettingsHandler();
3766
3767 // Setup default localization table
3768 LocalizeRegisterEntries(entries: GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3769
3770 // Setup default platform clipboard/IME handlers.
3771 g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
3772 g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3773 g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3774 g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl;
3775 g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl;
3776
3777 // Create default viewport
3778 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3779 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3780 g.Viewports.push_back(v: viewport);
3781 g.TempBuffer.resize(new_size: 1024 * 3 + 1, v: 0);
3782
3783 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3784 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3785 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3786 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3787 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3788 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3789 g.KeysMayBeCharInput.SetBit(key);
3790
3791#ifdef IMGUI_HAS_DOCK
3792#endif
3793
3794 g.Initialized = true;
3795}
3796
3797// This function is merely here to free heap allocations.
3798void ImGui::Shutdown()
3799{
3800 ImGuiContext& g = *GImGui;
3801 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3802 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3803
3804 // 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)
3805 if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3806 {
3807 g.IO.Fonts->Locked = false;
3808 IM_DELETE(p: g.IO.Fonts);
3809 }
3810 g.IO.Fonts = NULL;
3811 g.DrawListSharedData.TempBuffer.clear();
3812
3813 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3814 if (!g.Initialized)
3815 return;
3816
3817 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3818 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3819 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
3820
3821 CallContextHooks(context: &g, type: ImGuiContextHookType_Shutdown);
3822
3823 // Clear everything else
3824 g.Windows.clear_delete();
3825 g.WindowsFocusOrder.clear();
3826 g.WindowsTempSortBuffer.clear();
3827 g.CurrentWindow = NULL;
3828 g.CurrentWindowStack.clear();
3829 g.WindowsById.Clear();
3830 g.NavWindow = NULL;
3831 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3832 g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3833 g.MovingWindow = NULL;
3834
3835 g.KeysRoutingTable.Clear();
3836
3837 g.ColorStack.clear();
3838 g.StyleVarStack.clear();
3839 g.FontStack.clear();
3840 g.OpenPopupStack.clear();
3841 g.BeginPopupStack.clear();
3842 g.TreeNodeStack.clear();
3843
3844 g.Viewports.clear_delete();
3845
3846 g.TabBars.Clear();
3847 g.CurrentTabBarStack.clear();
3848 g.ShrinkWidthBuffer.clear();
3849
3850 g.ClipperTempData.clear_destruct();
3851
3852 g.Tables.Clear();
3853 g.TablesTempData.clear_destruct();
3854 g.DrawChannelsTempMergeBuffer.clear();
3855
3856 g.MultiSelectStorage.Clear();
3857 g.MultiSelectTempData.clear_destruct();
3858
3859 g.ClipboardHandlerData.clear();
3860 g.MenusIdSubmittedThisFrame.clear();
3861 g.InputTextState.ClearFreeMemory();
3862 g.InputTextDeactivatedState.ClearFreeMemory();
3863
3864 g.SettingsWindows.clear();
3865 g.SettingsHandlers.clear();
3866
3867 if (g.LogFile)
3868 {
3869#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3870 if (g.LogFile != stdout)
3871#endif
3872 ImFileClose(f: g.LogFile);
3873 g.LogFile = NULL;
3874 }
3875 g.LogBuffer.clear();
3876 g.DebugLogBuf.clear();
3877 g.DebugLogIndex.clear();
3878
3879 g.Initialized = false;
3880}
3881
3882// No specific ordering/dependency support, will see as needed
3883ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3884{
3885 ImGuiContext& g = *ctx;
3886 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3887 g.Hooks.push_back(v: *hook);
3888 g.Hooks.back().HookId = ++g.HookIdNext;
3889 return g.HookIdNext;
3890}
3891
3892// Deferred removal, avoiding issue with changing vector while iterating it
3893void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3894{
3895 ImGuiContext& g = *ctx;
3896 IM_ASSERT(hook_id != 0);
3897 for (ImGuiContextHook& hook : g.Hooks)
3898 if (hook.HookId == hook_id)
3899 hook.Type = ImGuiContextHookType_PendingRemoval_;
3900}
3901
3902// Call context hooks (used by e.g. test engine)
3903// We assume a small number of hooks so all stored in same array
3904void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3905{
3906 ImGuiContext& g = *ctx;
3907 for (ImGuiContextHook& hook : g.Hooks)
3908 if (hook.Type == hook_type)
3909 hook.Callback(&g, &hook);
3910}
3911
3912
3913//-----------------------------------------------------------------------------
3914// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3915//-----------------------------------------------------------------------------
3916
3917// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3918ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3919{
3920 memset(s: this, c: 0, n: sizeof(*this));
3921 Ctx = ctx;
3922 Name = ImStrdup(str: name);
3923 NameBufLen = (int)strlen(s: name) + 1;
3924 ID = ImHashStr(data_p: name);
3925 IDStack.push_back(v: ID);
3926 MoveId = GetID(str: "#MOVE");
3927 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3928 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3929 AutoFitFramesX = AutoFitFramesY = -1;
3930 AutoPosLastDirection = ImGuiDir_None;
3931 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = 0;
3932 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3933 LastFrameActive = -1;
3934 LastTimeActive = -1.0f;
3935 FontWindowScale = 1.0f;
3936 SettingsOffset = -1;
3937 DrawList = &DrawListInst;
3938 DrawList->_Data = &Ctx->DrawListSharedData;
3939 DrawList->_OwnerName = Name;
3940 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3941}
3942
3943ImGuiWindow::~ImGuiWindow()
3944{
3945 IM_ASSERT(DrawList == &DrawListInst);
3946 IM_DELETE(p: Name);
3947 ColumnsStorage.clear_destruct();
3948}
3949
3950static void SetCurrentWindow(ImGuiWindow* window)
3951{
3952 ImGuiContext& g = *GImGui;
3953 g.CurrentWindow = window;
3954 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(n: window->DC.CurrentTableIdx) : NULL;
3955 g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking
3956 if (window)
3957 {
3958 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3959 g.FontScale = g.FontSize / g.Font->FontSize;
3960 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3961 }
3962}
3963
3964void ImGui::GcCompactTransientMiscBuffers()
3965{
3966 ImGuiContext& g = *GImGui;
3967 g.ItemFlagsStack.clear();
3968 g.GroupStack.clear();
3969 g.MultiSelectTempDataStacked = 0;
3970 g.MultiSelectTempData.clear_destruct();
3971 TableGcCompactSettings();
3972}
3973
3974// Free up/compact internal window buffers, we can use this when a window becomes unused.
3975// Not freed:
3976// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3977// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3978void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3979{
3980 window->MemoryCompacted = true;
3981 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3982 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3983 window->IDStack.clear();
3984 window->DrawList->_ClearFreeMemory();
3985 window->DC.ChildWindows.clear();
3986 window->DC.ItemWidthStack.clear();
3987 window->DC.TextWrapPosStack.clear();
3988}
3989
3990void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3991{
3992 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3993 // The other buffers tends to amortize much faster.
3994 window->MemoryCompacted = false;
3995 window->DrawList->IdxBuffer.reserve(new_capacity: window->MemoryDrawListIdxCapacity);
3996 window->DrawList->VtxBuffer.reserve(new_capacity: window->MemoryDrawListVtxCapacity);
3997 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3998}
3999
4000void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4001{
4002 ImGuiContext& g = *GImGui;
4003
4004 // Clear previous active id
4005 if (g.ActiveId != 0)
4006 {
4007 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4008 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4009 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4010 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4011 {
4012 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4013 g.MovingWindow = NULL;
4014 }
4015
4016 // This could be written in a more general way (e.g associate a hook to ActiveId),
4017 // but since this is currently quite an exception we'll leave it as is.
4018 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4019 if (g.InputTextState.ID == g.ActiveId)
4020 InputTextDeactivateHook(id: g.ActiveId);
4021 }
4022
4023 // Set active id
4024 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4025 if (g.ActiveIdIsJustActivated)
4026 {
4027 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 : "");
4028 g.ActiveIdTimer = 0.0f;
4029 g.ActiveIdHasBeenPressedBefore = false;
4030 g.ActiveIdHasBeenEditedBefore = false;
4031 g.ActiveIdMouseButton = -1;
4032 if (id != 0)
4033 {
4034 g.LastActiveId = id;
4035 g.LastActiveIdTimer = 0.0f;
4036 }
4037 }
4038 g.ActiveId = id;
4039 g.ActiveIdAllowOverlap = false;
4040 g.ActiveIdNoClearOnFocusLoss = false;
4041 g.ActiveIdWindow = window;
4042 g.ActiveIdHasBeenEditedThisFrame = false;
4043 g.ActiveIdFromShortcut = false;
4044 if (id)
4045 {
4046 g.ActiveIdIsAlive = id;
4047 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4048 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4049 }
4050
4051 // Clear declaration of inputs claimed by the widget
4052 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4053 g.ActiveIdUsingNavDirMask = 0x00;
4054 g.ActiveIdUsingAllKeyboardKeys = false;
4055}
4056
4057void ImGui::ClearActiveID()
4058{
4059 SetActiveID(id: 0, NULL); // g.ActiveId = 0;
4060}
4061
4062void ImGui::SetHoveredID(ImGuiID id)
4063{
4064 ImGuiContext& g = *GImGui;
4065 g.HoveredId = id;
4066 g.HoveredIdAllowOverlap = false;
4067 if (id != 0 && g.HoveredIdPreviousFrame != id)
4068 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4069}
4070
4071ImGuiID ImGui::GetHoveredID()
4072{
4073 ImGuiContext& g = *GImGui;
4074 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4075}
4076
4077void ImGui::MarkItemEdited(ImGuiID id)
4078{
4079 // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4080 // 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.
4081 ImGuiContext& g = *GImGui;
4082 if (g.LockMarkEdited > 0)
4083 return;
4084 if (g.ActiveId == id || g.ActiveId == 0)
4085 {
4086 g.ActiveIdHasBeenEditedThisFrame = true;
4087 g.ActiveIdHasBeenEditedBefore = true;
4088 }
4089
4090 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4091 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4092 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4093
4094 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4095 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4096}
4097
4098bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4099{
4100 // An active popup disable hovering on other windows (apart from its own children)
4101 // FIXME-OPT: This could be cached/stored within the window.
4102 ImGuiContext& g = *GImGui;
4103 if (g.NavWindow)
4104 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
4105 if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
4106 {
4107 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4108 // NB: The 'else' is important because Modal windows are also Popups.
4109 bool want_inhibit = false;
4110 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4111 want_inhibit = true;
4112 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4113 want_inhibit = true;
4114
4115 // Inhibit hover unless the window is within the stack of our modal/popup
4116 if (want_inhibit)
4117 if (!IsWindowWithinBeginStackOf(window: window->RootWindow, potential_parent: focused_root_window))
4118 return false;
4119 }
4120 return true;
4121}
4122
4123static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4124{
4125 ImGuiContext& g = *GImGui;
4126 if (flags & ImGuiHoveredFlags_DelayNormal)
4127 return g.Style.HoverDelayNormal;
4128 if (flags & ImGuiHoveredFlags_DelayShort)
4129 return g.Style.HoverDelayShort;
4130 return 0.0f;
4131}
4132
4133static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4134{
4135 // Allow instance flags to override shared flags
4136 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4137 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4138 return user_flags | shared_flags;
4139}
4140
4141// This is roughly matching the behavior of internal-facing ItemHoverable()
4142// - 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()
4143// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4144bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4145{
4146 ImGuiContext& g = *GImGui;
4147 ImGuiWindow* window = g.CurrentWindow;
4148 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4149
4150 if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4151 {
4152 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4153 return false;
4154 if (!IsItemFocused())
4155 return false;
4156
4157 if (flags & ImGuiHoveredFlags_ForTooltip)
4158 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipNav);
4159 }
4160 else
4161 {
4162 // Test for bounding box overlap, as updated as ItemAdd()
4163 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4164 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4165 return false;
4166
4167 if (flags & ImGuiHoveredFlags_ForTooltip)
4168 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
4169
4170 IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0); // Flags not supported by this function
4171
4172 // Done with rectangle culling so we can perform heavier checks now
4173 // Test if we are hovering the right window (our window could be behind another window)
4174 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4175 // [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
4176 // 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
4177 // the test that has been running for a long while.
4178 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4179 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4180 return false;
4181
4182 // Test if another item is active (e.g. being dragged)
4183 const ImGuiID id = g.LastItemData.ID;
4184 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4185 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
4186 return false;
4187
4188 // Test if interactions on this window are blocked by an active popup or modal.
4189 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4190 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4191 return false;
4192
4193 // Test if the item is disabled
4194 if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4195 return false;
4196
4197 // Special handling for calling after Begin() which represent the title bar or tab.
4198 // When the window is skipped/collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
4199 if (id == window->MoveId && window->WriteAccessed)
4200 return false;
4201
4202 // Test if using AllowOverlap and overlapped
4203 if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4204 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4205 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4206 return false;
4207 }
4208
4209 // Handle hover delay
4210 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4211 const float delay = CalcDelayFromHoveredFlags(flags);
4212 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4213 {
4214 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(r_abs: g.LastItemData.Rect);
4215 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4216 g.HoverItemDelayTimer = 0.0f;
4217 g.HoverItemDelayId = hover_delay_id;
4218
4219 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4220 // but once unlocked on a given item we also moving.
4221 //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); }
4222 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4223 return false;
4224
4225 if (g.HoverItemDelayTimer < delay)
4226 return false;
4227 }
4228
4229 return true;
4230}
4231
4232// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4233// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4234// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4235// If you used this in your legacy/custom widgets code:
4236// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4237// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4238bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4239{
4240 ImGuiContext& g = *GImGui;
4241 ImGuiWindow* window = g.CurrentWindow;
4242 if (g.HoveredWindow != window)
4243 return false;
4244 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
4245 return false;
4246
4247 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4248 return false;
4249 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4250 if (!g.ActiveIdFromShortcut)
4251 return false;
4252
4253 // Done with rectangle culling so we can perform heavier checks now.
4254 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, flags: ImGuiHoveredFlags_None))
4255 {
4256 g.HoveredIdIsDisabled = true;
4257 return false;
4258 }
4259
4260 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4261 // hover test in widgets code. We could also decide to split this function is two.
4262 if (id != 0)
4263 {
4264 // Drag source doesn't report as hovered
4265 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4266 return false;
4267
4268 SetHoveredID(id);
4269
4270 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4271 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4272 if (item_flags & ImGuiItemFlags_AllowOverlap)
4273 {
4274 g.HoveredIdAllowOverlap = true;
4275 if (g.HoveredIdPreviousFrame != id)
4276 return false;
4277 }
4278
4279 // Display shortcut (only works with mouse)
4280 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4281 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
4282 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4283 SetTooltip("%s", GetKeyChordName(key_chord: g.LastItemData.Shortcut));
4284 }
4285
4286 // When disabled we'll return false but still set HoveredId
4287 if (item_flags & ImGuiItemFlags_Disabled)
4288 {
4289 // Release active id if turning disabled
4290 if (g.ActiveId == id && id != 0)
4291 ClearActiveID();
4292 g.HoveredIdIsDisabled = true;
4293 return false;
4294 }
4295
4296#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4297 if (id != 0)
4298 {
4299 // [DEBUG] Item Picker tool!
4300 // We perform the check here because reaching is path is rare (1~ time a frame),
4301 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4302 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4303 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4304 GetForegroundDrawList()->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
4305 if (g.DebugItemPickerBreakId == id)
4306 IM_DEBUG_BREAK();
4307 }
4308#endif
4309
4310 if (g.NavDisableMouseHover)
4311 return false;
4312
4313 return true;
4314}
4315
4316// FIXME: This is inlined/duplicated in ItemAdd()
4317// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4318bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4319{
4320 ImGuiContext& g = *GImGui;
4321 ImGuiWindow* window = g.CurrentWindow;
4322 if (!bb.Overlaps(r: window->ClipRect))
4323 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4324 if (!g.ItemUnclipByLog)
4325 return true;
4326 return false;
4327}
4328
4329// This is also inlined in ItemAdd()
4330// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4331void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4332{
4333 ImGuiContext& g = *GImGui;
4334 g.LastItemData.ID = item_id;
4335 g.LastItemData.InFlags = in_flags;
4336 g.LastItemData.StatusFlags = item_flags;
4337 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4338}
4339
4340float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4341{
4342 if (wrap_pos_x < 0.0f)
4343 return 0.0f;
4344
4345 ImGuiContext& g = *GImGui;
4346 ImGuiWindow* window = g.CurrentWindow;
4347 if (wrap_pos_x == 0.0f)
4348 {
4349 // We could decide to setup a default wrapping max point for auto-resizing windows,
4350 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4351 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4352 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4353 //else
4354 wrap_pos_x = window->WorkRect.Max.x;
4355 }
4356 else if (wrap_pos_x > 0.0f)
4357 {
4358 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4359 }
4360
4361 return ImMax(lhs: wrap_pos_x - pos.x, rhs: 1.0f);
4362}
4363
4364// IM_ALLOC() == ImGui::MemAlloc()
4365void* ImGui::MemAlloc(size_t size)
4366{
4367 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4368#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4369 if (ImGuiContext* ctx = GImGui)
4370 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size);
4371#endif
4372 return ptr;
4373}
4374
4375// IM_FREE() == ImGui::MemFree()
4376void ImGui::MemFree(void* ptr)
4377{
4378#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4379 if (ptr != NULL)
4380 if (ImGuiContext* ctx = GImGui)
4381 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size: (size_t)-1);
4382#endif
4383 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4384}
4385
4386// 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"
4387void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4388{
4389 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4390 IM_UNUSED(ptr);
4391 if (entry->FrameCount != frame_count)
4392 {
4393 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4394 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4395 entry->FrameCount = frame_count;
4396 entry->AllocCount = entry->FreeCount = 0;
4397 }
4398 if (size != (size_t)-1)
4399 {
4400 entry->AllocCount++;
4401 info->TotalAllocCount++;
4402 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4403 }
4404 else
4405 {
4406 entry->FreeCount++;
4407 info->TotalFreeCount++;
4408 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4409 }
4410}
4411
4412const char* ImGui::GetClipboardText()
4413{
4414 ImGuiContext& g = *GImGui;
4415 return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4416}
4417
4418void ImGui::SetClipboardText(const char* text)
4419{
4420 ImGuiContext& g = *GImGui;
4421 if (g.IO.SetClipboardTextFn)
4422 g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4423}
4424
4425const char* ImGui::GetVersion()
4426{
4427 return IMGUI_VERSION;
4428}
4429
4430ImGuiIO& ImGui::GetIO()
4431{
4432 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4433 return GImGui->IO;
4434}
4435
4436// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4437ImDrawData* ImGui::GetDrawData()
4438{
4439 ImGuiContext& g = *GImGui;
4440 ImGuiViewportP* viewport = g.Viewports[0];
4441 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4442}
4443
4444double ImGui::GetTime()
4445{
4446 return GImGui->Time;
4447}
4448
4449int ImGui::GetFrameCount()
4450{
4451 return GImGui->FrameCount;
4452}
4453
4454static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4455{
4456 // Create the draw list on demand, because they are not frequently used for all viewports
4457 ImGuiContext& g = *GImGui;
4458 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4459 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4460 if (draw_list == NULL)
4461 {
4462 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4463 draw_list->_OwnerName = drawlist_name;
4464 viewport->BgFgDrawLists[drawlist_no] = draw_list;
4465 }
4466
4467 // Our ImDrawList system requires that there is always a command
4468 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4469 {
4470 draw_list->_ResetForNewFrame();
4471 draw_list->PushTextureID(texture_id: g.IO.Fonts->TexID);
4472 draw_list->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size, intersect_with_current_clip_rect: false);
4473 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4474 }
4475 return draw_list;
4476}
4477
4478ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4479{
4480 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 0, drawlist_name: "##Background");
4481}
4482
4483ImDrawList* ImGui::GetBackgroundDrawList()
4484{
4485 ImGuiContext& g = *GImGui;
4486 return GetBackgroundDrawList(viewport: g.Viewports[0]);
4487}
4488
4489ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4490{
4491 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 1, drawlist_name: "##Foreground");
4492}
4493
4494ImDrawList* ImGui::GetForegroundDrawList()
4495{
4496 ImGuiContext& g = *GImGui;
4497 return GetForegroundDrawList(viewport: g.Viewports[0]);
4498}
4499
4500ImDrawListSharedData* ImGui::GetDrawListSharedData()
4501{
4502 return &GImGui->DrawListSharedData;
4503}
4504
4505void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4506{
4507 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4508 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4509 // This is because we want ActiveId to be set even when the window is not permitted to move.
4510 ImGuiContext& g = *GImGui;
4511 FocusWindow(window);
4512 SetActiveID(id: window->MoveId, window);
4513 g.NavDisableHighlight = true;
4514 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
4515 g.ActiveIdNoClearOnFocusLoss = true;
4516 SetActiveIdUsingAllKeyboardKeys();
4517
4518 bool can_move_window = true;
4519 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
4520 can_move_window = false;
4521 if (can_move_window)
4522 g.MovingWindow = window;
4523}
4524
4525// Handle mouse moving window
4526// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4527// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4528// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4529// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4530void ImGui::UpdateMouseMovingWindowNewFrame()
4531{
4532 ImGuiContext& g = *GImGui;
4533 if (g.MovingWindow != NULL)
4534 {
4535 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4536 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4537 KeepAliveID(id: g.ActiveId);
4538 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
4539 ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
4540 if (g.IO.MouseDown[0] && IsMousePosValid(mouse_pos: &g.IO.MousePos))
4541 {
4542 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4543 SetWindowPos(window: moving_window, pos, cond: ImGuiCond_Always);
4544 FocusWindow(window: g.MovingWindow);
4545 }
4546 else
4547 {
4548 g.MovingWindow = NULL;
4549 ClearActiveID();
4550 }
4551 }
4552 else
4553 {
4554 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4555 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4556 {
4557 KeepAliveID(id: g.ActiveId);
4558 if (!g.IO.MouseDown[0])
4559 ClearActiveID();
4560 }
4561 }
4562}
4563
4564// Initiate moving window when clicking on empty space or title bar.
4565// Handle left-click and right-click focus.
4566void ImGui::UpdateMouseMovingWindowEndFrame()
4567{
4568 ImGuiContext& g = *GImGui;
4569 if (g.ActiveId != 0 || g.HoveredId != 0)
4570 return;
4571
4572 // Unless we just made a window/popup appear
4573 if (g.NavWindow && g.NavWindow->Appearing)
4574 return;
4575
4576 // Click on empty space to focus window and start moving
4577 // (after we're done with all our widgets)
4578 if (g.IO.MouseClicked[0])
4579 {
4580 // Handle the edge case of a popup being closed while clicking in its empty space.
4581 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4582 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4583 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(id: root_window->PopupId, popup_flags: ImGuiPopupFlags_AnyPopupLevel);
4584
4585 if (root_window != NULL && !is_closed_popup)
4586 {
4587 StartMouseMovingWindow(window: g.HoveredWindow); //-V595
4588
4589 // Cancel moving if clicked outside of title bar
4590 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
4591 if (!root_window->TitleBarRect().Contains(p: g.IO.MouseClickedPos[0]))
4592 g.MovingWindow = NULL;
4593
4594 // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4595 if (g.HoveredIdIsDisabled)
4596 g.MovingWindow = NULL;
4597 }
4598 else if (root_window == NULL && g.NavWindow != NULL)
4599 {
4600 // Clicking on void disable focus
4601 FocusWindow(NULL, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
4602 }
4603 }
4604
4605 // With right mouse button we close popups without changing focus based on where the mouse is aimed
4606 // Instead, focus will be restored to the window under the bottom-most closed popup.
4607 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4608 if (g.IO.MouseClicked[1])
4609 {
4610 // Find the top-most window between HoveredWindow and the top-most Modal Window.
4611 // This is where we can trim the popup stack.
4612 ImGuiWindow* modal = GetTopMostPopupModal();
4613 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(potential_above: g.HoveredWindow, potential_below: modal));
4614 ClosePopupsOverWindow(ref_window: hovered_window_above_modal ? g.HoveredWindow : modal, restore_focus_to_window_under_popup: true);
4615 }
4616}
4617
4618static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4619{
4620 return (window->Active) && (!window->Hidden);
4621}
4622
4623// 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)
4624void ImGui::UpdateHoveredWindowAndCaptureFlags()
4625{
4626 ImGuiContext& g = *GImGui;
4627 ImGuiIO& io = g.IO;
4628
4629 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4630 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4631 g.WindowsHoverPadding = ImMax(lhs: g.Style.TouchExtraPadding, rhs: ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4632
4633 // Find the window hovered by mouse:
4634 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4635 // - 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.
4636 // - 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.
4637 bool clear_hovered_windows = false;
4638 FindHoveredWindowEx(pos: g.IO.MousePos, find_first_and_in_any_viewport: false, out_hovered_window: &g.HoveredWindow, out_hovered_window_under_moving_window: &g.HoveredWindowUnderMovingWindow);
4639 g.HoveredWindowBeforeClear = g.HoveredWindow;
4640
4641 // Modal windows prevents mouse from hovering behind them.
4642 ImGuiWindow* modal_window = GetTopMostPopupModal();
4643 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(window: g.HoveredWindow->RootWindow, potential_parent: modal_window))
4644 clear_hovered_windows = true;
4645
4646 // Disabled mouse hovering (we don't currently clear MousePos, we could)
4647 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4648 clear_hovered_windows = true;
4649
4650 // We track click ownership. When clicked outside of a window the click is owned by the application and
4651 // won't report hovering nor request capture even while dragging over our windows afterward.
4652 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4653 const bool has_open_modal = (modal_window != NULL);
4654 int mouse_earliest_down = -1;
4655 bool mouse_any_down = false;
4656 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4657 {
4658 if (io.MouseClicked[i])
4659 {
4660 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4661 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4662 }
4663 mouse_any_down |= io.MouseDown[i];
4664 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
4665 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4666 mouse_earliest_down = i;
4667 }
4668 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4669 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4670
4671 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4672 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4673 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4674 if (!mouse_avail && !mouse_dragging_extern_payload)
4675 clear_hovered_windows = true;
4676
4677 if (clear_hovered_windows)
4678 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4679
4680 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4681 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4682 if (g.WantCaptureMouseNextFrame != -1)
4683 {
4684 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4685 }
4686 else
4687 {
4688 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4689 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4690 }
4691
4692 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4693 io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4694 if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4695 io.WantCaptureKeyboard = true;
4696 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4697 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4698
4699 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4700 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4701}
4702
4703// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4704static void SetupDrawListSharedData()
4705{
4706 ImGuiContext& g = *GImGui;
4707 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4708 for (ImGuiViewportP* viewport : g.Viewports)
4709 virtual_space.Add(r: viewport->GetMainRect());
4710 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4711 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4712 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4713 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4714 if (g.Style.AntiAliasedLines)
4715 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4716 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4717 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4718 if (g.Style.AntiAliasedFill)
4719 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4720 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4721 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4722}
4723
4724void ImGui::NewFrame()
4725{
4726 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4727 ImGuiContext& g = *GImGui;
4728
4729 // Remove pending delete hooks before frame start.
4730 // This deferred removal avoid issues of removal while iterating the hook vector
4731 for (int n = g.Hooks.Size - 1; n >= 0; n--)
4732 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4733 g.Hooks.erase(it: &g.Hooks[n]);
4734
4735 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePre);
4736
4737 // Check and assert for various common IO and Configuration mistakes
4738 ErrorCheckNewFrameSanityChecks();
4739
4740 // Load settings on first frame, save settings when modified (after a delay)
4741 UpdateSettings();
4742
4743 g.Time += g.IO.DeltaTime;
4744 g.WithinFrameScope = true;
4745 g.FrameCount += 1;
4746 g.TooltipOverrideCount = 0;
4747 g.WindowsActiveCount = 0;
4748 g.MenusIdSubmittedThisFrame.resize(new_size: 0);
4749
4750 // Calculate frame-rate for the user, as a purely luxurious feature
4751 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4752 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4753 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4754 g.FramerateSecPerFrameCount = ImMin(lhs: g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4755 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4756
4757 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4758 g.InputEventsTrail.resize(new_size: 0);
4759 UpdateInputEvents(trickle_fast_inputs: g.IO.ConfigInputTrickleEventQueue);
4760
4761 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4762 UpdateViewportsNewFrame();
4763
4764 // Setup current font and draw list shared data
4765 g.IO.Fonts->Locked = true;
4766 SetupDrawListSharedData();
4767 SetCurrentFont(GetDefaultFont());
4768 IM_ASSERT(g.Font->IsLoaded());
4769
4770 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4771 for (ImGuiViewportP* viewport : g.Viewports)
4772 viewport->DrawDataP.Valid = false;
4773
4774 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4775 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4776 KeepAliveID(id: g.DragDropPayload.SourceId);
4777
4778 // Update HoveredId data
4779 if (!g.HoveredIdPreviousFrame)
4780 g.HoveredIdTimer = 0.0f;
4781 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4782 g.HoveredIdNotActiveTimer = 0.0f;
4783 if (g.HoveredId)
4784 g.HoveredIdTimer += g.IO.DeltaTime;
4785 if (g.HoveredId && g.ActiveId != g.HoveredId)
4786 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4787 g.HoveredIdPreviousFrame = g.HoveredId;
4788 g.HoveredId = 0;
4789 g.HoveredIdAllowOverlap = false;
4790 g.HoveredIdIsDisabled = false;
4791
4792 // Clear ActiveID if the item is not alive anymore.
4793 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4794 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4795 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4796 {
4797 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4798 ClearActiveID();
4799 }
4800
4801 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4802 if (g.ActiveId)
4803 g.ActiveIdTimer += g.IO.DeltaTime;
4804 g.LastActiveIdTimer += g.IO.DeltaTime;
4805 g.ActiveIdPreviousFrame = g.ActiveId;
4806 g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4807 g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4808 g.ActiveIdIsAlive = 0;
4809 g.ActiveIdHasBeenEditedThisFrame = false;
4810 g.ActiveIdPreviousFrameIsAlive = false;
4811 g.ActiveIdIsJustActivated = false;
4812 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4813 g.TempInputId = 0;
4814 if (g.ActiveId == 0)
4815 {
4816 g.ActiveIdUsingNavDirMask = 0x00;
4817 g.ActiveIdUsingAllKeyboardKeys = false;
4818 }
4819
4820 // Record when we have been stationary as this state is preserved while over same item.
4821 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4822 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4823 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4824 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4825 else if (g.HoverItemDelayId == 0)
4826 g.HoverItemUnlockedStationaryId = 0;
4827 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4828 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4829 else if (g.HoveredWindow == NULL)
4830 g.HoverWindowUnlockedStationaryId = 0;
4831
4832 // Update hover delay for IsItemHovered() with delays and tooltips
4833 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4834 if (g.HoverItemDelayId != 0)
4835 {
4836 g.HoverItemDelayTimer += g.IO.DeltaTime;
4837 g.HoverItemDelayClearTimer = 0.0f;
4838 g.HoverItemDelayId = 0;
4839 }
4840 else if (g.HoverItemDelayTimer > 0.0f)
4841 {
4842 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4843 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4844 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4845 if (g.HoverItemDelayClearTimer >= ImMax(lhs: 0.25f, rhs: g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4846 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.
4847 }
4848
4849 // Drag and drop
4850 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4851 g.DragDropAcceptIdCurr = 0;
4852 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4853 g.DragDropWithinSource = false;
4854 g.DragDropWithinTarget = false;
4855 g.DragDropHoldJustPressedId = 0;
4856
4857 // Close popups on focus lost (currently wip/opt-in)
4858 //if (g.IO.AppFocusLost)
4859 // ClosePopupsExceptModals();
4860
4861 // Update keyboard input state
4862 UpdateKeyboardInputs();
4863
4864 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4865 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4866 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4867 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4868
4869 // Update gamepad/keyboard navigation
4870 NavUpdate();
4871
4872 // Update mouse input state
4873 UpdateMouseInputs();
4874
4875 // Find hovered window
4876 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4877 UpdateHoveredWindowAndCaptureFlags();
4878
4879 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4880 UpdateMouseMovingWindowNewFrame();
4881
4882 // Background darkening/whitening
4883 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4884 g.DimBgRatio = ImMin(lhs: g.DimBgRatio + g.IO.DeltaTime * 6.0f, rhs: 1.0f);
4885 else
4886 g.DimBgRatio = ImMax(lhs: g.DimBgRatio - g.IO.DeltaTime * 10.0f, rhs: 0.0f);
4887
4888 g.MouseCursor = ImGuiMouseCursor_Arrow;
4889 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4890
4891 // Platform IME data: reset for the frame
4892 g.PlatformImeDataPrev = g.PlatformImeData;
4893 g.PlatformImeData.WantVisible = false;
4894
4895 // Mouse wheel scrolling, scale
4896 UpdateMouseWheel();
4897
4898 // Mark all windows as not visible and compact unused memory.
4899 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4900 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4901 for (ImGuiWindow* window : g.Windows)
4902 {
4903 window->WasActive = window->Active;
4904 window->Active = false;
4905 window->WriteAccessed = false;
4906 window->BeginCountPreviousFrame = window->BeginCount;
4907 window->BeginCount = 0;
4908
4909 // Garbage collect transient buffers of recently unused windows
4910 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4911 GcCompactTransientWindowBuffers(window);
4912 }
4913
4914 // Garbage collect transient buffers of recently unused tables
4915 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4916 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4917 TableGcCompactTransientBuffers(table: g.Tables.GetByIndex(n: i));
4918 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4919 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4920 TableGcCompactTransientBuffers(table: &table_temp_data);
4921 if (g.GcCompactAll)
4922 GcCompactTransientMiscBuffers();
4923 g.GcCompactAll = false;
4924
4925 // Closing the focused window restore focus to the first active root window in descending z-order
4926 if (g.NavWindow && !g.NavWindow->WasActive)
4927 FocusTopMostWindowUnderOne(NULL, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
4928
4929 // No window should be open at the beginning of the frame.
4930 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4931 g.CurrentWindowStack.resize(new_size: 0);
4932 g.BeginPopupStack.resize(new_size: 0);
4933 g.ItemFlagsStack.resize(new_size: 0);
4934 g.ItemFlagsStack.push_back(v: ImGuiItemFlags_AutoClosePopups); // Default flags
4935 g.CurrentItemFlags = g.ItemFlagsStack.back();
4936 g.GroupStack.resize(new_size: 0);
4937
4938 // [DEBUG] Update debug features
4939#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4940 UpdateDebugToolItemPicker();
4941 UpdateDebugToolStackQueries();
4942 UpdateDebugToolFlashStyleColor();
4943 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4944 {
4945 g.DebugLocateId = 0;
4946 g.DebugBreakInLocateId = false;
4947 }
4948 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
4949 {
4950 DebugLog(fmt: "(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
4951 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
4952 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4953 }
4954#endif
4955
4956 // Create implicit/fallback window - which we will only render it if the user has added something to it.
4957 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4958 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4959 g.WithinFrameScopeWithImplicitWindow = true;
4960 SetNextWindowSize(size: ImVec2(400, 400), cond: ImGuiCond_FirstUseEver);
4961 Begin(name: "Debug##Default");
4962 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4963
4964 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4965 // allowing to validate correct Begin/End behavior in user code.
4966#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4967 if (g.IO.ConfigDebugBeginReturnValueLoop)
4968 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4969 else
4970 g.DebugBeginReturnValueCullDepth = -1;
4971#endif
4972
4973 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePost);
4974}
4975
4976// FIXME: Add a more explicit sort order in the window structure.
4977static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4978{
4979 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4980 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4981 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4982 return d;
4983 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4984 return d;
4985 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4986}
4987
4988static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4989{
4990 out_sorted_windows->push_back(v: window);
4991 if (window->Active)
4992 {
4993 int count = window->DC.ChildWindows.Size;
4994 ImQsort(base: window->DC.ChildWindows.Data, count: (size_t)count, size_of_element: sizeof(ImGuiWindow*), compare_func: ChildWindowComparer);
4995 for (int i = 0; i < count; i++)
4996 {
4997 ImGuiWindow* child = window->DC.ChildWindows[i];
4998 if (child->Active)
4999 AddWindowToSortBuffer(out_sorted_windows, window: child);
5000 }
5001 }
5002}
5003
5004static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5005{
5006 ImGuiContext& g = *GImGui;
5007 ImGuiViewportP* viewport = g.Viewports[0];
5008 g.IO.MetricsRenderWindows++;
5009 if (window->DrawList->_Splitter._Count > 1)
5010 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5011 ImGui::AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[layer], draw_list: window->DrawList);
5012 for (ImGuiWindow* child : window->DC.ChildWindows)
5013 if (IsWindowActiveAndVisible(window: child)) // Clipped children may have been marked not active
5014 AddWindowToDrawData(window: child, layer);
5015}
5016
5017static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5018{
5019 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5020}
5021
5022// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5023static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5024{
5025 AddWindowToDrawData(window, layer: GetWindowDisplayLayer(window));
5026}
5027
5028static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5029{
5030 int n = builder->Layers[0]->Size;
5031 int full_size = n;
5032 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5033 full_size += builder->Layers[i]->Size;
5034 builder->Layers[0]->resize(new_size: full_size);
5035 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5036 {
5037 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5038 if (layer->empty())
5039 continue;
5040 memcpy(dest: builder->Layers[0]->Data + n, src: layer->Data, n: layer->Size * sizeof(ImDrawList*));
5041 n += layer->Size;
5042 layer->resize(new_size: 0);
5043 }
5044}
5045
5046static void InitViewportDrawData(ImGuiViewportP* viewport)
5047{
5048 ImGuiIO& io = ImGui::GetIO();
5049 ImDrawData* draw_data = &viewport->DrawDataP;
5050
5051 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5052 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5053 viewport->DrawDataBuilder.Layers[0]->resize(new_size: 0);
5054 viewport->DrawDataBuilder.Layers[1]->resize(new_size: 0);
5055
5056 draw_data->Valid = true;
5057 draw_data->CmdListsCount = 0;
5058 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5059 draw_data->DisplayPos = viewport->Pos;
5060 draw_data->DisplaySize = viewport->Size;
5061 draw_data->FramebufferScale = io.DisplayFramebufferScale;
5062 draw_data->OwnerViewport = viewport;
5063}
5064
5065// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5066// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5067// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5068// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5069// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5070// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5071void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5072{
5073 ImGuiWindow* window = GetCurrentWindow();
5074 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5075 window->ClipRect = window->DrawList->_ClipRectStack.back();
5076}
5077
5078void ImGui::PopClipRect()
5079{
5080 ImGuiWindow* window = GetCurrentWindow();
5081 window->DrawList->PopClipRect();
5082 window->ClipRect = window->DrawList->_ClipRectStack.back();
5083}
5084
5085static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5086{
5087 if ((col & IM_COL32_A_MASK) == 0)
5088 return;
5089
5090 ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport();
5091 ImRect viewport_rect = viewport->GetMainRect();
5092
5093 // Draw behind window by moving the draw command at the FRONT of the draw list
5094 {
5095 // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5096 // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5097 // 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.
5098 ImDrawList* draw_list = window->RootWindow->DrawList;
5099 if (draw_list->CmdBuffer.Size == 0)
5100 draw_list->AddDrawCmd();
5101 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)
5102 draw_list->AddRectFilled(p_min: viewport_rect.Min, p_max: viewport_rect.Max, col);
5103 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5104 IM_ASSERT(cmd.ElemCount == 6);
5105 draw_list->CmdBuffer.pop_back();
5106 draw_list->CmdBuffer.push_front(v: cmd);
5107 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5108 draw_list->PopClipRect();
5109 }
5110}
5111
5112ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5113{
5114 ImGuiContext& g = *GImGui;
5115 ImGuiWindow* bottom_most_visible_window = parent_window;
5116 for (int i = FindWindowDisplayIndex(window: parent_window); i >= 0; i--)
5117 {
5118 ImGuiWindow* window = g.Windows[i];
5119 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5120 continue;
5121 if (!IsWindowWithinBeginStackOf(window, potential_parent: parent_window))
5122 break;
5123 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(window: parent_window))
5124 bottom_most_visible_window = window;
5125 }
5126 return bottom_most_visible_window;
5127}
5128
5129static void ImGui::RenderDimmedBackgrounds()
5130{
5131 ImGuiContext& g = *GImGui;
5132 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5133 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5134 return;
5135 const bool dim_bg_for_modal = (modal_window != NULL);
5136 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5137 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5138 return;
5139
5140 if (dim_bg_for_modal)
5141 {
5142 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5143 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(parent_window: modal_window);
5144 RenderDimmedBackgroundBehindWindow(window: dim_behind_window, col: GetColorU32(col: modal_window->DC.ModalDimBgColor, alpha_mul: g.DimBgRatio));
5145 }
5146 else if (dim_bg_for_window_list)
5147 {
5148 // Draw dimming behind CTRL+Tab target window
5149 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingTargetAnim, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
5150
5151 // Draw border around CTRL+Tab target window
5152 ImGuiWindow* window = g.NavWindowingTargetAnim;
5153 ImGuiViewport* viewport = GetMainViewport();
5154 float distance = g.FontSize;
5155 ImRect bb = window->Rect();
5156 bb.Expand(amount: distance);
5157 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5158 bb.Expand(amount: -distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5159 if (window->DrawList->CmdBuffer.Size == 0)
5160 window->DrawList->AddDrawCmd();
5161 window->DrawList->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size);
5162 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);
5163 window->DrawList->PopClipRect();
5164 }
5165}
5166
5167// 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.
5168void ImGui::EndFrame()
5169{
5170 ImGuiContext& g = *GImGui;
5171 IM_ASSERT(g.Initialized);
5172
5173 // Don't process EndFrame() multiple times.
5174 if (g.FrameCountEnded == g.FrameCount)
5175 return;
5176 IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5177
5178 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePre);
5179
5180 ErrorCheckEndFrameSanityChecks();
5181
5182 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5183 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5184 if (g.IO.PlatformSetImeDataFn != NULL && memcmp(s1: ime_data, s2: &g.PlatformImeDataPrev, n: sizeof(ImGuiPlatformImeData)) != 0)
5185 {
5186 IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5187 ImGuiViewport* viewport = GetMainViewport();
5188 g.IO.PlatformSetImeDataFn(&g, viewport, ime_data);
5189 }
5190
5191 // Hide implicit/fallback "Debug" window if it hasn't been used
5192 g.WithinFrameScopeWithImplicitWindow = false;
5193 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5194 g.CurrentWindow->Active = false;
5195 End();
5196
5197 // Update navigation: CTRL+Tab, wrap-around requests
5198 NavEndFrame();
5199
5200 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5201 if (g.DragDropActive)
5202 {
5203 bool is_delivered = g.DragDropPayload.Delivery;
5204 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(button: g.DragDropMouseButton));
5205 if (is_delivered || is_elapsed)
5206 ClearDragDrop();
5207 }
5208
5209 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5210 // If you want to handle source item disappearing: instead of submitting your description tooltip
5211 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5212 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5213 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5214 if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5215 {
5216 g.DragDropWithinSource = true;
5217 SetTooltip("...");
5218 g.DragDropWithinSource = false;
5219 }
5220
5221 // End frame
5222 g.WithinFrameScope = false;
5223 g.FrameCountEnded = g.FrameCount;
5224
5225 // Initiate moving window + handle left-click and right-click focus
5226 UpdateMouseMovingWindowEndFrame();
5227
5228 // Sort the window list so that all child windows are after their parent
5229 // We cannot do that on FocusWindow() because children may not exist yet
5230 g.WindowsTempSortBuffer.resize(new_size: 0);
5231 g.WindowsTempSortBuffer.reserve(new_capacity: g.Windows.Size);
5232 for (ImGuiWindow* window : g.Windows)
5233 {
5234 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
5235 continue;
5236 AddWindowToSortBuffer(out_sorted_windows: &g.WindowsTempSortBuffer, window);
5237 }
5238
5239 // 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.
5240 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5241 g.Windows.swap(rhs&: g.WindowsTempSortBuffer);
5242 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5243
5244 // Unlock font atlas
5245 g.IO.Fonts->Locked = false;
5246
5247 // Clear Input data for next frame
5248 g.IO.MousePosPrev = g.IO.MousePos;
5249 g.IO.AppFocusLost = false;
5250 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5251 g.IO.InputQueueCharacters.resize(new_size: 0);
5252
5253 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePost);
5254}
5255
5256// Prepare the data for rendering so you can call GetDrawData()
5257// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5258// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5259void ImGui::Render()
5260{
5261 ImGuiContext& g = *GImGui;
5262 IM_ASSERT(g.Initialized);
5263
5264 if (g.FrameCountEnded != g.FrameCount)
5265 EndFrame();
5266 if (g.FrameCountRendered == g.FrameCount)
5267 return;
5268 g.FrameCountRendered = g.FrameCount;
5269
5270 g.IO.MetricsRenderWindows = 0;
5271 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPre);
5272
5273 // Draw modal/window whitening backgrounds
5274 RenderDimmedBackgrounds();
5275
5276 // Add background ImDrawList (for each active viewport)
5277 for (ImGuiViewportP* viewport : g.Viewports)
5278 {
5279 InitViewportDrawData(viewport);
5280 if (viewport->BgFgDrawLists[0] != NULL)
5281 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetBackgroundDrawList(viewport));
5282 }
5283
5284 // Add ImDrawList to render
5285 ImGuiWindow* windows_to_render_top_most[2];
5286 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
5287 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5288 for (ImGuiWindow* window : g.Windows)
5289 {
5290 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5291 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5292 AddRootWindowToDrawData(window);
5293 }
5294 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5295 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
5296 AddRootWindowToDrawData(window: windows_to_render_top_most[n]);
5297
5298 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5299 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5300 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));
5301
5302 // Setup ImDrawData structures for end-user
5303 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5304 for (ImGuiViewportP* viewport : g.Viewports)
5305 {
5306 FlattenDrawDataIntoSingleLayer(builder: &viewport->DrawDataBuilder);
5307
5308 // Add foreground ImDrawList (for each active viewport)
5309 if (viewport->BgFgDrawLists[1] != NULL)
5310 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetForegroundDrawList(viewport));
5311
5312 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5313 ImDrawData* draw_data = &viewport->DrawDataP;
5314 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5315 for (ImDrawList* draw_list : draw_data->CmdLists)
5316 draw_list->_PopUnusedDrawCmd();
5317
5318 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5319 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5320 }
5321
5322 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPost);
5323}
5324
5325// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5326// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5327ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5328{
5329 ImGuiContext& g = *GImGui;
5330
5331 const char* text_display_end;
5332 if (hide_text_after_double_hash)
5333 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
5334 else
5335 text_display_end = text_end;
5336
5337 ImFont* font = g.Font;
5338 const float font_size = g.FontSize;
5339 if (text == text_display_end)
5340 return ImVec2(0.0f, font_size);
5341 ImVec2 text_size = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width, text_begin: text, text_end: text_display_end, NULL);
5342
5343 // Round
5344 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5345 // FIXME: Investigate using ceilf or e.g.
5346 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5347 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5348 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5349
5350 return text_size;
5351}
5352
5353// Find window given position, search front-to-back
5354// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5355// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5356// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5357// called, aka before the next Begin(). Moving window isn't affected.
5358// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5359void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5360{
5361 ImGuiContext& g = *GImGui;
5362 ImGuiWindow* hovered_window = NULL;
5363 ImGuiWindow* hovered_window_under_moving_window = NULL;
5364
5365 if (find_first_and_in_any_viewport == false && g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5366 hovered_window = g.MovingWindow;
5367
5368 ImVec2 padding_regular = g.Style.TouchExtraPadding;
5369 ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5370 for (int i = g.Windows.Size - 1; i >= 0; i--)
5371 {
5372 ImGuiWindow* window = g.Windows[i];
5373 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5374 if (!window->Active || window->Hidden)
5375 continue;
5376 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5377 continue;
5378
5379 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5380 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5381 if (!window->OuterRectClipped.ContainsWithPad(p: pos, pad: hit_padding))
5382 continue;
5383
5384 // Support for one rectangular hole in any given window
5385 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5386 if (window->HitTestHoleSize.x != 0)
5387 {
5388 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5389 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5390 if (ImRect(hole_pos, hole_pos + hole_size).Contains(p: pos))
5391 continue;
5392 }
5393
5394 if (find_first_and_in_any_viewport)
5395 {
5396 hovered_window = window;
5397 break;
5398 }
5399 else
5400 {
5401 if (hovered_window == NULL)
5402 hovered_window = window;
5403 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5404 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
5405 hovered_window_under_moving_window = window;
5406 if (hovered_window && hovered_window_under_moving_window)
5407 break;
5408 }
5409 }
5410
5411 *out_hovered_window = hovered_window;
5412 if (out_hovered_window_under_moving_window != NULL)
5413 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5414}
5415
5416bool ImGui::IsItemActive()
5417{
5418 ImGuiContext& g = *GImGui;
5419 if (g.ActiveId)
5420 return g.ActiveId == g.LastItemData.ID;
5421 return false;
5422}
5423
5424bool ImGui::IsItemActivated()
5425{
5426 ImGuiContext& g = *GImGui;
5427 if (g.ActiveId)
5428 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5429 return true;
5430 return false;
5431}
5432
5433bool ImGui::IsItemDeactivated()
5434{
5435 ImGuiContext& g = *GImGui;
5436 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5437 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5438 return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5439}
5440
5441bool ImGui::IsItemDeactivatedAfterEdit()
5442{
5443 ImGuiContext& g = *GImGui;
5444 return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5445}
5446
5447// == GetItemID() == GetFocusID()
5448bool ImGui::IsItemFocused()
5449{
5450 ImGuiContext& g = *GImGui;
5451 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5452 return false;
5453 return true;
5454}
5455
5456// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5457// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5458bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5459{
5460 return IsMouseClicked(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_None);
5461}
5462
5463bool ImGui::IsItemToggledOpen()
5464{
5465 ImGuiContext& g = *GImGui;
5466 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5467}
5468
5469// Call after a Selectable() or TreeNode() involved in multi-selection.
5470// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
5471// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
5472// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
5473// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
5474bool ImGui::IsItemToggledSelection()
5475{
5476 ImGuiContext& g = *GImGui;
5477 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
5478 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5479}
5480
5481// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5482// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5483// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5484bool ImGui::IsAnyItemHovered()
5485{
5486 ImGuiContext& g = *GImGui;
5487 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5488}
5489
5490bool ImGui::IsAnyItemActive()
5491{
5492 ImGuiContext& g = *GImGui;
5493 return g.ActiveId != 0;
5494}
5495
5496bool ImGui::IsAnyItemFocused()
5497{
5498 ImGuiContext& g = *GImGui;
5499 return g.NavId != 0 && !g.NavDisableHighlight;
5500}
5501
5502bool ImGui::IsItemVisible()
5503{
5504 ImGuiContext& g = *GImGui;
5505 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5506}
5507
5508bool ImGui::IsItemEdited()
5509{
5510 ImGuiContext& g = *GImGui;
5511 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5512}
5513
5514// Allow next item to be overlapped by subsequent items.
5515// This works by requiring HoveredId to match for two subsequent frames,
5516// so if a following items overwrite it our interactions will naturally be disabled.
5517void ImGui::SetNextItemAllowOverlap()
5518{
5519 ImGuiContext& g = *GImGui;
5520 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5521}
5522
5523#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5524// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5525// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5526void ImGui::SetItemAllowOverlap()
5527{
5528 ImGuiContext& g = *GImGui;
5529 ImGuiID id = g.LastItemData.ID;
5530 if (g.HoveredId == id)
5531 g.HoveredIdAllowOverlap = true;
5532 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5533 g.ActiveIdAllowOverlap = true;
5534}
5535#endif
5536
5537// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
5538// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
5539void ImGui::SetActiveIdUsingAllKeyboardKeys()
5540{
5541 ImGuiContext& g = *GImGui;
5542 IM_ASSERT(g.ActiveId != 0);
5543 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5544 g.ActiveIdUsingAllKeyboardKeys = true;
5545 NavMoveRequestCancel();
5546}
5547
5548ImGuiID ImGui::GetItemID()
5549{
5550 ImGuiContext& g = *GImGui;
5551 return g.LastItemData.ID;
5552}
5553
5554ImVec2 ImGui::GetItemRectMin()
5555{
5556 ImGuiContext& g = *GImGui;
5557 return g.LastItemData.Rect.Min;
5558}
5559
5560ImVec2 ImGui::GetItemRectMax()
5561{
5562 ImGuiContext& g = *GImGui;
5563 return g.LastItemData.Rect.Max;
5564}
5565
5566ImVec2 ImGui::GetItemRectSize()
5567{
5568 ImGuiContext& g = *GImGui;
5569 return g.LastItemData.Rect.GetSize();
5570}
5571
5572// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5573// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5574bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5575{
5576 ImGuiID id = GetCurrentWindow()->GetID(str: str_id);
5577 return BeginChildEx(name: str_id, id, size_arg, child_flags, window_flags);
5578}
5579
5580bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5581{
5582 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5583}
5584
5585bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5586{
5587 ImGuiContext& g = *GImGui;
5588 ImGuiWindow* parent_window = g.CurrentWindow;
5589 IM_ASSERT(id != 0);
5590
5591 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5592 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5593 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5594 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5595 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5596 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5597 {
5598 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5599 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5600 }
5601#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5602 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5603 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5604 if (window_flags & ImGuiWindowFlags_NavFlattened)
5605 child_flags |= ImGuiChildFlags_NavFlattened;
5606#endif
5607 if (child_flags & ImGuiChildFlags_AutoResizeX)
5608 child_flags &= ~ImGuiChildFlags_ResizeX;
5609 if (child_flags & ImGuiChildFlags_AutoResizeY)
5610 child_flags &= ~ImGuiChildFlags_ResizeY;
5611
5612 // Set window flags
5613 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar;
5614 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5615 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5616 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5617 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5618 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5619
5620 // Special framed style
5621 if (child_flags & ImGuiChildFlags_FrameStyle)
5622 {
5623 PushStyleColor(idx: ImGuiCol_ChildBg, col: g.Style.Colors[ImGuiCol_FrameBg]);
5624 PushStyleVar(idx: ImGuiStyleVar_ChildRounding, val: g.Style.FrameRounding);
5625 PushStyleVar(idx: ImGuiStyleVar_ChildBorderSize, val: g.Style.FrameBorderSize);
5626 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.FramePadding);
5627 child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5628 window_flags |= ImGuiWindowFlags_NoMove;
5629 }
5630
5631 // Forward child flags
5632 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5633 g.NextWindowData.ChildFlags = child_flags;
5634
5635 // Forward size
5636 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5637 // (the alternative would to store conditional flags per axis, which is possible but more code)
5638 const ImVec2 size_avail = GetContentRegionAvail();
5639 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5640 const ImVec2 size = CalcItemSize(size: size_arg, default_w: size_default.x, default_h: size_default.y);
5641 SetNextWindowSize(size);
5642
5643 // 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.
5644 // 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.
5645 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5646 const char* temp_window_name;
5647 /*if (name && parent_window->IDStack.back() == parent_window->ID)
5648 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5649 else*/
5650 if (name)
5651 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%s_%08X", parent_window->Name, name, id);
5652 else
5653 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%08X", parent_window->Name, id);
5654
5655 // Set style
5656 const float backup_border_size = g.Style.ChildBorderSize;
5657 if ((child_flags & ImGuiChildFlags_Border) == 0)
5658 g.Style.ChildBorderSize = 0.0f;
5659
5660 // Begin into window
5661 const bool ret = Begin(name: temp_window_name, NULL, flags: window_flags);
5662
5663 // Restore style
5664 g.Style.ChildBorderSize = backup_border_size;
5665 if (child_flags & ImGuiChildFlags_FrameStyle)
5666 {
5667 PopStyleVar(count: 3);
5668 PopStyleColor();
5669 }
5670
5671 ImGuiWindow* child_window = g.CurrentWindow;
5672 child_window->ChildId = id;
5673
5674 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5675 // While this is not really documented/defined, it seems that the expected thing to do.
5676 if (child_window->BeginCount == 1)
5677 parent_window->DC.CursorPos = child_window->Pos;
5678
5679 // Process navigation-in immediately so NavInit can run on first frame
5680 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5681 const ImGuiID temp_id_for_activation = ImHashStr(data_p: "##Child", data_size: 0, seed: id);
5682 if (g.ActiveId == temp_id_for_activation)
5683 ClearActiveID();
5684 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5685 {
5686 FocusWindow(window: child_window);
5687 NavInitWindow(window: child_window, force_reinit: false);
5688 SetActiveID(id: temp_id_for_activation, window: child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5689 g.ActiveIdSource = g.NavInputSource;
5690 }
5691 return ret;
5692}
5693
5694void ImGui::EndChild()
5695{
5696 ImGuiContext& g = *GImGui;
5697 ImGuiWindow* child_window = g.CurrentWindow;
5698
5699 IM_ASSERT(g.WithinEndChild == false);
5700 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
5701
5702 g.WithinEndChild = true;
5703 ImVec2 child_size = child_window->Size;
5704 End();
5705 if (child_window->BeginCount == 1)
5706 {
5707 ImGuiWindow* parent_window = g.CurrentWindow;
5708 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5709 ItemSize(size: child_size);
5710 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
5711 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
5712 {
5713 ItemAdd(bb, id: child_window->ChildId);
5714 RenderNavHighlight(bb, id: child_window->ChildId);
5715
5716 // 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)
5717 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5718 RenderNavHighlight(bb: ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), id: g.NavId, flags: ImGuiNavHighlightFlags_Compact);
5719 }
5720 else
5721 {
5722 // Not navigable into
5723 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
5724 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
5725 ItemAdd(bb, id: child_window->ChildId, NULL, extra_flags: ImGuiItemFlags_NoNav);
5726
5727 // But when flattened we directly reach items, adjust active layer mask accordingly
5728 if (nav_flattened)
5729 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5730 }
5731 if (g.HoveredWindow == child_window)
5732 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5733 }
5734 g.WithinEndChild = false;
5735 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5736}
5737
5738static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5739{
5740 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
5741 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
5742 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5743}
5744
5745ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5746{
5747 ImGuiContext& g = *GImGui;
5748 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(key: id);
5749}
5750
5751ImGuiWindow* ImGui::FindWindowByName(const char* name)
5752{
5753 ImGuiID id = ImHashStr(data_p: name);
5754 return FindWindowByID(id);
5755}
5756
5757static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5758{
5759 window->Pos = ImTrunc(v: ImVec2(settings->Pos.x, settings->Pos.y));
5760 if (settings->Size.x > 0 && settings->Size.y > 0)
5761 window->Size = window->SizeFull = ImTrunc(v: ImVec2(settings->Size.x, settings->Size.y));
5762 window->Collapsed = settings->Collapsed;
5763}
5764
5765static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5766{
5767 ImGuiContext& g = *GImGui;
5768
5769 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5770 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5771 if ((just_created || child_flag_changed) && !new_is_explicit_child)
5772 {
5773 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5774 g.WindowsFocusOrder.push_back(v: window);
5775 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5776 }
5777 else if (!just_created && child_flag_changed && new_is_explicit_child)
5778 {
5779 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5780 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5781 g.WindowsFocusOrder[n]->FocusOrder--;
5782 g.WindowsFocusOrder.erase(it: g.WindowsFocusOrder.Data + window->FocusOrder);
5783 window->FocusOrder = -1;
5784 }
5785 window->IsExplicitChild = new_is_explicit_child;
5786}
5787
5788static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5789{
5790 // Initial window state with e.g. default/arbitrary window position
5791 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5792 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5793 window->Pos = main_viewport->Pos + ImVec2(60, 60);
5794 window->Size = window->SizeFull = ImVec2(0, 0);
5795 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5796
5797 if (settings != NULL)
5798 {
5799 SetWindowConditionAllowFlags(window, flags: ImGuiCond_FirstUseEver, enabled: false);
5800 ApplyWindowSettings(window, settings);
5801 }
5802 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5803
5804 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5805 {
5806 window->AutoFitFramesX = window->AutoFitFramesY = 2;
5807 window->AutoFitOnlyGrows = false;
5808 }
5809 else
5810 {
5811 if (window->Size.x <= 0.0f)
5812 window->AutoFitFramesX = 2;
5813 if (window->Size.y <= 0.0f)
5814 window->AutoFitFramesY = 2;
5815 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5816 }
5817}
5818
5819static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5820{
5821 // Create window the first time
5822 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5823 ImGuiContext& g = *GImGui;
5824 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5825 window->Flags = flags;
5826 g.WindowsById.SetVoidPtr(key: window->ID, val: window);
5827
5828 ImGuiWindowSettings* settings = NULL;
5829 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5830 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5831 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
5832
5833 InitOrLoadWindowSettings(window, settings);
5834
5835 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5836 g.Windows.push_front(v: window); // Quite slow but rare and only once
5837 else
5838 g.Windows.push_back(v: window);
5839
5840 return window;
5841}
5842
5843static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5844{
5845 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5846 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
5847 // Perhaps should tend further a neater test for this.
5848 ImGuiContext& g = *GImGui;
5849 ImVec2 size_min;
5850 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
5851 {
5852 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5853 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5854 }
5855 else
5856 {
5857 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
5858 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
5859 }
5860
5861 // Reduce artifacts with very small windows
5862 ImGuiWindow* window_for_height = window;
5863 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));
5864 return size_min;
5865}
5866
5867static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5868{
5869 ImGuiContext& g = *GImGui;
5870 ImVec2 new_size = size_desired;
5871 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5872 {
5873 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
5874 ImRect cr = g.NextWindowData.SizeConstraintRect;
5875 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;
5876 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;
5877 if (g.NextWindowData.SizeCallback)
5878 {
5879 ImGuiSizeCallbackData data;
5880 data.UserData = g.NextWindowData.SizeCallbackUserData;
5881 data.Pos = window->Pos;
5882 data.CurrentSize = window->SizeFull;
5883 data.DesiredSize = new_size;
5884 g.NextWindowData.SizeCallback(&data);
5885 new_size = data.DesiredSize;
5886 }
5887 new_size.x = IM_TRUNC(new_size.x);
5888 new_size.y = IM_TRUNC(new_size.y);
5889 }
5890
5891 // Minimum size
5892 ImVec2 size_min = CalcWindowMinSize(window);
5893 return ImMax(lhs: new_size, rhs: size_min);
5894}
5895
5896static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5897{
5898 bool preserve_old_content_sizes = false;
5899 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5900 preserve_old_content_sizes = true;
5901 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5902 preserve_old_content_sizes = true;
5903 if (preserve_old_content_sizes)
5904 {
5905 *content_size_current = window->ContentSize;
5906 *content_size_ideal = window->ContentSizeIdeal;
5907 return;
5908 }
5909
5910 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5911 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5912 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);
5913 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);
5914}
5915
5916static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5917{
5918 ImGuiContext& g = *GImGui;
5919 ImGuiStyle& style = g.Style;
5920 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5921 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5922 ImVec2 size_pad = window->WindowPadding * 2.0f;
5923 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5924 if (window->Flags & ImGuiWindowFlags_Tooltip)
5925 {
5926 // Tooltip always resize
5927 return size_desired;
5928 }
5929 else
5930 {
5931 // Maximum window size is determined by the viewport size or monitor size
5932 ImVec2 size_min = CalcWindowMinSize(window);
5933 ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
5934 ImVec2 size_auto_fit = ImClamp(v: size_desired, mn: size_min, mx: size_max);
5935
5936 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
5937 // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
5938 // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
5939 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
5940 size_auto_fit.y = window->SizeFull.y;
5941 else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
5942 size_auto_fit.x = window->SizeFull.x;
5943
5944 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5945 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5946 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
5947 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);
5948 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);
5949 if (will_have_scrollbar_x)
5950 size_auto_fit.y += style.ScrollbarSize;
5951 if (will_have_scrollbar_y)
5952 size_auto_fit.x += style.ScrollbarSize;
5953 return size_auto_fit;
5954 }
5955}
5956
5957ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5958{
5959 ImVec2 size_contents_current;
5960 ImVec2 size_contents_ideal;
5961 CalcWindowContentSizes(window, content_size_current: &size_contents_current, content_size_ideal: &size_contents_ideal);
5962 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: size_contents_ideal);
5963 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
5964 return size_final;
5965}
5966
5967static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5968{
5969 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5970 return ImGuiCol_PopupBg;
5971 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5972 return ImGuiCol_ChildBg;
5973 return ImGuiCol_WindowBg;
5974}
5975
5976static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5977{
5978 ImVec2 pos_min = ImLerp(a: corner_target, b: window->Pos, t: corner_norm); // Expected window upper-left
5979 ImVec2 pos_max = ImLerp(a: window->Pos + window->Size, b: corner_target, t: corner_norm); // Expected window lower-right
5980 ImVec2 size_expected = pos_max - pos_min;
5981 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_desired: size_expected);
5982 *out_pos = pos_min;
5983 if (corner_norm.x == 0.0f)
5984 out_pos->x -= (size_constrained.x - size_expected.x);
5985 if (corner_norm.y == 0.0f)
5986 out_pos->y -= (size_constrained.y - size_expected.y);
5987 *out_size = size_constrained;
5988}
5989
5990// Data for resizing from resize grip / corner
5991struct ImGuiResizeGripDef
5992{
5993 ImVec2 CornerPosN;
5994 ImVec2 InnerDir;
5995 int AngleMin12, AngleMax12;
5996};
5997static const ImGuiResizeGripDef resize_grip_def[4] =
5998{
5999 { .CornerPosN: ImVec2(1, 1), .InnerDir: ImVec2(-1, -1), .AngleMin12: 0, .AngleMax12: 3 }, // Lower-right
6000 { .CornerPosN: ImVec2(0, 1), .InnerDir: ImVec2(+1, -1), .AngleMin12: 3, .AngleMax12: 6 }, // Lower-left
6001 { .CornerPosN: ImVec2(0, 0), .InnerDir: ImVec2(+1, +1), .AngleMin12: 6, .AngleMax12: 9 }, // Upper-left (Unused)
6002 { .CornerPosN: ImVec2(1, 0), .InnerDir: ImVec2(-1, +1), .AngleMin12: 9, .AngleMax12: 12 } // Upper-right (Unused)
6003};
6004
6005// Data for resizing from borders
6006struct ImGuiResizeBorderDef
6007{
6008 ImVec2 InnerDir; // Normal toward inside
6009 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6010 float OuterAngle; // Angle toward outside
6011};
6012static const ImGuiResizeBorderDef resize_border_def[4] =
6013{
6014 { .InnerDir: ImVec2(+1, 0), .SegmentN1: ImVec2(0, 1), .SegmentN2: ImVec2(0, 0), IM_PI * 1.00f }, // Left
6015 { .InnerDir: ImVec2(-1, 0), .SegmentN1: ImVec2(1, 0), .SegmentN2: ImVec2(1, 1), IM_PI * 0.00f }, // Right
6016 { .InnerDir: ImVec2(0, +1), .SegmentN1: ImVec2(0, 0), .SegmentN2: ImVec2(1, 0), IM_PI * 1.50f }, // Up
6017 { .InnerDir: ImVec2(0, -1), .SegmentN1: ImVec2(1, 1), .SegmentN2: ImVec2(0, 1), IM_PI * 0.50f } // Down
6018};
6019
6020static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6021{
6022 ImRect rect = window->Rect();
6023 if (thickness == 0.0f)
6024 rect.Max -= ImVec2(1, 1);
6025 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); }
6026 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); }
6027 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); }
6028 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); }
6029 IM_ASSERT(0);
6030 return ImRect();
6031}
6032
6033// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6034ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6035{
6036 IM_ASSERT(n >= 0 && n < 4);
6037 ImGuiID id = window->ID;
6038 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
6039 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
6040 return id;
6041}
6042
6043// Borders (Left, Right, Up, Down)
6044ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6045{
6046 IM_ASSERT(dir >= 0 && dir < 4);
6047 int n = (int)dir + 4;
6048 ImGuiID id = window->ID;
6049 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
6050 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
6051 return id;
6052}
6053
6054// Handle resize for: Resize Grips, Borders, Gamepad
6055// Return true when using auto-fit (double-click on resize grip)
6056static 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)
6057{
6058 ImGuiContext& g = *GImGui;
6059 ImGuiWindowFlags flags = window->Flags;
6060
6061 if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6062 return false;
6063 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6064 return false;
6065
6066 int ret_auto_fit_mask = 0x00;
6067 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6068 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6069 const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6070
6071 ImRect clamp_rect = visibility_rect;
6072 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6073 if (window_move_from_title_bar)
6074 clamp_rect.Min.y -= window->TitleBarHeight;
6075
6076 ImVec2 pos_target(FLT_MAX, FLT_MAX);
6077 ImVec2 size_target(FLT_MAX, FLT_MAX);
6078
6079 // Resize grips and borders are on layer 1
6080 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6081
6082 // Manual resize grips
6083 PushID(str_id: "#RESIZE");
6084 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6085 {
6086 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6087 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: def.CornerPosN);
6088
6089 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6090 bool hovered, held;
6091 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6092 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(a&: resize_rect.Min.x, b&: resize_rect.Max.x);
6093 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(a&: resize_rect.Min.y, b&: resize_rect.Max.y);
6094 ImGuiID resize_grip_id = window->GetID(n: resize_grip_n); // == GetWindowResizeCornerID()
6095 ItemAdd(bb: resize_rect, id: resize_grip_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
6096 ButtonBehavior(bb: resize_rect, id: resize_grip_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6097 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6098 if (hovered || held)
6099 g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6100
6101 if (held && g.IO.MouseDoubleClicked[0])
6102 {
6103 // Auto-fit when double-clicking
6104 size_target = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6105 ret_auto_fit_mask = 0x03; // Both axises
6106 ClearActiveID();
6107 }
6108 else if (held)
6109 {
6110 // Resize from any of the four corners
6111 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6112 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);
6113 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);
6114 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
6115 corner_target = ImClamp(v: corner_target, mn: clamp_min, mx: clamp_max);
6116 CalcResizePosSizeFromAnyCorner(window, corner_target, corner_norm: def.CornerPosN, out_pos: &pos_target, out_size: &size_target);
6117 }
6118
6119 // Only lower-left grip is visible before hovering/activating
6120 if (resize_grip_n == 0 || held || hovered)
6121 resize_grip_col[resize_grip_n] = GetColorU32(idx: held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6122 }
6123
6124 int resize_border_mask = 0x00;
6125 if (window->Flags & ImGuiWindowFlags_ChildWindow)
6126 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6127 else
6128 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6129 for (int border_n = 0; border_n < 4; border_n++)
6130 {
6131 if ((resize_border_mask & (1 << border_n)) == 0)
6132 continue;
6133 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6134 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6135
6136 bool hovered, held;
6137 ImRect border_rect = GetResizeBorderRect(window, border_n, perp_padding: grip_hover_inner_size, thickness: WINDOWS_HOVER_PADDING);
6138 ImGuiID border_id = window->GetID(n: border_n + 4); // == GetWindowResizeBorderID()
6139 ItemAdd(bb: border_rect, id: border_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
6140 ButtonBehavior(bb: border_rect, id: border_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6141 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6142 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6143 hovered = false;
6144 if (hovered || held)
6145 g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6146 if (held && g.IO.MouseDoubleClicked[0])
6147 {
6148 // Double-clicking bottom or right border auto-fit on this axis
6149 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6150 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6151 if (border_n == 1 || border_n == 3) // Right and bottom border
6152 {
6153 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit)[axis];
6154 ret_auto_fit_mask |= (1 << axis);
6155 hovered = held = false; // So border doesn't show highlighted at new position
6156 }
6157 ClearActiveID();
6158 }
6159 else if (held)
6160 {
6161 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6162 // 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.
6163 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6164 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, potential_parent: g.WheelingWindow, popup_hierarchy: false));
6165 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6166 {
6167 g.WindowResizeBorderExpectedRect = border_rect;
6168 g.WindowResizeRelativeMode = false;
6169 }
6170 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(s1: &g.WindowResizeBorderExpectedRect, s2: &border_rect, n: sizeof(ImRect)) != 0)
6171 g.WindowResizeRelativeMode = true;
6172
6173 const ImVec2 border_curr = (window->Pos + ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2) * window->Size);
6174 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6175 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6176
6177 // Use absolute mode position
6178 ImVec2 border_target = window->Pos;
6179 border_target[axis] = border_target_abs_mode_for_axis;
6180
6181 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6182 bool ignore_resize = false;
6183 if (g.WindowResizeRelativeMode)
6184 {
6185 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6186 border_target[axis] = border_target_rel_mode_for_axis;
6187 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))
6188 ignore_resize = true;
6189 }
6190
6191 // Clamp, apply
6192 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);
6193 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6194 border_target = ImClamp(v: border_target, mn: clamp_min, mx: clamp_max);
6195 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6196 {
6197 ImGuiWindow* parent_window = window->ParentWindow;
6198 ImGuiWindowFlags parent_flags = parent_window->Flags;
6199 ImRect border_limit_rect = parent_window->InnerRect;
6200 border_limit_rect.Expand(amount: ImVec2(-ImMax(lhs: parent_window->WindowPadding.x, rhs: parent_window->WindowBorderSize), -ImMax(lhs: parent_window->WindowPadding.y, rhs: parent_window->WindowBorderSize)));
6201 if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6202 border_target.x = ImClamp(v: border_target.x, mn: border_limit_rect.Min.x, mx: border_limit_rect.Max.x);
6203 if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6204 border_target.y = ImClamp(v: border_target.y, mn: border_limit_rect.Min.y, mx: border_limit_rect.Max.y);
6205 }
6206 if (!ignore_resize)
6207 CalcResizePosSizeFromAnyCorner(window, corner_target: border_target, corner_norm: ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2), out_pos: &pos_target, out_size: &size_target);
6208 }
6209 if (hovered)
6210 *border_hovered = border_n;
6211 if (held)
6212 *border_held = border_n;
6213 }
6214 PopID();
6215
6216 // Restore nav layer
6217 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6218
6219 // Navigation resize (keyboard/gamepad)
6220 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6221 // Not even sure the callback works here.
6222 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
6223 {
6224 ImVec2 nav_resize_dir;
6225 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6226 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
6227 if (g.NavInputSource == ImGuiInputSource_Gamepad)
6228 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadDpadLeft, key_right: ImGuiKey_GamepadDpadRight, key_up: ImGuiKey_GamepadDpadUp, key_down: ImGuiKey_GamepadDpadDown);
6229 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6230 {
6231 const float NAV_RESIZE_SPEED = 600.0f;
6232 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(lhs: g.IO.DisplayFramebufferScale.x, rhs: g.IO.DisplayFramebufferScale.y);
6233 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6234 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
6235 g.NavWindowingToggleLayer = false;
6236 g.NavDisableMouseHover = true;
6237 resize_grip_col[0] = GetColorU32(idx: ImGuiCol_ResizeGripActive);
6238 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaSize);
6239 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6240 {
6241 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6242 size_target = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull + accum_floored);
6243 g.NavWindowingAccumDeltaSize -= accum_floored;
6244 }
6245 }
6246 }
6247
6248 // Apply back modified position/size to window
6249 const ImVec2 curr_pos = window->Pos;
6250 const ImVec2 curr_size = window->SizeFull;
6251 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6252 window->Size.x = window->SizeFull.x = size_target.x;
6253 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6254 window->Size.y = window->SizeFull.y = size_target.y;
6255 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(f: pos_target.x))
6256 window->Pos.x = ImTrunc(f: pos_target.x);
6257 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(f: pos_target.y))
6258 window->Pos.y = ImTrunc(f: pos_target.y);
6259 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)
6260 MarkIniSettingsDirty(window);
6261
6262 // Recalculate next expected border expected coordinates
6263 if (*border_held != -1)
6264 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_n: *border_held, perp_padding: grip_hover_inner_size, thickness: WINDOWS_HOVER_PADDING);
6265
6266 return ret_auto_fit_mask;
6267}
6268
6269static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6270{
6271 ImGuiContext& g = *GImGui;
6272 ImVec2 size_for_clamping = window->Size;
6273 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6274 size_for_clamping.y = window->TitleBarHeight;
6275 window->Pos = ImClamp(v: window->Pos, mn: visibility_rect.Min - size_for_clamping, mx: visibility_rect.Max);
6276}
6277
6278static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6279{
6280 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6281 const float rounding = window->WindowRounding;
6282 const ImRect border_r = GetResizeBorderRect(window, border_n, perp_padding: rounding, thickness: 0.0f);
6283 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);
6284 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);
6285 window->DrawList->PathStroke(col: border_col, flags: ImDrawFlags_None, thickness: border_size);
6286}
6287
6288static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6289{
6290 ImGuiContext& g = *GImGui;
6291 const float border_size = window->WindowBorderSize;
6292 const ImU32 border_col = GetColorU32(idx: ImGuiCol_Border);
6293 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6294 window->DrawList->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, col: border_col, rounding: window->WindowRounding, flags: 0, thickness: window->WindowBorderSize);
6295 else if (border_size > 0.0f)
6296 {
6297 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6298 RenderWindowOuterSingleBorder(window, border_n: 1, border_col, border_size);
6299 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6300 RenderWindowOuterSingleBorder(window, border_n: 3, border_col, border_size);
6301 }
6302 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6303 {
6304 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6305 const ImU32 border_col_resizing = GetColorU32(idx: (window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6306 RenderWindowOuterSingleBorder(window, border_n, border_col: border_col_resizing, border_size: ImMax(lhs: 2.0f, rhs: window->WindowBorderSize)); // Thicker than usual
6307 }
6308 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6309 {
6310 float y = window->Pos.y + window->TitleBarHeight - 1;
6311 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);
6312 }
6313}
6314
6315// Draw background and borders
6316// Draw and handle scrollbars
6317void 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)
6318{
6319 ImGuiContext& g = *GImGui;
6320 ImGuiStyle& style = g.Style;
6321 ImGuiWindowFlags flags = window->Flags;
6322
6323 // Ensure that ScrollBar doesn't read last frame's SkipItems
6324 IM_ASSERT(window->BeginCount == 0);
6325 window->SkipItems = false;
6326
6327 // Draw window + handle manual resize
6328 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6329 const float window_rounding = window->WindowRounding;
6330 const float window_border_size = window->WindowBorderSize;
6331 if (window->Collapsed)
6332 {
6333 // Title bar only
6334 const float backup_border_size = style.FrameBorderSize;
6335 g.Style.FrameBorderSize = window->WindowBorderSize;
6336 ImU32 title_bar_col = GetColorU32(idx: (title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6337 RenderFrame(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, fill_col: title_bar_col, border: true, rounding: window_rounding);
6338 g.Style.FrameBorderSize = backup_border_size;
6339 }
6340 else
6341 {
6342 // Window background
6343 if (!(flags & ImGuiWindowFlags_NoBackground))
6344 {
6345 ImU32 bg_col = GetColorU32(idx: GetWindowBgColorIdx(window));
6346 bool override_alpha = false;
6347 float alpha = 1.0f;
6348 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6349 {
6350 alpha = g.NextWindowData.BgAlphaVal;
6351 override_alpha = true;
6352 }
6353 if (override_alpha)
6354 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6355 window->DrawList->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);
6356 }
6357
6358 // Title bar
6359 if (!(flags & ImGuiWindowFlags_NoTitleBar))
6360 {
6361 ImU32 title_bar_col = GetColorU32(idx: title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6362 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);
6363 }
6364
6365 // Menu bar
6366 if (flags & ImGuiWindowFlags_MenuBar)
6367 {
6368 ImRect menu_bar_rect = window->MenuBarRect();
6369 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.
6370 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);
6371 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6372 window->DrawList->AddLine(p1: menu_bar_rect.GetBL(), p2: menu_bar_rect.GetBR(), col: GetColorU32(idx: ImGuiCol_Border), thickness: style.FrameBorderSize);
6373 }
6374
6375 // Scrollbars
6376 if (window->ScrollbarX)
6377 Scrollbar(axis: ImGuiAxis_X);
6378 if (window->ScrollbarY)
6379 Scrollbar(axis: ImGuiAxis_Y);
6380
6381 // Render resize grips (after their input handling so we don't have a frame of latency)
6382 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6383 {
6384 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6385 {
6386 const ImU32 col = resize_grip_col[resize_grip_n];
6387 if ((col & IM_COL32_A_MASK) == 0)
6388 continue;
6389 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6390 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: grip.CornerPosN);
6391 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)));
6392 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)));
6393 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);
6394 window->DrawList->PathFillConvex(col);
6395 }
6396 }
6397
6398 // Borders
6399 if (handle_borders_and_resize_grips)
6400 RenderWindowOuterBorders(window);
6401 }
6402}
6403
6404// Render title text, collapse button, close button
6405void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6406{
6407 ImGuiContext& g = *GImGui;
6408 ImGuiStyle& style = g.Style;
6409 ImGuiWindowFlags flags = window->Flags;
6410
6411 const bool has_close_button = (p_open != NULL);
6412 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6413
6414 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6415 // 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?
6416 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6417 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6418 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6419
6420 // Layout buttons
6421 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6422 float pad_l = style.FramePadding.x;
6423 float pad_r = style.FramePadding.x;
6424 float button_sz = g.FontSize;
6425 ImVec2 close_button_pos;
6426 ImVec2 collapse_button_pos;
6427 if (has_close_button)
6428 {
6429 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6430 pad_r += button_sz + style.ItemInnerSpacing.x;
6431 }
6432 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6433 {
6434 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6435 pad_r += button_sz + style.ItemInnerSpacing.x;
6436 }
6437 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6438 {
6439 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6440 pad_l += button_sz + style.ItemInnerSpacing.x;
6441 }
6442
6443 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6444 if (has_collapse_button)
6445 if (CollapseButton(id: window->GetID(str: "#COLLAPSE"), pos: collapse_button_pos))
6446 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6447
6448 // Close button
6449 if (has_close_button)
6450 if (CloseButton(id: window->GetID(str: "#CLOSE"), pos: close_button_pos))
6451 *p_open = false;
6452
6453 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6454 g.CurrentItemFlags = item_flags_backup;
6455
6456 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6457 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6458 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6459 const ImVec2 text_size = CalcTextSize(text: name, NULL, hide_text_after_double_hash: true) + ImVec2(marker_size_x, 0.0f);
6460
6461 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6462 // while uncentered title text will still reach edges correctly.
6463 if (pad_l > style.FramePadding.x)
6464 pad_l += g.Style.ItemInnerSpacing.x;
6465 if (pad_r > style.FramePadding.x)
6466 pad_r += g.Style.ItemInnerSpacing.x;
6467 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6468 {
6469 float centerness = ImSaturate(f: 1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6470 float pad_extend = ImMin(lhs: ImMax(lhs: pad_l, rhs: pad_r), rhs: title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6471 pad_l = ImMax(lhs: pad_l, rhs: pad_extend * centerness);
6472 pad_r = ImMax(lhs: pad_r, rhs: pad_extend * centerness);
6473 }
6474
6475 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);
6476 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);
6477 if (flags & ImGuiWindowFlags_UnsavedDocument)
6478 {
6479 ImVec2 marker_pos;
6480 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);
6481 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6482 if (marker_pos.x > layout_r.Min.x)
6483 {
6484 RenderBullet(draw_list: window->DrawList, pos: marker_pos, col: GetColorU32(idx: ImGuiCol_Text));
6485 clip_r.Max.x = ImMin(lhs: clip_r.Max.x, rhs: marker_pos.x - (int)(marker_size_x * 0.5f));
6486 }
6487 }
6488 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6489 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6490 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);
6491}
6492
6493void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6494{
6495 window->ParentWindow = parent_window;
6496 window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6497 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6498 window->RootWindow = parent_window->RootWindow;
6499 if (parent_window && (flags & ImGuiWindowFlags_Popup))
6500 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6501 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
6502 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6503 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6504 {
6505 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6506 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6507 }
6508}
6509
6510// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6511// This is designed as a toy/test-bed for
6512void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6513{
6514 ImGuiContext& g = *GImGui;
6515 window->SkipRefresh = false;
6516 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6517 return;
6518 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6519 {
6520 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6521 if (window->Appearing) // If currently appearing
6522 return;
6523 if (window->Hidden) // If was hidden (previous frame)
6524 return;
6525 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow)
6526 return;
6527 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow)
6528 return;
6529 window->DrawList = NULL;
6530 window->SkipRefresh = true;
6531 }
6532}
6533
6534// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6535// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6536// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6537// - WindowA // FindBlockingModal() returns Modal1
6538// - WindowB // .. returns Modal1
6539// - Modal1 // .. returns Modal2
6540// - WindowC // .. returns Modal2
6541// - WindowD // .. returns Modal2
6542// - Modal2 // .. returns Modal2
6543// - WindowE // .. returns NULL
6544// Notes:
6545// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6546// Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6547ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6548{
6549 ImGuiContext& g = *GImGui;
6550 if (g.OpenPopupStack.Size <= 0)
6551 return NULL;
6552
6553 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6554 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6555 {
6556 ImGuiWindow* popup_window = popup_data.Window;
6557 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6558 continue;
6559 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.
6560 continue;
6561 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6562 return popup_window;
6563 if (IsWindowWithinBeginStackOf(window, potential_parent: popup_window)) // Window may be over modal
6564 continue;
6565 return popup_window; // Place window right below first block modal
6566 }
6567 return NULL;
6568}
6569
6570// Push a new Dear ImGui window to add widgets to.
6571// - 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.
6572// - Begin/End can be called multiple times during the frame with the same window name to append content.
6573// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6574// 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.
6575// - 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.
6576// - 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.
6577bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6578{
6579 ImGuiContext& g = *GImGui;
6580 const ImGuiStyle& style = g.Style;
6581 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
6582 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
6583 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6584
6585 // Find or create
6586 ImGuiWindow* window = FindWindowByName(name);
6587 const bool window_just_created = (window == NULL);
6588 if (window_just_created)
6589 window = CreateNewWindow(name, flags);
6590
6591 // [DEBUG] Debug break requested by user
6592 if (g.DebugBreakInWindow == window->ID)
6593 IM_DEBUG_BREAK();
6594
6595 // Automatically disable manual moving/resizing when NoInputs is set
6596 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6597 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6598
6599 const int current_frame = g.FrameCount;
6600 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6601 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6602
6603 // Update the Appearing flag
6604 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6605 if (flags & ImGuiWindowFlags_Popup)
6606 {
6607 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6608 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6609 window_just_activated_by_user |= (window != popup_ref.Window);
6610 }
6611 window->Appearing = window_just_activated_by_user;
6612 if (window->Appearing)
6613 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
6614
6615 // Update Flags, LastFrameActive, BeginOrderXXX fields
6616 if (first_begin_of_the_frame)
6617 {
6618 UpdateWindowInFocusOrderList(window, just_created: window_just_created, new_flags: flags);
6619 window->Flags = (ImGuiWindowFlags)flags;
6620 window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6621 window->LastFrameActive = current_frame;
6622 window->LastTimeActive = (float)g.Time;
6623 window->BeginOrderWithinParent = 0;
6624 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6625 }
6626 else
6627 {
6628 flags = window->Flags;
6629 }
6630
6631 // 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
6632 ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6633 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6634 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6635
6636 // We allow window memory to be compacted so recreate the base stack when needed.
6637 if (window->IDStack.Size == 0)
6638 window->IDStack.push_back(v: window->ID);
6639
6640 // Add to stack
6641 g.CurrentWindow = window;
6642 ImGuiWindowStackData window_stack_data;
6643 window_stack_data.Window = window;
6644 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6645 window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6646 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
6647 g.CurrentWindowStack.push_back(v: window_stack_data);
6648 if (flags & ImGuiWindowFlags_ChildMenu)
6649 g.BeginMenuDepth++;
6650
6651 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6652 if (first_begin_of_the_frame)
6653 {
6654 UpdateWindowParentAndRootLinks(window, flags, parent_window);
6655 window->ParentWindowInBeginStack = parent_window_in_stack;
6656
6657 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
6658 // e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
6659 window->ParentWindowForFocusRoute = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window_in_stack : NULL;
6660 }
6661
6662 // Add to focus scope stack
6663 PushFocusScope(id: (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
6664 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6665
6666 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
6667 if (flags & ImGuiWindowFlags_Popup)
6668 {
6669 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6670 popup_ref.Window = window;
6671 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6672 g.BeginPopupStack.push_back(v: popup_ref);
6673 window->PopupId = popup_ref.PopupId;
6674 }
6675
6676 // Process SetNextWindow***() calls
6677 // (FIXME: Consider splitting the HasXXX flags into X/Y components
6678 bool window_pos_set_by_api = false;
6679 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6680 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6681 {
6682 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6683 if (window_pos_set_by_api && ImLengthSqr(lhs: g.NextWindowData.PosPivotVal) > 0.00001f)
6684 {
6685 // May be processed on the next frame if this is our first frame and we are measuring size
6686 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6687 window->SetWindowPosVal = g.NextWindowData.PosVal;
6688 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6689 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6690 }
6691 else
6692 {
6693 SetWindowPos(window, pos: g.NextWindowData.PosVal, cond: g.NextWindowData.PosCond);
6694 }
6695 }
6696 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6697 {
6698 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6699 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6700 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6701 g.NextWindowData.SizeVal.x = window->SizeFull.x;
6702 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6703 g.NextWindowData.SizeVal.y = window->SizeFull.y;
6704 SetWindowSize(window, size: g.NextWindowData.SizeVal, cond: g.NextWindowData.SizeCond);
6705 }
6706 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6707 {
6708 if (g.NextWindowData.ScrollVal.x >= 0.0f)
6709 {
6710 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6711 window->ScrollTargetCenterRatio.x = 0.0f;
6712 }
6713 if (g.NextWindowData.ScrollVal.y >= 0.0f)
6714 {
6715 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6716 window->ScrollTargetCenterRatio.y = 0.0f;
6717 }
6718 }
6719 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6720 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6721 else if (first_begin_of_the_frame)
6722 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6723 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6724 SetWindowCollapsed(window, collapsed: g.NextWindowData.CollapsedVal, cond: g.NextWindowData.CollapsedCond);
6725 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6726 FocusWindow(window);
6727 if (window->Appearing)
6728 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: false);
6729
6730 // [EXPERIMENTAL] Skip Refresh mode
6731 UpdateWindowSkipRefresh(window);
6732
6733 // Nested root windows (typically tooltips) override disabled state
6734 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
6735 BeginDisabledOverrideReenable();
6736
6737 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6738 g.CurrentWindow = NULL;
6739
6740 // When reusing window again multiple times a frame, just append content (don't need to setup again)
6741 if (first_begin_of_the_frame && !window->SkipRefresh)
6742 {
6743 // Initialize
6744 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6745 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6746 window->Active = true;
6747 window->HasCloseButton = (p_open != NULL);
6748 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6749 window->IDStack.resize(new_size: 1);
6750 window->DrawList->_ResetForNewFrame();
6751 window->DC.CurrentTableIdx = -1;
6752
6753 // Restore buffer capacity when woken from a compacted state, to avoid
6754 if (window->MemoryCompacted)
6755 GcAwakeTransientWindowBuffers(window);
6756
6757 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6758 // 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.
6759 bool window_title_visible_elsewhere = false;
6760 if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
6761 window_title_visible_elsewhere = true;
6762 if (window_title_visible_elsewhere && !window_just_created && strcmp(s1: name, s2: window->Name) != 0)
6763 {
6764 size_t buf_len = (size_t)window->NameBufLen;
6765 window->Name = ImStrdupcpy(dst: window->Name, p_dst_size: &buf_len, src: name);
6766 window->NameBufLen = (int)buf_len;
6767 }
6768
6769 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6770
6771 // Update contents size from last frame for auto-fitting (or use explicit size)
6772 CalcWindowContentSizes(window, content_size_current: &window->ContentSize, content_size_ideal: &window->ContentSizeIdeal);
6773 if (window->HiddenFramesCanSkipItems > 0)
6774 window->HiddenFramesCanSkipItems--;
6775 if (window->HiddenFramesCannotSkipItems > 0)
6776 window->HiddenFramesCannotSkipItems--;
6777 if (window->HiddenFramesForRenderOnly > 0)
6778 window->HiddenFramesForRenderOnly--;
6779
6780 // Hide new windows for one frame until they calculate their size
6781 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6782 window->HiddenFramesCannotSkipItems = 1;
6783
6784 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6785 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6786 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6787 {
6788 window->HiddenFramesCannotSkipItems = 1;
6789 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6790 {
6791 if (!window_size_x_set_by_api)
6792 window->Size.x = window->SizeFull.x = 0.f;
6793 if (!window_size_y_set_by_api)
6794 window->Size.y = window->SizeFull.y = 0.f;
6795 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6796 }
6797 }
6798
6799 // SELECT VIEWPORT
6800 // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
6801
6802 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
6803 SetWindowViewport(window, viewport);
6804 SetCurrentWindow(window);
6805
6806 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6807
6808 if (flags & ImGuiWindowFlags_ChildWindow)
6809 window->WindowBorderSize = style.ChildBorderSize;
6810 else
6811 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6812 window->WindowPadding = style.WindowPadding;
6813 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
6814 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6815
6816 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6817 window->DC.MenuBarOffset.x = ImMax(lhs: ImMax(lhs: window->WindowPadding.x, rhs: style.ItemSpacing.x), rhs: g.NextWindowData.MenuBarOffsetMinVal.x);
6818 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6819 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
6820 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
6821
6822 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
6823 // Those flags will be altered further down in the function depending on more conditions.
6824 bool use_current_size_for_scrollbar_x = window_just_created;
6825 bool use_current_size_for_scrollbar_y = window_just_created;
6826 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
6827 use_current_size_for_scrollbar_x = true;
6828 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
6829 use_current_size_for_scrollbar_y = true;
6830
6831 // Collapse window by double-clicking on title bar
6832 // 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
6833 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
6834 {
6835 // 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.
6836 ImRect title_bar_rect = window->TitleBarRect();
6837 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max))
6838 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(key: ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
6839 window->WantCollapseToggle = true;
6840 if (window->WantCollapseToggle)
6841 {
6842 window->Collapsed = !window->Collapsed;
6843 if (!window->Collapsed)
6844 use_current_size_for_scrollbar_y = true;
6845 MarkIniSettingsDirty(window);
6846 }
6847 }
6848 else
6849 {
6850 window->Collapsed = false;
6851 }
6852 window->WantCollapseToggle = false;
6853
6854 // SIZE
6855
6856 // Outer Decoration Sizes
6857 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
6858 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6859 window->DecoOuterSizeX1 = 0.0f;
6860 window->DecoOuterSizeX2 = 0.0f;
6861 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
6862 window->DecoOuterSizeY2 = 0.0f;
6863 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6864
6865 // Calculate auto-fit size, handle automatic resize
6866 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: window->ContentSizeIdeal);
6867 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6868 {
6869 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6870 if (!window_size_x_set_by_api)
6871 {
6872 window->SizeFull.x = size_auto_fit.x;
6873 use_current_size_for_scrollbar_x = true;
6874 }
6875 if (!window_size_y_set_by_api)
6876 {
6877 window->SizeFull.y = size_auto_fit.y;
6878 use_current_size_for_scrollbar_y = true;
6879 }
6880 }
6881 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6882 {
6883 // Auto-fit may only grow window during the first few frames
6884 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6885 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6886 {
6887 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.x, rhs: size_auto_fit.x) : size_auto_fit.x;
6888 use_current_size_for_scrollbar_x = true;
6889 }
6890 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6891 {
6892 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.y, rhs: size_auto_fit.y) : size_auto_fit.y;
6893 use_current_size_for_scrollbar_y = true;
6894 }
6895 if (!window->Collapsed)
6896 MarkIniSettingsDirty(window);
6897 }
6898
6899 // Apply minimum/maximum window size constraints and final size
6900 window->SizeFull = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull);
6901 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6902
6903 // POSITION
6904
6905 // Popup latch its initial position, will position itself when it appears next frame
6906 if (window_just_activated_by_user)
6907 {
6908 window->AutoPosLastDirection = ImGuiDir_None;
6909 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6910 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6911 }
6912
6913 // Position child window
6914 if (flags & ImGuiWindowFlags_ChildWindow)
6915 {
6916 IM_ASSERT(parent_window && parent_window->Active);
6917 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6918 parent_window->DC.ChildWindows.push_back(v: window);
6919 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6920 window->Pos = parent_window->DC.CursorPos;
6921 }
6922
6923 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6924 if (window_pos_with_pivot)
6925 SetWindowPos(window, pos: window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, cond: 0); // Position given a pivot (e.g. for centering)
6926 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6927 window->Pos = FindBestWindowPosForPopup(window);
6928 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6929 window->Pos = FindBestWindowPosForPopup(window);
6930 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6931 window->Pos = FindBestWindowPosForPopup(window);
6932
6933 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6934 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6935 ImRect viewport_rect(viewport->GetMainRect());
6936 ImRect viewport_work_rect(viewport->GetWorkRect());
6937 ImVec2 visibility_padding = ImMax(lhs: style.DisplayWindowPadding, rhs: style.DisplaySafeAreaPadding);
6938 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6939
6940 // Clamp position/size so window stays visible within its viewport or monitor
6941 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6942 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6943 if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
6944 ClampWindowPos(window, visibility_rect);
6945 window->Pos = ImTrunc(v: window->Pos);
6946
6947 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6948 // Large values tend to lead to variety of artifacts and are not recommended.
6949 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6950
6951 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6952 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6953 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6954
6955 // Apply window focus (new and reactivated windows are moved to front)
6956 bool want_focus = false;
6957 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6958 {
6959 if (flags & ImGuiWindowFlags_Popup)
6960 want_focus = true;
6961 else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
6962 want_focus = true;
6963 }
6964
6965 // [Test Engine] Register whole window in the item system (before submitting further decorations)
6966#ifdef IMGUI_ENABLE_TEST_ENGINE
6967 if (g.TestEngineHookItems)
6968 {
6969 IM_ASSERT(window->IDStack.Size == 1);
6970 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6971 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
6972 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6973 window->IDStack.Size = 1;
6974 }
6975#endif
6976
6977 // Handle manual resize: Resize Grips, Borders, Gamepad
6978 int border_hovered = -1, border_held = -1;
6979 ImU32 resize_grip_col[4] = {};
6980 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.
6981 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6982 if (!window->Collapsed)
6983 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))
6984 {
6985 if (auto_fit_mask & (1 << ImGuiAxis_X))
6986 use_current_size_for_scrollbar_x = true;
6987 if (auto_fit_mask & (1 << ImGuiAxis_Y))
6988 use_current_size_for_scrollbar_y = true;
6989 }
6990 window->ResizeBorderHovered = (signed char)border_hovered;
6991 window->ResizeBorderHeld = (signed char)border_held;
6992
6993 // SCROLLBAR VISIBILITY
6994
6995 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6996 if (!window->Collapsed)
6997 {
6998 // When reading the current size we need to read it after size constraints have been applied.
6999 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7000 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7001 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7002 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7003 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7004 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7005 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7006 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7007 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7008 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));
7009 if (window->ScrollbarX && !window->ScrollbarY)
7010 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7011 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7012
7013 // Amend the partially filled window->DecorationXXX values.
7014 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7015 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7016 }
7017
7018 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7019 // Update various regions. Variables they depend on should be set above in this function.
7020 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7021
7022 // Outer rectangle
7023 // Not affected by window border size. Used by:
7024 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7025 // - Begin() initial clipping rect for drawing window background and borders.
7026 // - Begin() clipping whole child
7027 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7028 const ImRect outer_rect = window->Rect();
7029 const ImRect title_bar_rect = window->TitleBarRect();
7030 window->OuterRectClipped = outer_rect;
7031 window->OuterRectClipped.ClipWith(r: host_rect);
7032
7033 // Inner rectangle
7034 // Not affected by window border size. Used by:
7035 // - InnerClipRect
7036 // - ScrollToRectEx()
7037 // - NavUpdatePageUpPageDown()
7038 // - Scrollbar()
7039 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7040 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7041 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7042 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7043
7044 // Inner clipping rectangle.
7045 // - Extend a outside of normal work region up to borders.
7046 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7047 // - It also makes clipped items be more noticeable.
7048 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7049 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7050 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7051 // Affected by window/frame border size. Used by:
7052 // - Begin() initial clip rect
7053 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7054 window->InnerClipRect.Min.x = ImFloor(f: 0.5f + window->InnerRect.Min.x + window->WindowBorderSize);
7055 window->InnerClipRect.Min.y = ImFloor(f: 0.5f + window->InnerRect.Min.y + top_border_size);
7056 window->InnerClipRect.Max.x = ImFloor(f: 0.5f + window->InnerRect.Max.x - window->WindowBorderSize);
7057 window->InnerClipRect.Max.y = ImFloor(f: 0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7058 window->InnerClipRect.ClipWithFull(r: host_rect);
7059
7060 // Default item width. Make it proportional to window size if window manually resizes
7061 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7062 window->ItemWidthDefault = ImTrunc(f: window->Size.x * 0.65f);
7063 else
7064 window->ItemWidthDefault = ImTrunc(f: g.FontSize * 16.0f);
7065
7066 // SCROLLING
7067
7068 // Lock down maximum scrolling
7069 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7070 // for right/bottom aligned items without creating a scrollbar.
7071 window->ScrollMax.x = ImMax(lhs: 0.0f, rhs: window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7072 window->ScrollMax.y = ImMax(lhs: 0.0f, rhs: window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7073
7074 // Apply scrolling
7075 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7076 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7077 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7078
7079 // DRAWING
7080
7081 // Setup draw list and outer clipping rectangle
7082 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7083 window->DrawList->PushTextureID(texture_id: g.Font->ContainerAtlas->TexID);
7084 PushClipRect(clip_rect_min: host_rect.Min, clip_rect_max: host_rect.Max, intersect_with_current_clip_rect: false);
7085
7086 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7087 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7088 // 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)
7089 {
7090 bool render_decorations_in_parent = false;
7091 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7092 {
7093 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7094 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7095 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7096 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(r: window->Rect()) : false;
7097 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7098 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7099 render_decorations_in_parent = true;
7100 }
7101 if (render_decorations_in_parent)
7102 window->DrawList = parent_window->DrawList;
7103
7104 // Handle title bar, scrollbar, resize grips and resize borders
7105 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7106 const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
7107 const bool handle_borders_and_resize_grips = true; // This exists to facilitate merge with 'docking' branch.
7108 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7109
7110 if (render_decorations_in_parent)
7111 window->DrawList = &window->DrawListInst;
7112 }
7113
7114 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7115
7116 // Work rectangle.
7117 // Affected by window padding and border size. Used by:
7118 // - Columns() for right-most edge
7119 // - TreeNode(), CollapsingHeader() for right-most edge
7120 // - BeginTabBar() for right-most edge
7121 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7122 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7123 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)));
7124 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)));
7125 window->WorkRect.Min.x = ImTrunc(f: window->InnerRect.Min.x - window->Scroll.x + ImMax(lhs: window->WindowPadding.x, rhs: window->WindowBorderSize));
7126 window->WorkRect.Min.y = ImTrunc(f: window->InnerRect.Min.y - window->Scroll.y + ImMax(lhs: window->WindowPadding.y, rhs: window->WindowBorderSize));
7127 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7128 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7129 window->ParentWorkRect = window->WorkRect;
7130
7131 // [LEGACY] Content Region
7132 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7133 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7134 // Used by:
7135 // - Mouse wheel scrolling + many other things
7136 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7137 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7138 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)));
7139 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)));
7140
7141 // Setup drawing context
7142 // (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.)
7143 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7144 window->DC.GroupOffset.x = 0.0f;
7145 window->DC.ColumnsOffset.x = 0.0f;
7146
7147 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7148 // 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.
7149 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7150 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7151 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7152 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7153 window->DC.CursorPos = window->DC.CursorStartPos;
7154 window->DC.CursorPosPrevLine = window->DC.CursorPos;
7155 window->DC.CursorMaxPos = window->DC.CursorStartPos;
7156 window->DC.IdealMaxPos = window->DC.CursorStartPos;
7157 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7158 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7159 window->DC.IsSameLine = window->DC.IsSetPos = false;
7160
7161 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7162 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7163 window->DC.NavLayersActiveMaskNext = 0x00;
7164 window->DC.NavIsScrollPushableX = true;
7165 window->DC.NavHideHighlightOneFrame = false;
7166 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7167
7168 window->DC.MenuBarAppending = false;
7169 window->DC.MenuColumns.Update(spacing: style.ItemSpacing.x, window_reappearing: window_just_activated_by_user);
7170 window->DC.TreeDepth = 0;
7171 window->DC.TreeHasStackDataDepthMask = 0x00;
7172 window->DC.ChildWindows.resize(new_size: 0);
7173 window->DC.StateStorage = &window->StateStorage;
7174 window->DC.CurrentColumns = NULL;
7175 window->DC.LayoutType = ImGuiLayoutType_Vertical;
7176 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7177
7178 window->DC.ItemWidth = window->ItemWidthDefault;
7179 window->DC.TextWrapPos = -1.0f; // disabled
7180 window->DC.ItemWidthStack.resize(new_size: 0);
7181 window->DC.TextWrapPosStack.resize(new_size: 0);
7182 if (flags & ImGuiWindowFlags_Modal)
7183 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(in: GetStyleColorVec4(idx: ImGuiCol_ModalWindowDimBg));
7184
7185 if (window->AutoFitFramesX > 0)
7186 window->AutoFitFramesX--;
7187 if (window->AutoFitFramesY > 0)
7188 window->AutoFitFramesY--;
7189
7190 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7191 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7192 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7193 // - Position window behind the modal that is not a begin-parent of this window.
7194 if (want_focus)
7195 FocusWindow(window, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
7196 if (want_focus && window == g.NavWindow)
7197 NavInitWindow(window, force_reinit: false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7198
7199 // Title bar
7200 if (!(flags & ImGuiWindowFlags_NoTitleBar))
7201 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);
7202
7203 // Clear hit test shape every frame
7204 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7205
7206 // Pressing CTRL+C while holding on a window copy its content to the clipboard
7207 // 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.
7208 // Maybe we can support CTRL+C on every element?
7209 /*
7210 //if (g.NavWindow == window && g.ActiveId == 0)
7211 if (g.ActiveId == window->MoveId)
7212 if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7213 LogToClipboard();
7214 */
7215
7216 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7217 // This is useful to allow creating context menus on title bar only, etc.
7218 SetLastItemDataForWindow(window, rect: title_bar_rect);
7219
7220 // [DEBUG]
7221#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7222 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7223 DebugLocateItemResolveWithLastItem();
7224#endif
7225
7226 // [Test Engine] Register title bar / tab with MoveId.
7227#ifdef IMGUI_ENABLE_TEST_ENGINE
7228 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7229 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7230#endif
7231 }
7232 else
7233 {
7234 // Skip refresh always mark active
7235 if (window->SkipRefresh)
7236 window->Active = true;
7237
7238 // Append
7239 SetCurrentWindow(window);
7240 SetLastItemDataForWindow(window, rect: window->TitleBarRect());
7241 }
7242
7243 if (!window->SkipRefresh)
7244 PushClipRect(clip_rect_min: window->InnerClipRect.Min, clip_rect_max: window->InnerClipRect.Max, intersect_with_current_clip_rect: true);
7245
7246 // 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)
7247 window->WriteAccessed = false;
7248 window->BeginCount++;
7249 g.NextWindowData.ClearFlags();
7250
7251 // Update visibility
7252 if (first_begin_of_the_frame && !window->SkipRefresh)
7253 {
7254 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7255 {
7256 // Child window can be out of sight and have "negative" clip windows.
7257 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7258 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
7259 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7260 if (!g.LogEnabled && !nav_request)
7261 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7262 {
7263 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7264 window->HiddenFramesCannotSkipItems = 1;
7265 else
7266 window->HiddenFramesCanSkipItems = 1;
7267 }
7268
7269 // Hide along with parent or if parent is collapsed
7270 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7271 window->HiddenFramesCanSkipItems = 1;
7272 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7273 window->HiddenFramesCannotSkipItems = 1;
7274 }
7275
7276 // 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)
7277 if (style.Alpha <= 0.0f)
7278 window->HiddenFramesCanSkipItems = 1;
7279
7280 // Update the Hidden flag
7281 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7282 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7283
7284 // Disable inputs for requested number of frames
7285 if (window->DisableInputsFrames > 0)
7286 {
7287 window->DisableInputsFrames--;
7288 window->Flags |= ImGuiWindowFlags_NoInputs;
7289 }
7290
7291 // Update the SkipItems flag, used to early out of all items functions (no layout required)
7292 bool skip_items = false;
7293 if (window->Collapsed || !window->Active || hidden_regular)
7294 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7295 skip_items = true;
7296 window->SkipItems = skip_items;
7297 }
7298 else if (first_begin_of_the_frame)
7299 {
7300 // Skip refresh mode
7301 window->SkipItems = true;
7302 }
7303
7304 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7305 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7306#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7307 if (!window->IsFallbackWindow)
7308 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7309 {
7310 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7311 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7312 return false;
7313 }
7314#endif
7315
7316 return !window->SkipItems;
7317}
7318
7319static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7320{
7321 ImGuiContext& g = *GImGui;
7322 SetLastItemData(item_id: window->MoveId, in_flags: g.CurrentItemFlags, item_flags: IsMouseHoveringRect(r_min: rect.Min, r_max: rect.Max, clip: false) ? ImGuiItemStatusFlags_HoveredRect : 0, item_rect: rect);
7323}
7324
7325void ImGui::End()
7326{
7327 ImGuiContext& g = *GImGui;
7328 ImGuiWindow* window = g.CurrentWindow;
7329
7330 // Error checking: verify that user hasn't called End() too many times!
7331 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7332 {
7333 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7334 return;
7335 }
7336 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7337
7338 // Error checking: verify that user doesn't directly call End() on a child window.
7339 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7340 IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7341
7342 // Close anything that is open
7343 if (window->DC.CurrentColumns)
7344 EndColumns();
7345 if (!window->SkipRefresh)
7346 PopClipRect(); // Inner window clip rectangle
7347 PopFocusScope();
7348 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7349 EndDisabledOverrideReenable();
7350
7351 if (window->SkipRefresh)
7352 {
7353 IM_ASSERT(window->DrawList == NULL);
7354 window->DrawList = &window->DrawListInst;
7355 }
7356
7357 // Stop logging
7358 if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
7359 LogFinish();
7360
7361 if (window->DC.IsSetPos)
7362 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7363
7364 // Pop from window stack
7365 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7366 if (window->Flags & ImGuiWindowFlags_ChildMenu)
7367 g.BeginMenuDepth--;
7368 if (window->Flags & ImGuiWindowFlags_Popup)
7369 g.BeginPopupStack.pop_back();
7370 window_stack_data.StackSizesOnBegin.CompareWithContextState(ctx: &g);
7371 g.CurrentWindowStack.pop_back();
7372 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7373}
7374
7375void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7376{
7377 ImGuiContext& g = *GImGui;
7378 IM_ASSERT(window == window->RootWindow);
7379
7380 const int cur_order = window->FocusOrder;
7381 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7382 if (g.WindowsFocusOrder.back() == window)
7383 return;
7384
7385 const int new_order = g.WindowsFocusOrder.Size - 1;
7386 for (int n = cur_order; n < new_order; n++)
7387 {
7388 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7389 g.WindowsFocusOrder[n]->FocusOrder--;
7390 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7391 }
7392 g.WindowsFocusOrder[new_order] = window;
7393 window->FocusOrder = (short)new_order;
7394}
7395
7396void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7397{
7398 ImGuiContext& g = *GImGui;
7399 ImGuiWindow* current_front_window = g.Windows.back();
7400 if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
7401 return;
7402 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7403 if (g.Windows[i] == window)
7404 {
7405 memmove(dest: &g.Windows[i], src: &g.Windows[i + 1], n: (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7406 g.Windows[g.Windows.Size - 1] = window;
7407 break;
7408 }
7409}
7410
7411void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7412{
7413 ImGuiContext& g = *GImGui;
7414 if (g.Windows[0] == window)
7415 return;
7416 for (int i = 0; i < g.Windows.Size; i++)
7417 if (g.Windows[i] == window)
7418 {
7419 memmove(dest: &g.Windows[1], src: &g.Windows[0], n: (size_t)i * sizeof(ImGuiWindow*));
7420 g.Windows[0] = window;
7421 break;
7422 }
7423}
7424
7425void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7426{
7427 IM_ASSERT(window != NULL && behind_window != NULL);
7428 ImGuiContext& g = *GImGui;
7429 window = window->RootWindow;
7430 behind_window = behind_window->RootWindow;
7431 int pos_wnd = FindWindowDisplayIndex(window);
7432 int pos_beh = FindWindowDisplayIndex(window: behind_window);
7433 if (pos_wnd < pos_beh)
7434 {
7435 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7436 memmove(dest: &g.Windows.Data[pos_wnd], src: &g.Windows.Data[pos_wnd + 1], n: copy_bytes);
7437 g.Windows[pos_beh - 1] = window;
7438 }
7439 else
7440 {
7441 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7442 memmove(dest: &g.Windows.Data[pos_beh + 1], src: &g.Windows.Data[pos_beh], n: copy_bytes);
7443 g.Windows[pos_beh] = window;
7444 }
7445}
7446
7447int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7448{
7449 ImGuiContext& g = *GImGui;
7450 return g.Windows.index_from_ptr(it: g.Windows.find(v: window));
7451}
7452
7453// Moving window to front of display and set focus (which happens to be back of our sorted list)
7454void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7455{
7456 ImGuiContext& g = *GImGui;
7457
7458 // Modal check?
7459 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7460 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7461 {
7462 // This block would typically be reached in two situations:
7463 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
7464 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
7465 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7466 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7467 BringWindowToDisplayBehind(window, behind_window: blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
7468 ClosePopupsOverWindow(ref_window: GetTopMostPopupModal(), restore_focus_to_window_under_popup: false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
7469 return;
7470 }
7471
7472 // Find last focused child (if any) and focus it instead.
7473 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7474 window = NavRestoreLastChildNavWindow(window);
7475
7476 // Apply focus
7477 if (g.NavWindow != window)
7478 {
7479 SetNavWindow(window);
7480 if (window && g.NavDisableMouseHover)
7481 g.NavMousePosDirty = true;
7482 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7483 g.NavLayer = ImGuiNavLayer_Main;
7484 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7485 g.NavIdIsAlive = false;
7486 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7487
7488 // Close popups if any
7489 ClosePopupsOverWindow(ref_window: window, restore_focus_to_window_under_popup: false);
7490 }
7491
7492 // Move the root window to the top of the pile
7493 IM_ASSERT(window == NULL || window->RootWindow != NULL);
7494 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
7495 ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
7496
7497 // Steal active widgets. Some of the cases it triggers includes:
7498 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7499 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7500 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7501 if (!g.ActiveIdNoClearOnFocusLoss)
7502 ClearActiveID();
7503
7504 // Passing NULL allow to disable keyboard focus
7505 if (!window)
7506 return;
7507
7508 // Bring to front
7509 BringWindowToFocusFront(window: focus_front_window);
7510 if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7511 BringWindowToDisplayFront(window: display_front_window);
7512}
7513
7514void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7515{
7516 ImGuiContext& g = *GImGui;
7517 IM_UNUSED(filter_viewport); // Unused in master branch.
7518 int start_idx = g.WindowsFocusOrder.Size - 1;
7519 if (under_this_window != NULL)
7520 {
7521 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7522 int offset = -1;
7523 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7524 {
7525 under_this_window = under_this_window->ParentWindow;
7526 offset = 0;
7527 }
7528 start_idx = FindWindowFocusIndex(window: under_this_window) + offset;
7529 }
7530 for (int i = start_idx; i >= 0; i--)
7531 {
7532 // 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.
7533 ImGuiWindow* window = g.WindowsFocusOrder[i];
7534 if (window == ignore_window || !window->WasActive)
7535 continue;
7536 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7537 {
7538 FocusWindow(window, flags);
7539 return;
7540 }
7541 }
7542 FocusWindow(NULL, flags);
7543}
7544
7545// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7546void ImGui::SetCurrentFont(ImFont* font)
7547{
7548 ImGuiContext& g = *GImGui;
7549 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7550 IM_ASSERT(font->Scale > 0.0f);
7551 g.Font = font;
7552 g.FontBaseSize = ImMax(lhs: 1.0f, rhs: g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7553 g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7554 g.FontScale = g.FontSize / g.Font->FontSize;
7555
7556 ImFontAtlas* atlas = g.Font->ContainerAtlas;
7557 g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7558 g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7559 g.DrawListSharedData.Font = g.Font;
7560 g.DrawListSharedData.FontSize = g.FontSize;
7561 g.DrawListSharedData.FontScale = g.FontScale;
7562}
7563
7564void ImGui::PushFont(ImFont* font)
7565{
7566 ImGuiContext& g = *GImGui;
7567 if (!font)
7568 font = GetDefaultFont();
7569 SetCurrentFont(font);
7570 g.FontStack.push_back(v: font);
7571 g.CurrentWindow->DrawList->PushTextureID(texture_id: font->ContainerAtlas->TexID);
7572}
7573
7574void ImGui::PopFont()
7575{
7576 ImGuiContext& g = *GImGui;
7577 g.CurrentWindow->DrawList->PopTextureID();
7578 g.FontStack.pop_back();
7579 SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7580}
7581
7582void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7583{
7584 ImGuiContext& g = *GImGui;
7585 ImGuiItemFlags item_flags = g.CurrentItemFlags;
7586 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7587 if (enabled)
7588 item_flags |= option;
7589 else
7590 item_flags &= ~option;
7591 g.CurrentItemFlags = item_flags;
7592 g.ItemFlagsStack.push_back(v: item_flags);
7593}
7594
7595void ImGui::PopItemFlag()
7596{
7597 ImGuiContext& g = *GImGui;
7598 IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7599 g.ItemFlagsStack.pop_back();
7600 g.CurrentItemFlags = g.ItemFlagsStack.back();
7601}
7602
7603// BeginDisabled()/EndDisabled()
7604// - 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)
7605// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7606// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7607// - 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.
7608// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7609void ImGui::BeginDisabled(bool disabled)
7610{
7611 ImGuiContext& g = *GImGui;
7612 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7613 if (!was_disabled && disabled)
7614 {
7615 g.DisabledAlphaBackup = g.Style.Alpha;
7616 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7617 }
7618 if (was_disabled || disabled)
7619 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7620 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
7621 g.DisabledStackSize++;
7622}
7623
7624void ImGui::EndDisabled()
7625{
7626 ImGuiContext& g = *GImGui;
7627 IM_ASSERT(g.DisabledStackSize > 0);
7628 g.DisabledStackSize--;
7629 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7630 //PopItemFlag();
7631 g.ItemFlagsStack.pop_back();
7632 g.CurrentItemFlags = g.ItemFlagsStack.back();
7633 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7634 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7635}
7636
7637// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
7638// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
7639// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
7640void ImGui::BeginDisabledOverrideReenable()
7641{
7642 ImGuiContext& g = *GImGui;
7643 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7644 g.Style.Alpha = g.DisabledAlphaBackup;
7645 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
7646 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags);
7647 g.DisabledStackSize++;
7648}
7649
7650void ImGui::EndDisabledOverrideReenable()
7651{
7652 ImGuiContext& g = *GImGui;
7653 g.DisabledStackSize--;
7654 IM_ASSERT(g.DisabledStackSize > 0);
7655 g.ItemFlagsStack.pop_back();
7656 g.CurrentItemFlags = g.ItemFlagsStack.back();
7657 g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
7658}
7659
7660void ImGui::PushTextWrapPos(float wrap_pos_x)
7661{
7662 ImGuiWindow* window = GetCurrentWindow();
7663 window->DC.TextWrapPosStack.push_back(v: window->DC.TextWrapPos);
7664 window->DC.TextWrapPos = wrap_pos_x;
7665}
7666
7667void ImGui::PopTextWrapPos()
7668{
7669 ImGuiWindow* window = GetCurrentWindow();
7670 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7671 window->DC.TextWrapPosStack.pop_back();
7672}
7673
7674static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)
7675{
7676 ImGuiWindow* last_window = NULL;
7677 while (last_window != window)
7678 {
7679 last_window = window;
7680 window = window->RootWindow;
7681 if (popup_hierarchy)
7682 window = window->RootWindowPopupTree;
7683 }
7684 return window;
7685}
7686
7687bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)
7688{
7689 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);
7690 if (window_root == potential_parent)
7691 return true;
7692 while (window != NULL)
7693 {
7694 if (window == potential_parent)
7695 return true;
7696 if (window == window_root) // end of chain
7697 return false;
7698 window = window->ParentWindow;
7699 }
7700 return false;
7701}
7702
7703bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7704{
7705 if (window->RootWindow == potential_parent)
7706 return true;
7707 while (window != NULL)
7708 {
7709 if (window == potential_parent)
7710 return true;
7711 window = window->ParentWindowInBeginStack;
7712 }
7713 return false;
7714}
7715
7716bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7717{
7718 ImGuiContext& g = *GImGui;
7719
7720 // 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
7721 const int display_layer_delta = GetWindowDisplayLayer(window: potential_above) - GetWindowDisplayLayer(window: potential_below);
7722 if (display_layer_delta != 0)
7723 return display_layer_delta > 0;
7724
7725 for (int i = g.Windows.Size - 1; i >= 0; i--)
7726 {
7727 ImGuiWindow* candidate_window = g.Windows[i];
7728 if (candidate_window == potential_above)
7729 return true;
7730 if (candidate_window == potential_below)
7731 return false;
7732 }
7733 return false;
7734}
7735
7736// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
7737// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
7738// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
7739// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
7740bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7741{
7742 IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
7743
7744 ImGuiContext& g = *GImGui;
7745 ImGuiWindow* ref_window = g.HoveredWindow;
7746 ImGuiWindow* cur_window = g.CurrentWindow;
7747 if (ref_window == NULL)
7748 return false;
7749
7750 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7751 {
7752 IM_ASSERT(cur_window); // Not inside a Begin()/End()
7753 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7754 if (flags & ImGuiHoveredFlags_RootWindow)
7755 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy);
7756
7757 bool result;
7758 if (flags & ImGuiHoveredFlags_ChildWindows)
7759 result = IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy);
7760 else
7761 result = (ref_window == cur_window);
7762 if (!result)
7763 return false;
7764 }
7765
7766 if (!IsWindowContentHoverable(window: ref_window, flags))
7767 return false;
7768 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7769 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7770 return false;
7771
7772 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
7773 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
7774 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
7775 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
7776 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
7777 if (flags & ImGuiHoveredFlags_ForTooltip)
7778 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
7779 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
7780 return false;
7781
7782 return true;
7783}
7784
7785bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7786{
7787 ImGuiContext& g = *GImGui;
7788 ImGuiWindow* ref_window = g.NavWindow;
7789 ImGuiWindow* cur_window = g.CurrentWindow;
7790
7791 if (ref_window == NULL)
7792 return false;
7793 if (flags & ImGuiFocusedFlags_AnyWindow)
7794 return true;
7795
7796 IM_ASSERT(cur_window); // Not inside a Begin()/End()
7797 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7798 if (flags & ImGuiHoveredFlags_RootWindow)
7799 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy);
7800
7801 if (flags & ImGuiHoveredFlags_ChildWindows)
7802 return IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy);
7803 else
7804 return (ref_window == cur_window);
7805}
7806
7807// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7808// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7809// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7810bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7811{
7812 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7813}
7814
7815float ImGui::GetWindowWidth()
7816{
7817 ImGuiWindow* window = GImGui->CurrentWindow;
7818 return window->Size.x;
7819}
7820
7821float ImGui::GetWindowHeight()
7822{
7823 ImGuiWindow* window = GImGui->CurrentWindow;
7824 return window->Size.y;
7825}
7826
7827ImVec2 ImGui::GetWindowPos()
7828{
7829 ImGuiContext& g = *GImGui;
7830 ImGuiWindow* window = g.CurrentWindow;
7831 return window->Pos;
7832}
7833
7834void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7835{
7836 // Test condition (NB: bit 0 is always true) and clear flags for next time
7837 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7838 return;
7839
7840 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7841 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7842 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7843
7844 // Set
7845 const ImVec2 old_pos = window->Pos;
7846 window->Pos = ImTrunc(v: pos);
7847 ImVec2 offset = window->Pos - old_pos;
7848 if (offset.x == 0.0f && offset.y == 0.0f)
7849 return;
7850 MarkIniSettingsDirty(window);
7851 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
7852 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7853 window->DC.IdealMaxPos += offset;
7854 window->DC.CursorStartPos += offset;
7855}
7856
7857void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7858{
7859 ImGuiWindow* window = GetCurrentWindowRead();
7860 SetWindowPos(window, pos, cond);
7861}
7862
7863void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7864{
7865 if (ImGuiWindow* window = FindWindowByName(name))
7866 SetWindowPos(window, pos, cond);
7867}
7868
7869ImVec2 ImGui::GetWindowSize()
7870{
7871 ImGuiWindow* window = GetCurrentWindowRead();
7872 return window->Size;
7873}
7874
7875void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7876{
7877 // Test condition (NB: bit 0 is always true) and clear flags for next time
7878 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7879 return;
7880
7881 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7882 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7883
7884 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
7885 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
7886 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7887 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
7888 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7889
7890 // Set
7891 ImVec2 old_size = window->SizeFull;
7892 if (size.x <= 0.0f)
7893 window->AutoFitOnlyGrows = false;
7894 else
7895 window->SizeFull.x = IM_TRUNC(size.x);
7896 if (size.y <= 0.0f)
7897 window->AutoFitOnlyGrows = false;
7898 else
7899 window->SizeFull.y = IM_TRUNC(size.y);
7900 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7901 MarkIniSettingsDirty(window);
7902}
7903
7904void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7905{
7906 SetWindowSize(window: GImGui->CurrentWindow, size, cond);
7907}
7908
7909void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7910{
7911 if (ImGuiWindow* window = FindWindowByName(name))
7912 SetWindowSize(window, size, cond);
7913}
7914
7915void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7916{
7917 // Test condition (NB: bit 0 is always true) and clear flags for next time
7918 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7919 return;
7920 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7921
7922 // Set
7923 window->Collapsed = collapsed;
7924}
7925
7926void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7927{
7928 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
7929 window->HitTestHoleSize = ImVec2ih(size);
7930 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7931}
7932
7933void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
7934{
7935 window->Hidden = window->SkipItems = true;
7936 window->HiddenFramesCanSkipItems = 1;
7937}
7938
7939void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7940{
7941 SetWindowCollapsed(window: GImGui->CurrentWindow, collapsed, cond);
7942}
7943
7944bool ImGui::IsWindowCollapsed()
7945{
7946 ImGuiWindow* window = GetCurrentWindowRead();
7947 return window->Collapsed;
7948}
7949
7950bool ImGui::IsWindowAppearing()
7951{
7952 ImGuiWindow* window = GetCurrentWindowRead();
7953 return window->Appearing;
7954}
7955
7956void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7957{
7958 if (ImGuiWindow* window = FindWindowByName(name))
7959 SetWindowCollapsed(window, collapsed, cond);
7960}
7961
7962void ImGui::SetWindowFocus()
7963{
7964 FocusWindow(window: GImGui->CurrentWindow);
7965}
7966
7967void ImGui::SetWindowFocus(const char* name)
7968{
7969 if (name)
7970 {
7971 if (ImGuiWindow* window = FindWindowByName(name))
7972 FocusWindow(window);
7973 }
7974 else
7975 {
7976 FocusWindow(NULL);
7977 }
7978}
7979
7980void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
7981{
7982 ImGuiContext& g = *GImGui;
7983 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7984 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
7985 g.NextWindowData.PosVal = pos;
7986 g.NextWindowData.PosPivotVal = pivot;
7987 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
7988}
7989
7990void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
7991{
7992 ImGuiContext& g = *GImGui;
7993 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7994 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
7995 g.NextWindowData.SizeVal = size;
7996 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
7997}
7998
7999// For each axis:
8000// - 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.
8001// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8002// - See "Demo->Examples->Constrained-resizing window" for examples.
8003void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8004{
8005 ImGuiContext& g = *GImGui;
8006 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8007 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8008 g.NextWindowData.SizeCallback = custom_callback;
8009 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8010}
8011
8012// Content size = inner scrollable rectangle, padded with WindowPadding.
8013// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8014void ImGui::SetNextWindowContentSize(const ImVec2& size)
8015{
8016 ImGuiContext& g = *GImGui;
8017 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8018 g.NextWindowData.ContentSizeVal = ImTrunc(v: size);
8019}
8020
8021void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8022{
8023 ImGuiContext& g = *GImGui;
8024 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8025 g.NextWindowData.ScrollVal = scroll;
8026}
8027
8028void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8029{
8030 ImGuiContext& g = *GImGui;
8031 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8032 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8033 g.NextWindowData.CollapsedVal = collapsed;
8034 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8035}
8036
8037void ImGui::SetNextWindowFocus()
8038{
8039 ImGuiContext& g = *GImGui;
8040 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8041}
8042
8043void ImGui::SetNextWindowBgAlpha(float alpha)
8044{
8045 ImGuiContext& g = *GImGui;
8046 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8047 g.NextWindowData.BgAlphaVal = alpha;
8048}
8049
8050// This is experimental and meant to be a toy for exploring a future/wider range of features.
8051void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8052{
8053 ImGuiContext& g = *GImGui;
8054 g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8055 g.NextWindowData.RefreshFlagsVal = flags;
8056}
8057
8058ImDrawList* ImGui::GetWindowDrawList()
8059{
8060 ImGuiWindow* window = GetCurrentWindow();
8061 return window->DrawList;
8062}
8063
8064ImFont* ImGui::GetFont()
8065{
8066 return GImGui->Font;
8067}
8068
8069float ImGui::GetFontSize()
8070{
8071 return GImGui->FontSize;
8072}
8073
8074ImVec2 ImGui::GetFontTexUvWhitePixel()
8075{
8076 return GImGui->DrawListSharedData.TexUvWhitePixel;
8077}
8078
8079void ImGui::SetWindowFontScale(float scale)
8080{
8081 IM_ASSERT(scale > 0.0f);
8082 ImGuiContext& g = *GImGui;
8083 ImGuiWindow* window = GetCurrentWindow();
8084 window->FontWindowScale = scale;
8085 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8086 g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
8087}
8088
8089void ImGui::PushFocusScope(ImGuiID id)
8090{
8091 ImGuiContext& g = *GImGui;
8092 ImGuiFocusScopeData data;
8093 data.ID = id;
8094 data.WindowID = g.CurrentWindow->ID;
8095 g.FocusScopeStack.push_back(v: data);
8096 g.CurrentFocusScopeId = id;
8097}
8098
8099void ImGui::PopFocusScope()
8100{
8101 ImGuiContext& g = *GImGui;
8102 if (g.FocusScopeStack.Size == 0)
8103 {
8104 IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8105 return;
8106 }
8107 g.FocusScopeStack.pop_back();
8108 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8109}
8110
8111void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8112{
8113 ImGuiContext& g = *GImGui;
8114 g.NavFocusScopeId = focus_scope_id;
8115 g.NavFocusRoute.resize(new_size: 0); // Invalidate
8116 if (focus_scope_id == 0)
8117 return;
8118 IM_ASSERT(g.NavWindow != NULL);
8119
8120 // Store current path (in reverse order)
8121 if (focus_scope_id == g.CurrentFocusScopeId)
8122 {
8123 // Top of focus stack contains local focus scopes inside current window
8124 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8125 g.NavFocusRoute.push_back(v: g.FocusScopeStack.Data[n]);
8126 }
8127 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8128 g.NavFocusRoute.push_back(v: { .ID: focus_scope_id, .WindowID: g.NavWindow->ID });
8129 else
8130 return;
8131
8132 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8133 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8134 g.NavFocusRoute.push_back(v: { .ID: window->NavRootFocusScopeId, .WindowID: window->ID });
8135 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8136}
8137
8138// Focus = move navigation cursor, set scrolling, set focus window.
8139void ImGui::FocusItem()
8140{
8141 ImGuiContext& g = *GImGui;
8142 ImGuiWindow* window = g.CurrentWindow;
8143 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8144 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8145 {
8146 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8147 return;
8148 }
8149
8150 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8151 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8152 SetNavWindow(window);
8153 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: ImGuiDir_Up, move_flags, scroll_flags);
8154 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
8155}
8156
8157void ImGui::ActivateItemByID(ImGuiID id)
8158{
8159 ImGuiContext& g = *GImGui;
8160 g.NavNextActivateId = id;
8161 g.NavNextActivateFlags = ImGuiActivateFlags_None;
8162}
8163
8164// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8165// But ActivateItem() should function without altering scroll/focus?
8166void ImGui::SetKeyboardFocusHere(int offset)
8167{
8168 ImGuiContext& g = *GImGui;
8169 ImGuiWindow* window = g.CurrentWindow;
8170 IM_ASSERT(offset >= -1); // -1 is allowed but not below
8171 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8172
8173 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8174 // When we refactor this function into ActivateItem() we may want to make this an option.
8175 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8176 // is also automatically dropped in the event g.ActiveId is stolen.
8177 if (g.DragDropActive || g.MovingWindow != NULL)
8178 {
8179 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8180 return;
8181 }
8182
8183 SetNavWindow(window);
8184
8185 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8186 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8187 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.
8188 if (offset == -1)
8189 {
8190 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
8191 }
8192 else
8193 {
8194 g.NavTabbingDir = 1;
8195 g.NavTabbingCounter = offset + 1;
8196 }
8197}
8198
8199void ImGui::SetItemDefaultFocus()
8200{
8201 ImGuiContext& g = *GImGui;
8202 ImGuiWindow* window = g.CurrentWindow;
8203 if (!window->Appearing)
8204 return;
8205 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8206 return;
8207
8208 g.NavInitRequest = false;
8209 NavApplyItemToResult(result: &g.NavInitResult);
8210 NavUpdateAnyRequestFlag();
8211
8212 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8213 if (!window->ClipRect.Contains(r: g.LastItemData.Rect))
8214 ScrollToRectEx(window, rect: g.LastItemData.Rect, flags: ImGuiScrollFlags_None);
8215}
8216
8217void ImGui::SetStateStorage(ImGuiStorage* tree)
8218{
8219 ImGuiWindow* window = GImGui->CurrentWindow;
8220 window->DC.StateStorage = tree ? tree : &window->StateStorage;
8221}
8222
8223ImGuiStorage* ImGui::GetStateStorage()
8224{
8225 ImGuiWindow* window = GImGui->CurrentWindow;
8226 return window->DC.StateStorage;
8227}
8228
8229bool ImGui::IsRectVisible(const ImVec2& size)
8230{
8231 ImGuiWindow* window = GImGui->CurrentWindow;
8232 return window->ClipRect.Overlaps(r: ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8233}
8234
8235bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8236{
8237 ImGuiWindow* window = GImGui->CurrentWindow;
8238 return window->ClipRect.Overlaps(r: ImRect(rect_min, rect_max));
8239}
8240
8241//-----------------------------------------------------------------------------
8242// [SECTION] ID STACK
8243//-----------------------------------------------------------------------------
8244
8245// This is one of the very rare legacy case where we use ImGuiWindow methods,
8246// it should ideally be flattened at some point but it's been used a lots by widgets.
8247IM_MSVC_RUNTIME_CHECKS_OFF
8248ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8249{
8250 ImGuiID seed = IDStack.back();
8251 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
8252#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8253 ImGuiContext& g = *Ctx;
8254 if (g.DebugHookIdInfo == id)
8255 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
8256#endif
8257 return id;
8258}
8259
8260ImGuiID ImGuiWindow::GetID(const void* ptr)
8261{
8262 ImGuiID seed = IDStack.back();
8263 ImGuiID id = ImHashData(data_p: &ptr, data_size: sizeof(void*), seed);
8264#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8265 ImGuiContext& g = *Ctx;
8266 if (g.DebugHookIdInfo == id)
8267 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_Pointer, data_id: ptr, NULL);
8268#endif
8269 return id;
8270}
8271
8272ImGuiID ImGuiWindow::GetID(int n)
8273{
8274 ImGuiID seed = IDStack.back();
8275 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
8276#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8277 ImGuiContext& g = *Ctx;
8278 if (g.DebugHookIdInfo == id)
8279 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
8280#endif
8281 return id;
8282}
8283
8284// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8285ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8286{
8287 ImGuiID seed = IDStack.back();
8288 ImRect r_rel = ImGui::WindowRectAbsToRel(window: this, r: r_abs);
8289 ImGuiID id = ImHashData(data_p: &r_rel, data_size: sizeof(r_rel), seed);
8290 return id;
8291}
8292
8293void ImGui::PushID(const char* str_id)
8294{
8295 ImGuiContext& g = *GImGui;
8296 ImGuiWindow* window = g.CurrentWindow;
8297 ImGuiID id = window->GetID(str: str_id);
8298 window->IDStack.push_back(v: id);
8299}
8300
8301void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8302{
8303 ImGuiContext& g = *GImGui;
8304 ImGuiWindow* window = g.CurrentWindow;
8305 ImGuiID id = window->GetID(str: str_id_begin, str_end: str_id_end);
8306 window->IDStack.push_back(v: id);
8307}
8308
8309void ImGui::PushID(const void* ptr_id)
8310{
8311 ImGuiContext& g = *GImGui;
8312 ImGuiWindow* window = g.CurrentWindow;
8313 ImGuiID id = window->GetID(ptr: ptr_id);
8314 window->IDStack.push_back(v: id);
8315}
8316
8317void ImGui::PushID(int int_id)
8318{
8319 ImGuiContext& g = *GImGui;
8320 ImGuiWindow* window = g.CurrentWindow;
8321 ImGuiID id = window->GetID(n: int_id);
8322 window->IDStack.push_back(v: id);
8323}
8324
8325// Push a given id value ignoring the ID stack as a seed.
8326void ImGui::PushOverrideID(ImGuiID id)
8327{
8328 ImGuiContext& g = *GImGui;
8329 ImGuiWindow* window = g.CurrentWindow;
8330#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8331 if (g.DebugHookIdInfo == id)
8332 DebugHookIdInfo(id, data_type: ImGuiDataType_ID, NULL, NULL);
8333#endif
8334 window->IDStack.push_back(v: id);
8335}
8336
8337// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8338// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8339// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8340ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8341{
8342 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
8343#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8344 ImGuiContext& g = *GImGui;
8345 if (g.DebugHookIdInfo == id)
8346 DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
8347#endif
8348 return id;
8349}
8350
8351ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8352{
8353 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
8354#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8355 ImGuiContext& g = *GImGui;
8356 if (g.DebugHookIdInfo == id)
8357 DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
8358#endif
8359 return id;
8360}
8361
8362void ImGui::PopID()
8363{
8364 ImGuiWindow* window = GImGui->CurrentWindow;
8365 IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8366 window->IDStack.pop_back();
8367}
8368
8369ImGuiID ImGui::GetID(const char* str_id)
8370{
8371 ImGuiWindow* window = GImGui->CurrentWindow;
8372 return window->GetID(str: str_id);
8373}
8374
8375ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8376{
8377 ImGuiWindow* window = GImGui->CurrentWindow;
8378 return window->GetID(str: str_id_begin, str_end: str_id_end);
8379}
8380
8381ImGuiID ImGui::GetID(const void* ptr_id)
8382{
8383 ImGuiWindow* window = GImGui->CurrentWindow;
8384 return window->GetID(ptr: ptr_id);
8385}
8386
8387ImGuiID ImGui::GetID(int int_id)
8388{
8389 ImGuiWindow* window = GImGui->CurrentWindow;
8390 return window->GetID(n: int_id);
8391}
8392IM_MSVC_RUNTIME_CHECKS_RESTORE
8393
8394//-----------------------------------------------------------------------------
8395// [SECTION] INPUTS
8396//-----------------------------------------------------------------------------
8397// - GetModForModKey() [Internal]
8398// - FixupKeyChord() [Internal]
8399// - GetKeyData() [Internal]
8400// - GetKeyIndex() [Internal]
8401// - GetKeyName()
8402// - GetKeyChordName() [Internal]
8403// - CalcTypematicRepeatAmount() [Internal]
8404// - GetTypematicRepeatRate() [Internal]
8405// - GetKeyPressedAmount() [Internal]
8406// - GetKeyMagnitude2d() [Internal]
8407//-----------------------------------------------------------------------------
8408// - UpdateKeyRoutingTable() [Internal]
8409// - GetRoutingIdFromOwnerId() [Internal]
8410// - GetShortcutRoutingData() [Internal]
8411// - CalcRoutingScore() [Internal]
8412// - SetShortcutRouting() [Internal]
8413// - TestShortcutRouting() [Internal]
8414//-----------------------------------------------------------------------------
8415// - IsKeyDown()
8416// - IsKeyPressed()
8417// - IsKeyReleased()
8418//-----------------------------------------------------------------------------
8419// - IsMouseDown()
8420// - IsMouseClicked()
8421// - IsMouseReleased()
8422// - IsMouseDoubleClicked()
8423// - GetMouseClickedCount()
8424// - IsMouseHoveringRect() [Internal]
8425// - IsMouseDragPastThreshold() [Internal]
8426// - IsMouseDragging()
8427// - GetMousePos()
8428// - SetMousePos() [Internal]
8429// - GetMousePosOnOpeningCurrentPopup()
8430// - IsMousePosValid()
8431// - IsAnyMouseDown()
8432// - GetMouseDragDelta()
8433// - ResetMouseDragDelta()
8434// - GetMouseCursor()
8435// - SetMouseCursor()
8436//-----------------------------------------------------------------------------
8437// - UpdateAliasKey()
8438// - GetMergedModsFromKeys()
8439// - UpdateKeyboardInputs()
8440// - UpdateMouseInputs()
8441//-----------------------------------------------------------------------------
8442// - LockWheelingWindow [Internal]
8443// - FindBestWheelingWindow [Internal]
8444// - UpdateMouseWheel() [Internal]
8445//-----------------------------------------------------------------------------
8446// - SetNextFrameWantCaptureKeyboard()
8447// - SetNextFrameWantCaptureMouse()
8448//-----------------------------------------------------------------------------
8449// - GetInputSourceName() [Internal]
8450// - DebugPrintInputEvent() [Internal]
8451// - UpdateInputEvents() [Internal]
8452//-----------------------------------------------------------------------------
8453// - GetKeyOwner() [Internal]
8454// - TestKeyOwner() [Internal]
8455// - SetKeyOwner() [Internal]
8456// - SetItemKeyOwner() [Internal]
8457// - Shortcut() [Internal]
8458//-----------------------------------------------------------------------------
8459
8460static ImGuiKeyChord GetModForModKey(ImGuiKey key)
8461{
8462 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
8463 return ImGuiMod_Ctrl;
8464 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
8465 return ImGuiMod_Shift;
8466 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
8467 return ImGuiMod_Alt;
8468 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
8469 return ImGuiMod_Super;
8470 return ImGuiMod_None;
8471}
8472
8473ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
8474{
8475 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8476 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8477 if (IsModKey(key))
8478 key_chord |= GetModForModKey(key);
8479 return key_chord;
8480}
8481
8482ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8483{
8484 ImGuiContext& g = *ctx;
8485
8486 // Special storage location for mods
8487 if (key & ImGuiMod_Mask_)
8488 key = ConvertSingleModFlagToKey(key);
8489
8490#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8491 IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8492 if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8493 key = (ImGuiKey)g.IO.KeyMap[key]; // Remap native->imgui or imgui->native
8494#else
8495 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8496#endif
8497 return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8498}
8499
8500#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8501// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
8502ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8503{
8504 ImGuiContext& g = *GImGui;
8505 IM_ASSERT(IsNamedKey(key));
8506 const ImGuiKeyData* key_data = GetKeyData(key);
8507 return (ImGuiKey)(key_data - g.IO.KeysData);
8508}
8509#endif
8510
8511// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8512static const char* const GKeyNames[] =
8513{
8514 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8515 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8516 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8517 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8518 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8519 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8520 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8521 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8522 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8523 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8524 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8525 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8526 "AppBack", "AppForward",
8527 "GamepadStart", "GamepadBack",
8528 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8529 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8530 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8531 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8532 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8533 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8534 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8535};
8536IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8537
8538const char* ImGui::GetKeyName(ImGuiKey key)
8539{
8540 if (key == ImGuiKey_None)
8541 return "None";
8542#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8543 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8544#else
8545 ImGuiContext& g = *GImGui;
8546 if (IsLegacyKey(key))
8547 {
8548 if (g.IO.KeyMap[key] == -1)
8549 return "N/A";
8550 IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8551 key = (ImGuiKey)g.IO.KeyMap[key];
8552 }
8553#endif
8554 if (key & ImGuiMod_Mask_)
8555 key = ConvertSingleModFlagToKey(key);
8556 if (!IsNamedKey(key))
8557 return "Unknown";
8558
8559 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8560}
8561
8562// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
8563// Lifetime of return value: valid until next call to same function.
8564const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
8565{
8566 ImGuiContext& g = *GImGui;
8567
8568 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8569 if (IsModKey(key))
8570 key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
8571 ImFormatString(buf: g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), fmt: "%s%s%s%s%s",
8572 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8573 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8574 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8575 (key_chord & ImGuiMod_Super) ? "Super+" : "",
8576 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
8577 size_t len;
8578 if (key == ImGuiKey_None && key_chord != 0)
8579 if ((len = strlen(s: g.TempKeychordName)) != 0) // Remove trailing '+'
8580 g.TempKeychordName[len - 1] = 0;
8581 return g.TempKeychordName;
8582}
8583
8584// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8585// t1 = current time (e.g.: g.Time)
8586// An event is triggered at:
8587// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
8588int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8589{
8590 if (t1 == 0.0f)
8591 return 1;
8592 if (t0 >= t1)
8593 return 0;
8594 if (repeat_rate <= 0.0f)
8595 return (t0 < repeat_delay) && (t1 >= repeat_delay);
8596 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8597 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8598 const int count = count_t1 - count_t0;
8599 return count;
8600}
8601
8602void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8603{
8604 ImGuiContext& g = *GImGui;
8605 switch (flags & ImGuiInputFlags_RepeatRateMask_)
8606 {
8607 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8608 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8609 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8610 }
8611}
8612
8613// Return value representing the number of presses in the last time period, for the given repeat rate
8614// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8615int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8616{
8617 ImGuiContext& g = *GImGui;
8618 const ImGuiKeyData* key_data = GetKeyData(key);
8619 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)
8620 return 0;
8621 const float t = key_data->DownDuration;
8622 return CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay, repeat_rate);
8623}
8624
8625// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8626ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8627{
8628 return ImVec2(
8629 GetKeyData(key: key_right)->AnalogValue - GetKeyData(key: key_left)->AnalogValue,
8630 GetKeyData(key: key_down)->AnalogValue - GetKeyData(key: key_up)->AnalogValue);
8631}
8632
8633// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8634// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
8635// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
8636// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8637static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8638{
8639 ImGuiContext& g = *GImGui;
8640 rt->EntriesNext.resize(new_size: 0);
8641 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8642 {
8643 const int new_routing_start_idx = rt->EntriesNext.Size;
8644 ImGuiKeyRoutingData* routing_entry;
8645 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8646 {
8647 routing_entry = &rt->Entries[old_routing_idx];
8648 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
8649 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8650 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
8651 routing_entry->RoutingNextScore = 255;
8652 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
8653 continue;
8654 rt->EntriesNext.push_back(v: *routing_entry); // Write alive ones into new buffer
8655
8656 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8657 // This is the result of previous frame's SetShortcutRouting() call.
8658 if (routing_entry->Mods == g.IO.KeyMods)
8659 {
8660 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
8661 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
8662 {
8663 owner_data->OwnerCurr = routing_entry->RoutingCurr;
8664 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
8665 }
8666 }
8667 }
8668
8669 // Rewrite linked-list
8670 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8671 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8672 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8673 }
8674 rt->Entries.swap(rhs&: rt->EntriesNext); // Swap new and old indexes
8675}
8676
8677// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8678static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8679{
8680 ImGuiContext& g = *GImGui;
8681 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8682}
8683
8684ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8685{
8686 // Majority of shortcuts will be Key + any number of Mods
8687 // We accept _Single_ mod with ImGuiKey_None.
8688 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
8689 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
8690 // - Shortcut(ImGuiMod_Ctrl); // Legal
8691 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
8692 ImGuiContext& g = *GImGui;
8693 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8694 ImGuiKeyRoutingData* routing_data;
8695 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8696 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8697 if (key == ImGuiKey_None)
8698 key = ConvertSingleModFlagToKey(key: mods);
8699 IM_ASSERT(IsNamedKey(key));
8700
8701 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8702 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8703 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8704 {
8705 routing_data = &rt->Entries[idx];
8706 if (routing_data->Mods == mods)
8707 return routing_data;
8708 }
8709
8710 // Add to linked-list
8711 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8712 rt->Entries.push_back(v: ImGuiKeyRoutingData());
8713 routing_data = &rt->Entries[routing_data_idx];
8714 routing_data->Mods = (ImU16)mods;
8715 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8716 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8717 return routing_data;
8718}
8719
8720// Current score encoding (lower is highest priority):
8721// - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
8722// - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
8723// - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
8724// - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8725// - 254: ImGuiInputFlags_RouteGlobal
8726// - 255: never route
8727// 'flags' should include an explicit routing policy
8728static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
8729{
8730 ImGuiContext& g = *GImGui;
8731 if (flags & ImGuiInputFlags_RouteFocused)
8732 {
8733 // ActiveID gets top priority
8734 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8735 if (owner_id != 0 && g.ActiveId == owner_id)
8736 return 1;
8737
8738 // Score based on distance to focused window (lower is better)
8739 // Assuming both windows are submitting a routing request,
8740 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8741 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
8742 // Assuming only WindowA is submitting a routing request,
8743 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8744 // This essentially follow the window->ParentWindowForFocusRoute chain.
8745 if (focus_scope_id == 0)
8746 return 255;
8747 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
8748 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
8749 return 3 + index_in_focus_path;
8750 return 255;
8751 }
8752 else if (flags & ImGuiInputFlags_RouteActive)
8753 {
8754 if (owner_id != 0 && g.ActiveId == owner_id)
8755 return 1;
8756 return 255;
8757 }
8758 else if (flags & ImGuiInputFlags_RouteGlobal)
8759 {
8760 if (flags & ImGuiInputFlags_RouteOverActive)
8761 return 0;
8762 if (flags & ImGuiInputFlags_RouteOverFocused)
8763 return 2;
8764 return 254;
8765 }
8766 IM_ASSERT(0);
8767 return 0;
8768}
8769
8770// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
8771// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
8772static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
8773{
8774 // Mimic 'ignore_char_inputs' logic in InputText()
8775 ImGuiContext& g = *GImGui;
8776
8777 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
8778 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8779 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
8780 if (ignore_char_inputs)
8781 return false;
8782
8783 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
8784 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8785 return g.KeysMayBeCharInput.TestBit(n: key);
8786}
8787
8788// Request a desired route for an input chord (key + mods).
8789// Return true if the route is available this frame.
8790// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8791// (Conceptually this does a "Submit for next frame" + "Test for current frame".
8792// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8793bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
8794{
8795 ImGuiContext& g = *GImGui;
8796 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
8797 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8798 else
8799 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
8800 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
8801 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
8802 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
8803
8804 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8805 key_chord = FixupKeyChord(key_chord);
8806
8807 // [DEBUG] Debug break requested by user
8808 if (g.DebugBreakInShortcutRouting == key_chord)
8809 IM_DEBUG_BREAK();
8810
8811 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8812 if (g.NavWindow == NULL)
8813 return false;
8814
8815 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
8816 if (flags & ImGuiInputFlags_RouteAlways)
8817 {
8818 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
8819 return true;
8820 }
8821
8822 // Specific culling when there's an active item.
8823 if (g.ActiveId != 0 && g.ActiveId != owner_id)
8824 {
8825 if (flags & ImGuiInputFlags_RouteActive)
8826 return false;
8827
8828 // Cull shortcuts with no modifiers when it could generate a character.
8829 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
8830 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
8831 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
8832 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
8833 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
8834 {
8835 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
8836 return false;
8837 }
8838
8839 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
8840 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
8841 {
8842 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8843 if (key == ImGuiKey_None)
8844 key = ConvertSingleModFlagToKey(key: (ImGuiKey)(key_chord & ImGuiMod_Mask_));
8845 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
8846 return false;
8847 }
8848 }
8849
8850 // Where do we evaluate route for?
8851 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
8852 if (flags & ImGuiInputFlags_RouteFromRootWindow)
8853 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
8854
8855 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
8856 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
8857 if (score == 255)
8858 return false;
8859
8860 // Submit routing for NEXT frame (assuming score is sufficient)
8861 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8862 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8863 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8864 if (score < routing_data->RoutingNextScore)
8865 {
8866 routing_data->RoutingNext = owner_id;
8867 routing_data->RoutingNextScore = (ImU8)score;
8868 }
8869
8870 // Return routing state for CURRENT frame
8871 if (routing_data->RoutingCurr == owner_id)
8872 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
8873 return routing_data->RoutingCurr == owner_id;
8874}
8875
8876// Currently unused by core (but used by tests)
8877// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8878bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8879{
8880 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8881 key_chord = FixupKeyChord(key_chord);
8882 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8883 return routing_data->RoutingCurr == routing_id;
8884}
8885
8886// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8887// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8888bool ImGui::IsKeyDown(ImGuiKey key)
8889{
8890 return IsKeyDown(key, ImGuiKeyOwner_Any);
8891}
8892
8893bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8894{
8895 const ImGuiKeyData* key_data = GetKeyData(key);
8896 if (!key_data->Down)
8897 return false;
8898 if (!TestKeyOwner(key, owner_id))
8899 return false;
8900 return true;
8901}
8902
8903bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8904{
8905 return IsKeyPressed(key, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
8906}
8907
8908// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8909bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
8910{
8911 const ImGuiKeyData* key_data = GetKeyData(key);
8912 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)
8913 return false;
8914 const float t = key_data->DownDuration;
8915 if (t < 0.0f)
8916 return false;
8917 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8918 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
8919 flags |= ImGuiInputFlags_Repeat;
8920
8921 bool pressed = (t == 0.0f);
8922 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
8923 {
8924 float repeat_delay, repeat_rate;
8925 GetTypematicRepeatRate(flags, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
8926 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8927 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
8928 {
8929 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
8930 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
8931 ImGuiContext& g = *GImGui;
8932 double key_pressed_time = g.Time - t + 0.00001f;
8933 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
8934 pressed = false;
8935 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
8936 pressed = false;
8937 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
8938 pressed = false;
8939 }
8940 }
8941 if (!pressed)
8942 return false;
8943 if (!TestKeyOwner(key, owner_id))
8944 return false;
8945 return true;
8946}
8947
8948bool ImGui::IsKeyReleased(ImGuiKey key)
8949{
8950 return IsKeyReleased(key, ImGuiKeyOwner_Any);
8951}
8952
8953bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8954{
8955 const ImGuiKeyData* key_data = GetKeyData(key);
8956 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8957 return false;
8958 if (!TestKeyOwner(key, owner_id))
8959 return false;
8960 return true;
8961}
8962
8963bool ImGui::IsMouseDown(ImGuiMouseButton button)
8964{
8965 ImGuiContext& g = *GImGui;
8966 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8967 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.
8968}
8969
8970bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8971{
8972 ImGuiContext& g = *GImGui;
8973 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8974 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.
8975}
8976
8977bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8978{
8979 return IsMouseClicked(button, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
8980}
8981
8982bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
8983{
8984 ImGuiContext& g = *GImGui;
8985 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8986 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)
8987 return false;
8988 const float t = g.IO.MouseDownDuration[button];
8989 if (t < 0.0f)
8990 return false;
8991 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
8992
8993 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8994 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);
8995 if (!pressed)
8996 return false;
8997
8998 if (!TestKeyOwner(key: MouseButtonToKey(button), owner_id))
8999 return false;
9000
9001 return true;
9002}
9003
9004bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9005{
9006 ImGuiContext& g = *GImGui;
9007 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9008 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9009}
9010
9011bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9012{
9013 ImGuiContext& g = *GImGui;
9014 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9015 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9016}
9017
9018bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9019{
9020 ImGuiContext& g = *GImGui;
9021 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9022 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any);
9023}
9024
9025bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9026{
9027 ImGuiContext& g = *GImGui;
9028 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9029 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), owner_id);
9030}
9031
9032int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9033{
9034 ImGuiContext& g = *GImGui;
9035 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9036 return g.IO.MouseClickedCount[button];
9037}
9038
9039// Test if mouse cursor is hovering given rectangle
9040// NB- Rectangle is clipped by our current clip setting
9041// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9042bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9043{
9044 ImGuiContext& g = *GImGui;
9045
9046 // Clip
9047 ImRect rect_clipped(r_min, r_max);
9048 if (clip)
9049 rect_clipped.ClipWith(r: g.CurrentWindow->ClipRect);
9050
9051 // Hit testing, expanded for touch input
9052 if (!rect_clipped.ContainsWithPad(p: g.IO.MousePos, pad: g.Style.TouchExtraPadding))
9053 return false;
9054 return true;
9055}
9056
9057// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9058// [Internal] This doesn't test if the button is pressed
9059bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9060{
9061 ImGuiContext& g = *GImGui;
9062 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9063 if (lock_threshold < 0.0f)
9064 lock_threshold = g.IO.MouseDragThreshold;
9065 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9066}
9067
9068bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9069{
9070 ImGuiContext& g = *GImGui;
9071 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9072 if (!g.IO.MouseDown[button])
9073 return false;
9074 return IsMouseDragPastThreshold(button, lock_threshold);
9075}
9076
9077ImVec2 ImGui::GetMousePos()
9078{
9079 ImGuiContext& g = *GImGui;
9080 return g.IO.MousePos;
9081}
9082
9083// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9084// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9085void ImGui::TeleportMousePos(const ImVec2& pos)
9086{
9087 ImGuiContext& g = *GImGui;
9088 g.IO.MousePos = g.IO.MousePosPrev = pos;
9089 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9090 g.IO.WantSetMousePos = true;
9091 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9092}
9093
9094// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9095ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9096{
9097 ImGuiContext& g = *GImGui;
9098 if (g.BeginPopupStack.Size > 0)
9099 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9100 return g.IO.MousePos;
9101}
9102
9103// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9104bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9105{
9106 // The assert is only to silence a false-positive in XCode Static Analysis.
9107 // 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).
9108 IM_ASSERT(GImGui != NULL);
9109 const float MOUSE_INVALID = -256000.0f;
9110 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9111 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9112}
9113
9114// [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.
9115bool ImGui::IsAnyMouseDown()
9116{
9117 ImGuiContext& g = *GImGui;
9118 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9119 if (g.IO.MouseDown[n])
9120 return true;
9121 return false;
9122}
9123
9124// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9125// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9126// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9127ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9128{
9129 ImGuiContext& g = *GImGui;
9130 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9131 if (lock_threshold < 0.0f)
9132 lock_threshold = g.IO.MouseDragThreshold;
9133 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9134 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9135 if (IsMousePosValid(mouse_pos: &g.IO.MousePos) && IsMousePosValid(mouse_pos: &g.IO.MouseClickedPos[button]))
9136 return g.IO.MousePos - g.IO.MouseClickedPos[button];
9137 return ImVec2(0.0f, 0.0f);
9138}
9139
9140void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9141{
9142 ImGuiContext& g = *GImGui;
9143 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9144 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9145 g.IO.MouseClickedPos[button] = g.IO.MousePos;
9146}
9147
9148// Get desired mouse cursor shape.
9149// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9150// updated during the frame, and locked in EndFrame()/Render().
9151// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9152ImGuiMouseCursor ImGui::GetMouseCursor()
9153{
9154 ImGuiContext& g = *GImGui;
9155 return g.MouseCursor;
9156}
9157
9158void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9159{
9160 ImGuiContext& g = *GImGui;
9161 g.MouseCursor = cursor_type;
9162}
9163
9164static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9165{
9166 IM_ASSERT(ImGui::IsAliasKey(key));
9167 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9168 key_data->Down = v;
9169 key_data->AnalogValue = analog_value;
9170}
9171
9172// [Internal] Do not use directly
9173static ImGuiKeyChord GetMergedModsFromKeys()
9174{
9175 ImGuiKeyChord mods = 0;
9176 if (ImGui::IsKeyDown(key: ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
9177 if (ImGui::IsKeyDown(key: ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
9178 if (ImGui::IsKeyDown(key: ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
9179 if (ImGui::IsKeyDown(key: ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
9180 return mods;
9181}
9182
9183static void ImGui::UpdateKeyboardInputs()
9184{
9185 ImGuiContext& g = *GImGui;
9186 ImGuiIO& io = g.IO;
9187
9188 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9189 io.ClearInputKeys();
9190
9191 // Import legacy keys or verify they are not used
9192#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9193 if (io.BackendUsingLegacyKeyArrays == 0)
9194 {
9195 // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9196 for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9197 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!");
9198 }
9199 else
9200 {
9201 if (g.FrameCount == 0)
9202 for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9203 IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9204
9205 // Build reverse KeyMap (Named -> Legacy)
9206 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9207 if (io.KeyMap[n] != -1)
9208 {
9209 IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9210 io.KeyMap[io.KeyMap[n]] = n;
9211 }
9212
9213 // Import legacy keys into new ones
9214 for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9215 if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9216 {
9217 const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9218 IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9219 io.KeysData[key].Down = io.KeysDown[n];
9220 if (key != n)
9221 io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9222 io.BackendUsingLegacyKeyArrays = 1;
9223 }
9224 if (io.BackendUsingLegacyKeyArrays == 1)
9225 {
9226 GetKeyData(key: ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9227 GetKeyData(key: ImGuiMod_Shift)->Down = io.KeyShift;
9228 GetKeyData(key: ImGuiMod_Alt)->Down = io.KeyAlt;
9229 GetKeyData(key: ImGuiMod_Super)->Down = io.KeySuper;
9230 }
9231 }
9232#endif
9233
9234 // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9235#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9236 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9237 if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9238 {
9239 #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)
9240 #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)
9241 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9242 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9243 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9244 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9245 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9246 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9247 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9248 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9249 MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9250 MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9251 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9252 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9253 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9254 MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9255 #undef NAV_MAP_KEY
9256 }
9257#endif
9258
9259 // Update aliases
9260 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9261 UpdateAliasKey(key: MouseButtonToKey(button: n), v: io.MouseDown[n], analog_value: io.MouseDown[n] ? 1.0f : 0.0f);
9262 UpdateAliasKey(key: ImGuiKey_MouseWheelX, v: io.MouseWheelH != 0.0f, analog_value: io.MouseWheelH);
9263 UpdateAliasKey(key: ImGuiKey_MouseWheelY, v: io.MouseWheel != 0.0f, analog_value: io.MouseWheel);
9264
9265 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9266 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9267 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9268 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9269 const ImGuiKeyChord prev_key_mods = io.KeyMods;
9270 io.KeyMods = GetMergedModsFromKeys();
9271 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9272 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9273 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9274 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9275 if (prev_key_mods != io.KeyMods)
9276 g.LastKeyModsChangeTime = g.Time;
9277 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9278 g.LastKeyModsChangeFromNoneTime = g.Time;
9279
9280 // Clear gamepad data if disabled
9281 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9282 for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9283 {
9284 io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9285 io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9286 }
9287
9288 // Update keys
9289 for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9290 {
9291 ImGuiKeyData* key_data = &io.KeysData[i];
9292 key_data->DownDurationPrev = key_data->DownDuration;
9293 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9294 if (key_data->DownDuration == 0.0f)
9295 {
9296 ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9297 if (IsKeyboardKey(key))
9298 g.LastKeyboardKeyPressTime = g.Time;
9299 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9300 g.LastKeyboardKeyPressTime = g.Time;
9301 }
9302 }
9303
9304 // Update keys/input owner (named keys only): one entry per key
9305 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9306 {
9307 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9308 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9309 owner_data->OwnerCurr = owner_data->OwnerNext;
9310 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.
9311 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9312 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
9313 }
9314
9315 // Update key routing (for e.g. shortcuts)
9316 UpdateKeyRoutingTable(rt: &g.KeysRoutingTable);
9317}
9318
9319static void ImGui::UpdateMouseInputs()
9320{
9321 ImGuiContext& g = *GImGui;
9322 ImGuiIO& io = g.IO;
9323
9324 // Mouse Wheel swapping flag
9325 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9326 // - We avoid doing it on OSX as it the OS input layer handles this already.
9327 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9328 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9329 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9330
9331 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9332 if (IsMousePosValid(mouse_pos: &io.MousePos))
9333 io.MousePos = g.MouseLastValidPos = ImFloor(v: io.MousePos);
9334
9335 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9336 if (IsMousePosValid(mouse_pos: &io.MousePos) && IsMousePosValid(mouse_pos: &io.MousePosPrev))
9337 io.MouseDelta = io.MousePos - io.MousePosPrev;
9338 else
9339 io.MouseDelta = ImVec2(0.0f, 0.0f);
9340
9341 // Update stationary timer.
9342 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9343 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9344 const bool mouse_stationary = (ImLengthSqr(lhs: io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9345 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9346 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9347
9348 // 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.
9349 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9350 g.NavDisableMouseHover = false;
9351
9352 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9353 {
9354 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9355 io.MouseClickedCount[i] = 0; // Will be filled below
9356 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9357 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9358 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9359 if (io.MouseClicked[i])
9360 {
9361 bool is_repeated_click = false;
9362 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9363 {
9364 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9365 if (ImLengthSqr(lhs: delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9366 is_repeated_click = true;
9367 }
9368 if (is_repeated_click)
9369 io.MouseClickedLastCount[i]++;
9370 else
9371 io.MouseClickedLastCount[i] = 1;
9372 io.MouseClickedTime[i] = g.Time;
9373 io.MouseClickedPos[i] = io.MousePos;
9374 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9375 io.MouseDragMaxDistanceSqr[i] = 0.0f;
9376 }
9377 else if (io.MouseDown[i])
9378 {
9379 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9380 float delta_sqr_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? ImLengthSqr(lhs: io.MousePos - io.MouseClickedPos[i]) : 0.0f;
9381 io.MouseDragMaxDistanceSqr[i] = ImMax(lhs: io.MouseDragMaxDistanceSqr[i], rhs: delta_sqr_click_pos);
9382 }
9383
9384 // We provide io.MouseDoubleClicked[] as a legacy service
9385 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9386
9387 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9388 if (io.MouseClicked[i])
9389 g.NavDisableMouseHover = false;
9390 }
9391}
9392
9393static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9394{
9395 ImGuiContext& g = *GImGui;
9396 if (window)
9397 g.WheelingWindowReleaseTimer = ImMin(lhs: g.WheelingWindowReleaseTimer + ImAbs(x: wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, rhs: WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9398 else
9399 g.WheelingWindowReleaseTimer = 0.0f;
9400 if (g.WheelingWindow == window)
9401 return;
9402 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9403 g.WheelingWindow = window;
9404 g.WheelingWindowRefMousePos = g.IO.MousePos;
9405 if (window == NULL)
9406 {
9407 g.WheelingWindowStartFrame = -1;
9408 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9409 }
9410}
9411
9412static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9413{
9414 // For each axis, find window in the hierarchy that may want to use scrolling
9415 ImGuiContext& g = *GImGui;
9416 ImGuiWindow* windows[2] = { NULL, NULL };
9417 for (int axis = 0; axis < 2; axis++)
9418 if (wheel[axis] != 0.0f)
9419 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9420 {
9421 // Bubble up into parent window if:
9422 // - a child window doesn't allow any scrolling.
9423 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9424 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9425 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9426 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9427 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9428 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9429 break; // select this window
9430 }
9431 if (windows[0] == NULL && windows[1] == NULL)
9432 return NULL;
9433
9434 // If there's only one window or only one axis then there's no ambiguity
9435 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9436 return windows[1] ? windows[1] : windows[0];
9437
9438 // If candidate are different windows we need to decide which one to prioritize
9439 // - First frame: only find a winner if one axis is zero.
9440 // - Subsequent frames: only find a winner when one is more than the other.
9441 if (g.WheelingWindowStartFrame == -1)
9442 g.WheelingWindowStartFrame = g.FrameCount;
9443 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9444 {
9445 g.WheelingWindowWheelRemainder = wheel;
9446 return NULL;
9447 }
9448 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9449}
9450
9451// Called by NewFrame()
9452void ImGui::UpdateMouseWheel()
9453{
9454 // Reset the locked window if we move the mouse or after the timer elapses.
9455 // 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)
9456 ImGuiContext& g = *GImGui;
9457 if (g.WheelingWindow != NULL)
9458 {
9459 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9460 if (IsMousePosValid() && ImLengthSqr(lhs: g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9461 g.WheelingWindowReleaseTimer = 0.0f;
9462 if (g.WheelingWindowReleaseTimer <= 0.0f)
9463 LockWheelingWindow(NULL, wheel_amount: 0.0f);
9464 }
9465
9466 ImVec2 wheel;
9467 wheel.x = TestKeyOwner(key: ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
9468 wheel.y = TestKeyOwner(key: ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
9469
9470 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9471 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9472 if (!mouse_window || mouse_window->Collapsed)
9473 return;
9474
9475 // Zoom / Scale window
9476 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9477 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9478 {
9479 LockWheelingWindow(window: mouse_window, wheel_amount: wheel.y);
9480 ImGuiWindow* window = mouse_window;
9481 const float new_font_scale = ImClamp(v: window->FontWindowScale + g.IO.MouseWheel * 0.10f, mn: 0.50f, mx: 2.50f);
9482 const float scale = new_font_scale / window->FontWindowScale;
9483 window->FontWindowScale = new_font_scale;
9484 if (window == window->RootWindow)
9485 {
9486 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9487 SetWindowPos(window, pos: window->Pos + offset, cond: 0);
9488 window->Size = ImTrunc(v: window->Size * scale);
9489 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
9490 }
9491 return;
9492 }
9493 if (g.IO.KeyCtrl)
9494 return;
9495
9496 // Mouse wheel scrolling
9497 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9498 if (g.IO.MouseWheelRequestAxisSwap)
9499 wheel = ImVec2(wheel.y, 0.0f);
9500
9501 // Maintain a rough average of moving magnitude on both axises
9502 // FIXME: should by based on wall clock time rather than frame-counter
9503 g.WheelingAxisAvg.x = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.x, sample: ImAbs(x: wheel.x), n: 30);
9504 g.WheelingAxisAvg.y = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.y, sample: ImAbs(x: wheel.y), n: 30);
9505
9506 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9507 wheel += g.WheelingWindowWheelRemainder;
9508 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9509 if (wheel.x == 0.0f && wheel.y == 0.0f)
9510 return;
9511
9512 // Mouse wheel scrolling: find target and apply
9513 // - don't renew lock if axis doesn't apply on the window.
9514 // - select a main axis when both axises are being moved.
9515 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9516 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9517 {
9518 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9519 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9520 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9521 if (do_scroll[ImGuiAxis_X])
9522 {
9523 LockWheelingWindow(window, wheel_amount: wheel.x);
9524 float max_step = window->InnerRect.GetWidth() * 0.67f;
9525 float scroll_step = ImTrunc(f: ImMin(lhs: 2 * window->CalcFontSize(), rhs: max_step));
9526 SetScrollX(window, scroll_x: window->Scroll.x - wheel.x * scroll_step);
9527 g.WheelingWindowScrolledFrame = g.FrameCount;
9528 }
9529 if (do_scroll[ImGuiAxis_Y])
9530 {
9531 LockWheelingWindow(window, wheel_amount: wheel.y);
9532 float max_step = window->InnerRect.GetHeight() * 0.67f;
9533 float scroll_step = ImTrunc(f: ImMin(lhs: 5 * window->CalcFontSize(), rhs: max_step));
9534 SetScrollY(window, scroll_y: window->Scroll.y - wheel.y * scroll_step);
9535 g.WheelingWindowScrolledFrame = g.FrameCount;
9536 }
9537 }
9538}
9539
9540void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9541{
9542 ImGuiContext& g = *GImGui;
9543 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9544}
9545
9546void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9547{
9548 ImGuiContext& g = *GImGui;
9549 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9550}
9551
9552#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9553static const char* GetInputSourceName(ImGuiInputSource source)
9554{
9555 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
9556 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9557 return input_source_names[source];
9558}
9559static const char* GetMouseSourceName(ImGuiMouseSource source)
9560{
9561 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9562 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9563 return mouse_source_names[source];
9564}
9565static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9566{
9567 ImGuiContext& g = *GImGui;
9568 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; }
9569 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; }
9570 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; }
9571 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; }
9572 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9573 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9574}
9575#endif
9576
9577// Process input queue
9578// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9579// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9580// - 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)
9581void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9582{
9583 ImGuiContext& g = *GImGui;
9584 ImGuiIO& io = g.IO;
9585
9586 // Only trickle chars<>key when working with InputText()
9587 // FIXME: InputText() could parse event trail?
9588 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9589 const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9590
9591 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9592 int mouse_button_changed = 0x00;
9593 ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9594
9595 int event_n = 0;
9596 for (; event_n < g.InputEventsQueue.Size; event_n++)
9597 {
9598 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9599 if (e->Type == ImGuiInputEventType_MousePos)
9600 {
9601 if (g.IO.WantSetMousePos)
9602 continue;
9603 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9604 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9605 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9606 break;
9607 io.MousePos = event_pos;
9608 io.MouseSource = e->MousePos.MouseSource;
9609 mouse_moved = true;
9610 }
9611 else if (e->Type == ImGuiInputEventType_MouseButton)
9612 {
9613 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9614 const ImGuiMouseButton button = e->MouseButton.Button;
9615 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9616 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9617 break;
9618 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9619 break;
9620 io.MouseDown[button] = e->MouseButton.Down;
9621 io.MouseSource = e->MouseButton.MouseSource;
9622 mouse_button_changed |= (1 << button);
9623 }
9624 else if (e->Type == ImGuiInputEventType_MouseWheel)
9625 {
9626 // Trickling Rule: Stop processing queued events if we got multiple action on the event
9627 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9628 break;
9629 io.MouseWheelH += e->MouseWheel.WheelX;
9630 io.MouseWheel += e->MouseWheel.WheelY;
9631 io.MouseSource = e->MouseWheel.MouseSource;
9632 mouse_wheeled = true;
9633 }
9634 else if (e->Type == ImGuiInputEventType_Key)
9635 {
9636 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9637 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9638 continue;
9639 ImGuiKey key = e->Key.Key;
9640 IM_ASSERT(key != ImGuiKey_None);
9641 ImGuiKeyData* key_data = GetKeyData(key);
9642 const int key_data_index = (int)(key_data - g.IO.KeysData);
9643 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(n: key_data_index) || text_inputted || mouse_button_changed != 0))
9644 break;
9645 key_data->Down = e->Key.Down;
9646 key_data->AnalogValue = e->Key.AnalogValue;
9647 key_changed = true;
9648 key_changed_mask.SetBit(key_data_index);
9649
9650 // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9651#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9652 io.KeysDown[key_data_index] = key_data->Down;
9653 if (io.KeyMap[key_data_index] != -1)
9654 io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9655#endif
9656 }
9657 else if (e->Type == ImGuiInputEventType_Text)
9658 {
9659 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9660 continue;
9661 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9662 if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9663 break;
9664 unsigned int c = e->Text.Char;
9665 io.InputQueueCharacters.push_back(v: c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9666 if (trickle_interleaved_keys_and_text)
9667 text_inputted = true;
9668 }
9669 else if (e->Type == ImGuiInputEventType_Focus)
9670 {
9671 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9672 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9673 const bool focus_lost = !e->AppFocused.Focused;
9674 io.AppFocusLost = focus_lost;
9675 }
9676 else
9677 {
9678 IM_ASSERT(0 && "Unknown event!");
9679 }
9680 }
9681
9682 // Record trail (for domain-specific applications wanting to access a precise trail)
9683 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9684 for (int n = 0; n < event_n; n++)
9685 g.InputEventsTrail.push_back(v: g.InputEventsQueue[n]);
9686
9687 // [DEBUG]
9688#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9689 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9690 for (int n = 0; n < g.InputEventsQueue.Size; n++)
9691 DebugPrintInputEvent(prefix: n < event_n ? "Processed" : "Remaining", e: &g.InputEventsQueue[n]);
9692#endif
9693
9694 // Remaining events will be processed on the next frame
9695 if (event_n == g.InputEventsQueue.Size)
9696 g.InputEventsQueue.resize(new_size: 0);
9697 else
9698 g.InputEventsQueue.erase(it: g.InputEventsQueue.Data, it_last: g.InputEventsQueue.Data + event_n);
9699
9700 // Clear buttons state when focus is lost
9701 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9702 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9703 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9704 if (g.IO.AppFocusLost)
9705 {
9706 g.IO.ClearInputKeys();
9707 g.IO.ClearInputMouse();
9708 }
9709}
9710
9711ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9712{
9713 if (!IsNamedKeyOrMod(key))
9714 return ImGuiKeyOwner_NoOwner;
9715
9716 ImGuiContext& g = *GImGui;
9717 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
9718 ImGuiID owner_id = owner_data->OwnerCurr;
9719
9720 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9721 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9722 return ImGuiKeyOwner_NoOwner;
9723
9724 return owner_id;
9725}
9726
9727// TestKeyOwner(..., ID) : (owner == None || owner == ID)
9728// TestKeyOwner(..., None) : (owner == None)
9729// TestKeyOwner(..., Any) : no owner test
9730// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9731bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9732{
9733 if (!IsNamedKeyOrMod(key))
9734 return true;
9735
9736 ImGuiContext& g = *GImGui;
9737 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9738 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9739 return false;
9740
9741 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
9742 if (owner_id == ImGuiKeyOwner_Any)
9743 return (owner_data->LockThisFrame == false);
9744
9745 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9746 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9747 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9748 if (owner_data->OwnerCurr != owner_id)
9749 {
9750 if (owner_data->LockThisFrame)
9751 return false;
9752 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
9753 return false;
9754 }
9755
9756 return true;
9757}
9758
9759// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9760// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9761// - SetKeyOwner(..., None) : clears owner
9762// - SetKeyOwner(..., Any, !Lock) : illegal (assert)
9763// - SetKeyOwner(..., Any or None, Lock) : set lock
9764void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9765{
9766 ImGuiContext& g = *GImGui;
9767 IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9768 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9769 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
9770
9771 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
9772 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9773
9774 // We cannot lock by default as it would likely break lots of legacy code.
9775 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9776 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9777 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9778}
9779
9780// Rarely used helper
9781void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9782{
9783 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(key: ImGuiMod_Ctrl, owner_id, flags); }
9784 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(key: ImGuiMod_Shift, owner_id, flags); }
9785 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(key: ImGuiMod_Alt, owner_id, flags); }
9786 if (key_chord & ImGuiMod_Super) { SetKeyOwner(key: ImGuiMod_Super, owner_id, flags); }
9787 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner(key: (ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9788}
9789
9790// This is more or less equivalent to:
9791// if (IsItemHovered() || IsItemActive())
9792// SetKeyOwner(key, GetItemID());
9793// 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.
9794// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9795// 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.
9796void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9797{
9798 ImGuiContext& g = *GImGui;
9799 ImGuiID id = g.LastItemData.ID;
9800 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9801 return;
9802 if ((flags & ImGuiInputFlags_CondMask_) == 0)
9803 flags |= ImGuiInputFlags_CondDefault_;
9804 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9805 {
9806 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9807 SetKeyOwner(key, owner_id: id, flags: flags & ~ImGuiInputFlags_CondMask_);
9808 }
9809}
9810
9811void ImGui::SetItemKeyOwner(ImGuiKey key)
9812{
9813 SetItemKeyOwner(key, flags: ImGuiInputFlags_None);
9814}
9815
9816// This is the only public API until we expose owner_id versions of the API as replacements.
9817bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
9818{
9819 return IsKeyChordPressed(key_chord, flags: ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9820}
9821
9822// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
9823bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9824{
9825 ImGuiContext& g = *GImGui;
9826 key_chord = FixupKeyChord(key_chord);
9827 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9828 if (g.IO.KeyMods != mods)
9829 return false;
9830
9831 // Special storage location for mods
9832 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9833 if (key == ImGuiKey_None)
9834 key = ConvertSingleModFlagToKey(key: mods);
9835 if (!IsKeyPressed(key, flags: (flags & ImGuiInputFlags_RepeatMask_), owner_id))
9836 return false;
9837 return true;
9838}
9839
9840void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
9841{
9842 ImGuiContext& g = *GImGui;
9843 g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
9844 g.NextItemData.Shortcut = key_chord;
9845 g.NextItemData.ShortcutFlags = flags;
9846}
9847
9848// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
9849void ImGui::ItemHandleShortcut(ImGuiID id)
9850{
9851 ImGuiContext& g = *GImGui;
9852 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
9853 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
9854
9855 if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
9856 return;
9857 if (flags & ImGuiInputFlags_Tooltip)
9858 {
9859 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
9860 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
9861 }
9862 if (!Shortcut(key_chord: g.NextItemData.Shortcut, flags: flags & ImGuiInputFlags_SupportedByShortcut, owner_id: id) || g.NavActivateId != 0)
9863 return;
9864
9865 // FIXME: Generalize Activation queue?
9866 g.NavActivateId = id; // Will effectively disable clipping.
9867 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
9868 //if (g.ActiveId == 0 || g.ActiveId == id)
9869 g.NavActivateDownId = g.NavActivatePressedId = id;
9870 NavHighlightActivated(id);
9871}
9872
9873bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
9874{
9875 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
9876}
9877
9878bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9879{
9880 ImGuiContext& g = *GImGui;
9881 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
9882
9883 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9884 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9885 flags |= ImGuiInputFlags_RouteFocused;
9886
9887 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
9888 // Effectively makes Shortcut() always input-owner aware.
9889 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
9890 owner_id = GetRoutingIdFromOwnerId(owner_id);
9891
9892 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
9893 return false;
9894
9895 // Submit route
9896 if (!SetShortcutRouting(key_chord, flags, owner_id))
9897 return false;
9898
9899 // Default repeat behavior for Shortcut()
9900 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
9901 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
9902 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
9903
9904 if (!IsKeyChordPressed(key_chord, flags, owner_id))
9905 return false;
9906
9907 // Claim mods during the press
9908 SetKeyOwnersForKeyChord(key_chord: key_chord & ImGuiMod_Mask_, owner_id);
9909
9910 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9911 return true;
9912}
9913
9914
9915//-----------------------------------------------------------------------------
9916// [SECTION] ERROR CHECKING
9917//-----------------------------------------------------------------------------
9918
9919// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
9920// Called by IMGUI_CHECKVERSION().
9921// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9922// If this triggers you have mismatched headers and compiled code versions.
9923// - It could be because of a build issue (using new headers with old compiled code)
9924// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
9925// THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
9926// Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
9927// Otherwise it is possible that different compilation units would see different structure layout.
9928// If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
9929bool 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)
9930{
9931 bool error = false;
9932 if (strcmp(s1: version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9933 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9934 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9935 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9936 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9937 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9938 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9939 return !error;
9940}
9941
9942// 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)
9943// This is causing issues and ambiguity and we need to retire that.
9944// See https://github.com/ocornut/imgui/issues/5548 for more details.
9945// [Scenario 1]
9946// Previously this would make the window content size ~200x200:
9947// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK
9948// Instead, please submit an item:
9949// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9950// Alternative:
9951// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9952// [Scenario 2]
9953// For reference this is one of the issue what we aim to fix with this change:
9954// BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9955// 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!
9956// 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.
9957void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9958{
9959 ImGuiContext& g = *GImGui;
9960 ImGuiWindow* window = g.CurrentWindow;
9961 IM_ASSERT(window->DC.IsSetPos);
9962 window->DC.IsSetPos = false;
9963#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9964 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9965 return;
9966 if (window->SkipItems)
9967 return;
9968 IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9969#else
9970 window->DC.CursorMaxPos = ImMax(lhs: window->DC.CursorMaxPos, rhs: window->DC.CursorPos);
9971#endif
9972}
9973
9974static void ImGui::ErrorCheckNewFrameSanityChecks()
9975{
9976 ImGuiContext& g = *GImGui;
9977
9978 // Check user IM_ASSERT macro
9979 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9980 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9981 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9982 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
9983 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
9984 if (true) IM_ASSERT(1); else IM_ASSERT(0);
9985
9986 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9987 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9988#ifdef __EMSCRIPTEN__
9989 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9990 g.IO.DeltaTime = 0.00001f;
9991#endif
9992
9993 // Check user data
9994 // (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)
9995 IM_ASSERT(g.Initialized);
9996 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
9997 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9998 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
9999 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()");
10000 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
10001 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
10002 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
10003 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10004 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10005 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10006#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10007 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10008 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)");
10009
10010 // 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)
10011 if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10012 IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10013#endif
10014}
10015
10016static void ImGui::ErrorCheckEndFrameSanityChecks()
10017{
10018 ImGuiContext& g = *GImGui;
10019
10020 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10021 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10022 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10023 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10024 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10025 // while still correctly asserting on mid-frame key press events.
10026 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10027 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10028 IM_UNUSED(key_mods);
10029
10030 // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10031 //ErrorCheckEndFrameRecover();
10032
10033 // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10034 // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10035 if (g.CurrentWindowStack.Size != 1)
10036 {
10037 if (g.CurrentWindowStack.Size > 1)
10038 {
10039 ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10040 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10041 IM_UNUSED(window);
10042 while (g.CurrentWindowStack.Size > 1)
10043 End();
10044 }
10045 else
10046 {
10047 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10048 }
10049 }
10050
10051 IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10052}
10053
10054// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10055// Must be called during or before EndFrame().
10056// This is generally flawed as we are not necessarily End/Popping things in the right order.
10057// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10058// FIXME: Can't recover from interleaved BeginTabBar/Begin
10059void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10060{
10061 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10062 ImGuiContext& g = *GImGui;
10063 while (g.CurrentWindowStack.Size > 0) //-V1044
10064 {
10065 ErrorCheckEndWindowRecover(log_callback, user_data);
10066 ImGuiWindow* window = g.CurrentWindow;
10067 if (g.CurrentWindowStack.Size == 1)
10068 {
10069 IM_ASSERT(window->IsFallbackWindow);
10070 break;
10071 }
10072 if (window->Flags & ImGuiWindowFlags_ChildWindow)
10073 {
10074 if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10075 EndChild();
10076 }
10077 else
10078 {
10079 if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10080 End();
10081 }
10082 }
10083}
10084
10085// Must be called before End()/EndChild()
10086void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10087{
10088 ImGuiContext& g = *GImGui;
10089 while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10090 {
10091 if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10092 EndTable();
10093 }
10094
10095 ImGuiWindow* window = g.CurrentWindow;
10096 ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10097 IM_ASSERT(window != NULL);
10098 while (g.CurrentTabBar != NULL) //-V1044
10099 {
10100 if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10101 EndTabBar();
10102 }
10103 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
10104 {
10105 if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'", window->Name);
10106 EndMultiSelect();
10107 }
10108 while (window->DC.TreeDepth > 0)
10109 {
10110 if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10111 TreePop();
10112 }
10113 while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10114 {
10115 if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10116 EndGroup();
10117 }
10118 while (window->IDStack.Size > 1)
10119 {
10120 if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10121 PopID();
10122 }
10123 while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10124 {
10125 if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10126 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10127 EndDisabled();
10128 else
10129 {
10130 EndDisabledOverrideReenable();
10131 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10132 }
10133 }
10134 while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10135 {
10136 if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(idx: g.ColorStack.back().Col));
10137 PopStyleColor();
10138 }
10139 while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10140 {
10141 if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10142 PopItemFlag();
10143 }
10144 while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10145 {
10146 if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10147 PopStyleVar();
10148 }
10149 while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10150 {
10151 if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10152 PopFont();
10153 }
10154 while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10155 {
10156 if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10157 PopFocusScope();
10158 }
10159}
10160
10161// Save current stack sizes for later compare
10162void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10163{
10164 ImGuiContext& g = *ctx;
10165 ImGuiWindow* window = g.CurrentWindow;
10166 SizeOfIDStack = (short)window->IDStack.Size;
10167 SizeOfColorStack = (short)g.ColorStack.Size;
10168 SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10169 SizeOfFontStack = (short)g.FontStack.Size;
10170 SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10171 SizeOfGroupStack = (short)g.GroupStack.Size;
10172 SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10173 SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10174 SizeOfDisabledStack = (short)g.DisabledStackSize;
10175}
10176
10177// Compare to detect usage errors
10178void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10179{
10180 ImGuiContext& g = *ctx;
10181 ImGuiWindow* window = g.CurrentWindow;
10182 IM_UNUSED(window);
10183
10184 // Window stacks
10185 // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10186 IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
10187
10188 // Global stacks
10189 // 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.
10190 IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
10191 IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10192 IM_ASSERT(SizeOfDisabledStack == g.DisabledStackSize && "BeginDisabled/EndDisabled Mismatch!");
10193 IM_ASSERT(SizeOfItemFlagsStack >= g.ItemFlagsStack.Size && "PushItemFlag/PopItemFlag Mismatch!");
10194 IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
10195 IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
10196 IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
10197 IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
10198}
10199
10200//-----------------------------------------------------------------------------
10201// [SECTION] ITEM SUBMISSION
10202//-----------------------------------------------------------------------------
10203// - KeepAliveID()
10204// - ItemAdd()
10205//-----------------------------------------------------------------------------
10206
10207// 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().
10208void ImGui::KeepAliveID(ImGuiID id)
10209{
10210 ImGuiContext& g = *GImGui;
10211 if (g.ActiveId == id)
10212 g.ActiveIdIsAlive = id;
10213 if (g.ActiveIdPreviousFrame == id)
10214 g.ActiveIdPreviousFrameIsAlive = true;
10215}
10216
10217// Declare item bounding box for clipping and interaction.
10218// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10219// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10220// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10221IM_MSVC_RUNTIME_CHECKS_OFF
10222bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10223{
10224 ImGuiContext& g = *GImGui;
10225 ImGuiWindow* window = g.CurrentWindow;
10226
10227 // Set item data
10228 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10229 g.LastItemData.ID = id;
10230 g.LastItemData.Rect = bb;
10231 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10232 g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10233 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10234 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10235
10236 if (id != 0)
10237 {
10238 KeepAliveID(id);
10239
10240 // Directional navigation processing
10241 // Runs prior to clipping early-out
10242 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10243 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10244 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10245 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10246 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10247 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10248 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10249 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10250 if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10251 {
10252 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10253 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10254 if (g.NavId == id || g.NavAnyRequest)
10255 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10256 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10257 NavProcessItem();
10258 }
10259
10260 if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10261 ItemHandleShortcut(id);
10262 }
10263
10264 // Lightweight clear of SetNextItemXXX data.
10265 g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10266 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10267
10268#ifdef IMGUI_ENABLE_TEST_ENGINE
10269 if (id != 0)
10270 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10271#endif
10272
10273 // Clipping test
10274 // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10275 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10276 const bool is_rect_visible = bb.Overlaps(r: window->ClipRect);
10277 if (!is_rect_visible)
10278 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10279 if (!g.ItemUnclipByLog)
10280 return false;
10281
10282 // [DEBUG]
10283#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10284 if (id != 0)
10285 {
10286 if (id == g.DebugLocateId)
10287 DebugLocateItemResolveWithLastItem();
10288
10289 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10290 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10291 // READ THE FAQ: https://dearimgui.com/faq
10292 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!");
10293 }
10294 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10295 //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10296 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10297#endif
10298
10299 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10300 if (is_rect_visible)
10301 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10302 if (IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
10303 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10304 return true;
10305}
10306IM_MSVC_RUNTIME_CHECKS_RESTORE
10307
10308//-----------------------------------------------------------------------------
10309// [SECTION] LAYOUT
10310//-----------------------------------------------------------------------------
10311// - ItemSize()
10312// - SameLine()
10313// - GetCursorScreenPos()
10314// - SetCursorScreenPos()
10315// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10316// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10317// - GetCursorStartPos()
10318// - Indent()
10319// - Unindent()
10320// - SetNextItemWidth()
10321// - PushItemWidth()
10322// - PushMultiItemsWidths()
10323// - PopItemWidth()
10324// - CalcItemWidth()
10325// - CalcItemSize()
10326// - GetTextLineHeight()
10327// - GetTextLineHeightWithSpacing()
10328// - GetFrameHeight()
10329// - GetFrameHeightWithSpacing()
10330// - GetContentRegionMax()
10331// - GetContentRegionAvail(),
10332// - BeginGroup()
10333// - EndGroup()
10334// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10335//-----------------------------------------------------------------------------
10336
10337// Advance cursor given item size for layout.
10338// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10339// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10340// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10341IM_MSVC_RUNTIME_CHECKS_OFF
10342void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10343{
10344 ImGuiContext& g = *GImGui;
10345 ImGuiWindow* window = g.CurrentWindow;
10346 if (window->SkipItems)
10347 return;
10348
10349 // We increase the height in this function to accommodate for baseline offset.
10350 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10351 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10352 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(lhs: 0.0f, rhs: window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10353
10354 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10355 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);
10356
10357 // Always align ourselves on pixel boundaries
10358 //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]
10359 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10360 window->DC.CursorPosPrevLine.y = line_y1;
10361 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
10362 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
10363 window->DC.CursorMaxPos.x = ImMax(lhs: window->DC.CursorMaxPos.x, rhs: window->DC.CursorPosPrevLine.x);
10364 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10365 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10366
10367 window->DC.PrevLineSize.y = line_height;
10368 window->DC.CurrLineSize.y = 0.0f;
10369 window->DC.PrevLineTextBaseOffset = ImMax(lhs: window->DC.CurrLineTextBaseOffset, rhs: text_baseline_y);
10370 window->DC.CurrLineTextBaseOffset = 0.0f;
10371 window->DC.IsSameLine = window->DC.IsSetPos = false;
10372
10373 // Horizontal layout mode
10374 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10375 SameLine();
10376}
10377IM_MSVC_RUNTIME_CHECKS_RESTORE
10378
10379// Gets back to previous line and continue with horizontal layout
10380// offset_from_start_x == 0 : follow right after previous item
10381// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10382// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10383// spacing_w >= 0 : enforce spacing amount
10384void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10385{
10386 ImGuiContext& g = *GImGui;
10387 ImGuiWindow* window = g.CurrentWindow;
10388 if (window->SkipItems)
10389 return;
10390
10391 if (offset_from_start_x != 0.0f)
10392 {
10393 if (spacing_w < 0.0f)
10394 spacing_w = 0.0f;
10395 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10396 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10397 }
10398 else
10399 {
10400 if (spacing_w < 0.0f)
10401 spacing_w = g.Style.ItemSpacing.x;
10402 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10403 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10404 }
10405 window->DC.CurrLineSize = window->DC.PrevLineSize;
10406 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10407 window->DC.IsSameLine = true;
10408}
10409
10410ImVec2 ImGui::GetCursorScreenPos()
10411{
10412 ImGuiWindow* window = GetCurrentWindowRead();
10413 return window->DC.CursorPos;
10414}
10415
10416void ImGui::SetCursorScreenPos(const ImVec2& pos)
10417{
10418 ImGuiWindow* window = GetCurrentWindow();
10419 window->DC.CursorPos = pos;
10420 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10421 window->DC.IsSetPos = true;
10422}
10423
10424// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10425// 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'.
10426ImVec2 ImGui::GetCursorPos()
10427{
10428 ImGuiWindow* window = GetCurrentWindowRead();
10429 return window->DC.CursorPos - window->Pos + window->Scroll;
10430}
10431
10432float ImGui::GetCursorPosX()
10433{
10434 ImGuiWindow* window = GetCurrentWindowRead();
10435 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10436}
10437
10438float ImGui::GetCursorPosY()
10439{
10440 ImGuiWindow* window = GetCurrentWindowRead();
10441 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10442}
10443
10444void ImGui::SetCursorPos(const ImVec2& local_pos)
10445{
10446 ImGuiWindow* window = GetCurrentWindow();
10447 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10448 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10449 window->DC.IsSetPos = true;
10450}
10451
10452void ImGui::SetCursorPosX(float x)
10453{
10454 ImGuiWindow* window = GetCurrentWindow();
10455 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10456 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10457 window->DC.IsSetPos = true;
10458}
10459
10460void ImGui::SetCursorPosY(float y)
10461{
10462 ImGuiWindow* window = GetCurrentWindow();
10463 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10464 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10465 window->DC.IsSetPos = true;
10466}
10467
10468ImVec2 ImGui::GetCursorStartPos()
10469{
10470 ImGuiWindow* window = GetCurrentWindowRead();
10471 return window->DC.CursorStartPos - window->Pos;
10472}
10473
10474void ImGui::Indent(float indent_w)
10475{
10476 ImGuiContext& g = *GImGui;
10477 ImGuiWindow* window = GetCurrentWindow();
10478 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10479 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10480}
10481
10482void ImGui::Unindent(float indent_w)
10483{
10484 ImGuiContext& g = *GImGui;
10485 ImGuiWindow* window = GetCurrentWindow();
10486 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10487 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10488}
10489
10490// Affect large frame+labels widgets only.
10491void ImGui::SetNextItemWidth(float item_width)
10492{
10493 ImGuiContext& g = *GImGui;
10494 g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10495 g.NextItemData.Width = item_width;
10496}
10497
10498// FIXME: Remove the == 0.0f behavior?
10499void ImGui::PushItemWidth(float item_width)
10500{
10501 ImGuiContext& g = *GImGui;
10502 ImGuiWindow* window = g.CurrentWindow;
10503 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
10504 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10505 g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10506}
10507
10508void ImGui::PushMultiItemsWidths(int components, float w_full)
10509{
10510 ImGuiContext& g = *GImGui;
10511 ImGuiWindow* window = g.CurrentWindow;
10512 IM_ASSERT(components > 0);
10513 const ImGuiStyle& style = g.Style;
10514 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
10515 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
10516 float prev_split = w_items;
10517 for (int i = components - 1; i > 0; i--)
10518 {
10519 float next_split = IM_TRUNC(w_items * i / components);
10520 window->DC.ItemWidthStack.push_back(v: ImMax(lhs: prev_split - next_split, rhs: 1.0f));
10521 prev_split = next_split;
10522 }
10523 window->DC.ItemWidth = ImMax(lhs: prev_split, rhs: 1.0f);
10524 g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10525}
10526
10527void ImGui::PopItemWidth()
10528{
10529 ImGuiWindow* window = GetCurrentWindow();
10530 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10531 window->DC.ItemWidthStack.pop_back();
10532}
10533
10534// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10535// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10536float ImGui::CalcItemWidth()
10537{
10538 ImGuiContext& g = *GImGui;
10539 ImGuiWindow* window = g.CurrentWindow;
10540 float w;
10541 if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10542 w = g.NextItemData.Width;
10543 else
10544 w = window->DC.ItemWidth;
10545 if (w < 0.0f)
10546 {
10547 float region_avail_x = GetContentRegionAvail().x;
10548 w = ImMax(lhs: 1.0f, rhs: region_avail_x + w);
10549 }
10550 w = IM_TRUNC(w);
10551 return w;
10552}
10553
10554// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10555// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10556// Note that only CalcItemWidth() is publicly exposed.
10557// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10558ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10559{
10560 ImVec2 avail;
10561 if (size.x < 0.0f || size.y < 0.0f)
10562 avail = GetContentRegionAvail();
10563
10564 if (size.x == 0.0f)
10565 size.x = default_w;
10566 else if (size.x < 0.0f)
10567 size.x = ImMax(lhs: 4.0f, rhs: avail.x + size.x); // <-- size.x is negative here so we are subtracting
10568
10569 if (size.y == 0.0f)
10570 size.y = default_h;
10571 else if (size.y < 0.0f)
10572 size.y = ImMax(lhs: 4.0f, rhs: avail.y + size.y); // <-- size.y is negative here so we are subtracting
10573
10574 return size;
10575}
10576
10577float ImGui::GetTextLineHeight()
10578{
10579 ImGuiContext& g = *GImGui;
10580 return g.FontSize;
10581}
10582
10583float ImGui::GetTextLineHeightWithSpacing()
10584{
10585 ImGuiContext& g = *GImGui;
10586 return g.FontSize + g.Style.ItemSpacing.y;
10587}
10588
10589float ImGui::GetFrameHeight()
10590{
10591 ImGuiContext& g = *GImGui;
10592 return g.FontSize + g.Style.FramePadding.y * 2.0f;
10593}
10594
10595float ImGui::GetFrameHeightWithSpacing()
10596{
10597 ImGuiContext& g = *GImGui;
10598 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10599}
10600
10601ImVec2 ImGui::GetContentRegionAvail()
10602{
10603 ImGuiContext& g = *GImGui;
10604 ImGuiWindow* window = g.CurrentWindow;
10605 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10606 return mx - window->DC.CursorPos;
10607}
10608
10609#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10610
10611// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
10612// They are bizarre local-coordinates which don't play well with scrolling.
10613ImVec2 ImGui::GetContentRegionMax()
10614{
10615 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
10616}
10617
10618ImVec2 ImGui::GetWindowContentRegionMin()
10619{
10620 ImGuiWindow* window = GImGui->CurrentWindow;
10621 return window->ContentRegionRect.Min - window->Pos;
10622}
10623
10624ImVec2 ImGui::GetWindowContentRegionMax()
10625{
10626 ImGuiWindow* window = GImGui->CurrentWindow;
10627 return window->ContentRegionRect.Max - window->Pos;
10628}
10629#endif
10630
10631// 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.)
10632// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10633// FIXME-OPT: Could we safely early out on ->SkipItems?
10634void ImGui::BeginGroup()
10635{
10636 ImGuiContext& g = *GImGui;
10637 ImGuiWindow* window = g.CurrentWindow;
10638
10639 g.GroupStack.resize(new_size: g.GroupStack.Size + 1);
10640 ImGuiGroupData& group_data = g.GroupStack.back();
10641 group_data.WindowID = window->ID;
10642 group_data.BackupCursorPos = window->DC.CursorPos;
10643 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10644 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10645 group_data.BackupIndent = window->DC.Indent;
10646 group_data.BackupGroupOffset = window->DC.GroupOffset;
10647 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10648 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10649 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10650 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10651 group_data.BackupIsSameLine = window->DC.IsSameLine;
10652 group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10653 group_data.EmitItem = true;
10654
10655 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10656 window->DC.Indent = window->DC.GroupOffset;
10657 window->DC.CursorMaxPos = window->DC.CursorPos;
10658 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10659 if (g.LogEnabled)
10660 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10661}
10662
10663void ImGui::EndGroup()
10664{
10665 ImGuiContext& g = *GImGui;
10666 ImGuiWindow* window = g.CurrentWindow;
10667 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10668
10669 ImGuiGroupData& group_data = g.GroupStack.back();
10670 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10671
10672 if (window->DC.IsSetPos)
10673 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10674
10675 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
10676 ImRect group_bb(group_data.BackupCursorPos, ImMax(lhs: ImMax(lhs: window->DC.CursorMaxPos, rhs: g.LastItemData.Rect.Max), rhs: group_data.BackupCursorPos));
10677 window->DC.CursorPos = group_data.BackupCursorPos;
10678 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
10679 window->DC.CursorMaxPos = ImMax(lhs: group_data.BackupCursorMaxPos, rhs: group_bb.Max);
10680 window->DC.Indent = group_data.BackupIndent;
10681 window->DC.GroupOffset = group_data.BackupGroupOffset;
10682 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10683 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10684 window->DC.IsSameLine = group_data.BackupIsSameLine;
10685 if (g.LogEnabled)
10686 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10687
10688 if (!group_data.EmitItem)
10689 {
10690 g.GroupStack.pop_back();
10691 return;
10692 }
10693
10694 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.
10695 ItemSize(size: group_bb.GetSize());
10696 ItemAdd(bb: group_bb, id: 0, NULL, extra_flags: ImGuiItemFlags_NoTabStop);
10697
10698 // 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.
10699 // 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.
10700 // Also if you grep for LastItemId you'll notice it is only used in that context.
10701 // (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.)
10702 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10703 const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10704 if (group_contains_curr_active_id)
10705 g.LastItemData.ID = g.ActiveId;
10706 else if (group_contains_prev_active_id)
10707 g.LastItemData.ID = g.ActiveIdPreviousFrame;
10708 g.LastItemData.Rect = group_bb;
10709
10710 // Forward Hovered flag
10711 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10712 if (group_contains_curr_hovered_id)
10713 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10714
10715 // Forward Edited flag
10716 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10717 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10718
10719 // Forward Deactivated flag
10720 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10721 if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10722 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10723
10724 g.GroupStack.pop_back();
10725 if (g.DebugShowGroupRects)
10726 window->DrawList->AddRect(p_min: group_bb.Min, p_max: group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
10727}
10728
10729
10730//-----------------------------------------------------------------------------
10731// [SECTION] SCROLLING
10732//-----------------------------------------------------------------------------
10733
10734// Helper to snap on edges when aiming at an item very close to the edge,
10735// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10736// When we refactor the scrolling API this may be configurable with a flag?
10737// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10738static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10739{
10740 if (target <= snap_min + snap_threshold)
10741 return ImLerp(a: snap_min, b: target, t: center_ratio);
10742 if (target >= snap_max - snap_threshold)
10743 return ImLerp(a: target, b: snap_max, t: center_ratio);
10744 return target;
10745}
10746
10747static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10748{
10749 ImVec2 scroll = window->Scroll;
10750 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10751 for (int axis = 0; axis < 2; axis++)
10752 {
10753 if (window->ScrollTarget[axis] < FLT_MAX)
10754 {
10755 float center_ratio = window->ScrollTargetCenterRatio[axis];
10756 float scroll_target = window->ScrollTarget[axis];
10757 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10758 {
10759 float snap_min = 0.0f;
10760 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10761 scroll_target = CalcScrollEdgeSnap(target: scroll_target, snap_min, snap_max, snap_threshold: window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10762 }
10763 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10764 }
10765 scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
10766 if (!window->Collapsed && !window->SkipItems)
10767 scroll[axis] = ImMin(lhs: scroll[axis], rhs: window->ScrollMax[axis]);
10768 }
10769 return scroll;
10770}
10771
10772void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10773{
10774 ImGuiContext& g = *GImGui;
10775 ImGuiWindow* window = g.CurrentWindow;
10776 ScrollToRectEx(window, rect: g.LastItemData.NavRect, flags);
10777}
10778
10779void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10780{
10781 ScrollToRectEx(window, rect: item_rect, flags);
10782}
10783
10784// Scroll to keep newly navigated item fully into view
10785ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10786{
10787 ImGuiContext& g = *GImGui;
10788 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10789 scroll_rect.Min.x = ImMin(lhs: scroll_rect.Min.x + window->DecoInnerSizeX1, rhs: scroll_rect.Max.x);
10790 scroll_rect.Min.y = ImMin(lhs: scroll_rect.Min.y + window->DecoInnerSizeY1, rhs: scroll_rect.Max.y);
10791 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10792 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10793
10794 // Check that only one behavior is selected per axis
10795 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10796 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10797
10798 // Defaults
10799 ImGuiScrollFlags in_flags = flags;
10800 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10801 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10802 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10803 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10804
10805 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10806 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10807 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;
10808 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;
10809
10810 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10811 {
10812 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10813 SetScrollFromPosX(window, local_x: item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 0.0f);
10814 else if (item_rect.Max.x >= scroll_rect.Max.x)
10815 SetScrollFromPosX(window, local_x: item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 1.0f);
10816 }
10817 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10818 {
10819 if (can_be_fully_visible_x)
10820 SetScrollFromPosX(window, local_x: ImTrunc(f: (item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, center_x_ratio: 0.5f);
10821 else
10822 SetScrollFromPosX(window, local_x: item_rect.Min.x - window->Pos.x, center_x_ratio: 0.0f);
10823 }
10824
10825 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10826 {
10827 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10828 SetScrollFromPosY(window, local_y: item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 0.0f);
10829 else if (item_rect.Max.y >= scroll_rect.Max.y)
10830 SetScrollFromPosY(window, local_y: item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 1.0f);
10831 }
10832 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10833 {
10834 if (can_be_fully_visible_y)
10835 SetScrollFromPosY(window, local_y: ImTrunc(f: (item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, center_y_ratio: 0.5f);
10836 else
10837 SetScrollFromPosY(window, local_y: item_rect.Min.y - window->Pos.y, center_y_ratio: 0.0f);
10838 }
10839
10840 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10841 ImVec2 delta_scroll = next_scroll - window->Scroll;
10842
10843 // Also scroll parent window to keep us into view if necessary
10844 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10845 {
10846 // FIXME-SCROLL: May be an option?
10847 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10848 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10849 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10850 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10851 delta_scroll += ScrollToRectEx(window: window->ParentWindow, item_rect: ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), flags: in_flags);
10852 }
10853
10854 return delta_scroll;
10855}
10856
10857float ImGui::GetScrollX()
10858{
10859 ImGuiWindow* window = GImGui->CurrentWindow;
10860 return window->Scroll.x;
10861}
10862
10863float ImGui::GetScrollY()
10864{
10865 ImGuiWindow* window = GImGui->CurrentWindow;
10866 return window->Scroll.y;
10867}
10868
10869float ImGui::GetScrollMaxX()
10870{
10871 ImGuiWindow* window = GImGui->CurrentWindow;
10872 return window->ScrollMax.x;
10873}
10874
10875float ImGui::GetScrollMaxY()
10876{
10877 ImGuiWindow* window = GImGui->CurrentWindow;
10878 return window->ScrollMax.y;
10879}
10880
10881void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10882{
10883 window->ScrollTarget.x = scroll_x;
10884 window->ScrollTargetCenterRatio.x = 0.0f;
10885 window->ScrollTargetEdgeSnapDist.x = 0.0f;
10886}
10887
10888void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10889{
10890 window->ScrollTarget.y = scroll_y;
10891 window->ScrollTargetCenterRatio.y = 0.0f;
10892 window->ScrollTargetEdgeSnapDist.y = 0.0f;
10893}
10894
10895void ImGui::SetScrollX(float scroll_x)
10896{
10897 ImGuiContext& g = *GImGui;
10898 SetScrollX(window: g.CurrentWindow, scroll_x);
10899}
10900
10901void ImGui::SetScrollY(float scroll_y)
10902{
10903 ImGuiContext& g = *GImGui;
10904 SetScrollY(window: g.CurrentWindow, scroll_y);
10905}
10906
10907// Note that a local position will vary depending on initial scroll value,
10908// This is a little bit confusing so bear with us:
10909// - local_pos = (absolution_pos - window->Pos)
10910// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10911// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10912// - They mostly exist because of legacy API.
10913// Following the rules above, when trying to work with scrolling code, consider that:
10914// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10915// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10916// 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
10917void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10918{
10919 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10920 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10921 window->ScrollTargetCenterRatio.x = center_x_ratio;
10922 window->ScrollTargetEdgeSnapDist.x = 0.0f;
10923}
10924
10925void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10926{
10927 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10928 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10929 window->ScrollTargetCenterRatio.y = center_y_ratio;
10930 window->ScrollTargetEdgeSnapDist.y = 0.0f;
10931}
10932
10933void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10934{
10935 ImGuiContext& g = *GImGui;
10936 SetScrollFromPosX(window: g.CurrentWindow, local_x, center_x_ratio);
10937}
10938
10939void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10940{
10941 ImGuiContext& g = *GImGui;
10942 SetScrollFromPosY(window: g.CurrentWindow, local_y, center_y_ratio);
10943}
10944
10945// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10946void ImGui::SetScrollHereX(float center_x_ratio)
10947{
10948 ImGuiContext& g = *GImGui;
10949 ImGuiWindow* window = g.CurrentWindow;
10950 float spacing_x = ImMax(lhs: window->WindowPadding.x, rhs: g.Style.ItemSpacing.x);
10951 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);
10952 SetScrollFromPosX(window, local_x: target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10953
10954 // Tweak: snap on edges when aiming at an item very close to the edge
10955 window->ScrollTargetEdgeSnapDist.x = ImMax(lhs: 0.0f, rhs: window->WindowPadding.x - spacing_x);
10956}
10957
10958// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10959void ImGui::SetScrollHereY(float center_y_ratio)
10960{
10961 ImGuiContext& g = *GImGui;
10962 ImGuiWindow* window = g.CurrentWindow;
10963 float spacing_y = ImMax(lhs: window->WindowPadding.y, rhs: g.Style.ItemSpacing.y);
10964 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);
10965 SetScrollFromPosY(window, local_y: target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10966
10967 // Tweak: snap on edges when aiming at an item very close to the edge
10968 window->ScrollTargetEdgeSnapDist.y = ImMax(lhs: 0.0f, rhs: window->WindowPadding.y - spacing_y);
10969}
10970
10971//-----------------------------------------------------------------------------
10972// [SECTION] TOOLTIPS
10973//-----------------------------------------------------------------------------
10974
10975bool ImGui::BeginTooltip()
10976{
10977 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
10978}
10979
10980bool ImGui::BeginItemTooltip()
10981{
10982 if (!IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
10983 return false;
10984 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
10985}
10986
10987bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10988{
10989 ImGuiContext& g = *GImGui;
10990
10991 if (g.DragDropWithinSource || g.DragDropWithinTarget)
10992 {
10993 // Drag and Drop tooltips are positioning differently than other tooltips:
10994 // - offset visibility to increase visibility around mouse.
10995 // - never clamp within outer viewport boundary.
10996 // We call SetNextWindowPos() to enforce position and disable clamping.
10997 // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
10998 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10999 ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11000 SetNextWindowPos(pos: tooltip_pos);
11001 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11002 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11003 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11004 }
11005
11006 char window_name[16];
11007 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: "##Tooltip_%02d", g.TooltipOverrideCount);
11008 if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11009 if (ImGuiWindow* window = FindWindowByName(name: window_name))
11010 if (window->Active)
11011 {
11012 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11013 SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11014 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: "##Tooltip_%02d", ++g.TooltipOverrideCount);
11015 }
11016 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
11017 Begin(name: window_name, NULL, flags: flags | extra_window_flags);
11018 // 2023-03-09: Added bool return value to the API, but currently always returning true.
11019 // If this ever returns false we need to update BeginDragDropSource() accordingly.
11020 //if (!ret)
11021 // End();
11022 //return ret;
11023 return true;
11024}
11025
11026void ImGui::EndTooltip()
11027{
11028 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
11029 End();
11030}
11031
11032void ImGui::SetTooltip(const char* fmt, ...)
11033{
11034 va_list args;
11035 va_start(args, fmt);
11036 SetTooltipV(fmt, args);
11037 va_end(args);
11038}
11039
11040void ImGui::SetTooltipV(const char* fmt, va_list args)
11041{
11042 if (!BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_OverridePrevious, extra_window_flags: ImGuiWindowFlags_None))
11043 return;
11044 TextV(fmt, args);
11045 EndTooltip();
11046}
11047
11048// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11049// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11050void ImGui::SetItemTooltip(const char* fmt, ...)
11051{
11052 va_list args;
11053 va_start(args, fmt);
11054 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
11055 SetTooltipV(fmt, args);
11056 va_end(args);
11057}
11058
11059void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11060{
11061 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
11062 SetTooltipV(fmt, args);
11063}
11064
11065
11066//-----------------------------------------------------------------------------
11067// [SECTION] POPUPS
11068//-----------------------------------------------------------------------------
11069
11070// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11071bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11072{
11073 ImGuiContext& g = *GImGui;
11074 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11075 {
11076 // Return true if any popup is open at the current BeginPopup() level of the popup stack
11077 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11078 IM_ASSERT(id == 0);
11079 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11080 return g.OpenPopupStack.Size > 0;
11081 else
11082 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11083 }
11084 else
11085 {
11086 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11087 {
11088 // Return true if the popup is open anywhere in the popup stack
11089 for (int n = 0; n < g.OpenPopupStack.Size; n++)
11090 if (g.OpenPopupStack[n].PopupId == id)
11091 return true;
11092 return false;
11093 }
11094 else
11095 {
11096 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11097 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11098 }
11099 }
11100}
11101
11102bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11103{
11104 ImGuiContext& g = *GImGui;
11105 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str: str_id);
11106 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11107 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11108 return IsPopupOpen(id, popup_flags);
11109}
11110
11111// Also see FindBlockingModal(NULL)
11112ImGuiWindow* ImGui::GetTopMostPopupModal()
11113{
11114 ImGuiContext& g = *GImGui;
11115 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11116 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11117 if (popup->Flags & ImGuiWindowFlags_Modal)
11118 return popup;
11119 return NULL;
11120}
11121
11122// See Demo->Stacked Modal to confirm what this is for.
11123ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11124{
11125 ImGuiContext& g = *GImGui;
11126 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11127 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11128 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(window: popup))
11129 return popup;
11130 return NULL;
11131}
11132
11133void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11134{
11135 ImGuiContext& g = *GImGui;
11136 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
11137 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11138 OpenPopupEx(id, popup_flags);
11139}
11140
11141void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11142{
11143 OpenPopupEx(id, popup_flags);
11144}
11145
11146// Mark popup as open (toggle toward open state).
11147// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11148// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11149// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11150void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11151{
11152 ImGuiContext& g = *GImGui;
11153 ImGuiWindow* parent_window = g.CurrentWindow;
11154 const int current_stack_size = g.BeginPopupStack.Size;
11155
11156 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11157 if (IsPopupOpen(id: (ImGuiID)0, popup_flags: ImGuiPopupFlags_AnyPopupId))
11158 return;
11159
11160 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11161 popup_ref.PopupId = id;
11162 popup_ref.Window = NULL;
11163 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
11164 popup_ref.OpenFrameCount = g.FrameCount;
11165 popup_ref.OpenParentId = parent_window->IDStack.back();
11166 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11167 popup_ref.OpenMousePos = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11168
11169 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11170 if (g.OpenPopupStack.Size < current_stack_size + 1)
11171 {
11172 g.OpenPopupStack.push_back(v: popup_ref);
11173 }
11174 else
11175 {
11176 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11177 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11178 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11179 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11180 bool keep_existing = false;
11181 if (g.OpenPopupStack[current_stack_size].PopupId == id)
11182 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11183 keep_existing = true;
11184 if (keep_existing)
11185 {
11186 // No reopen
11187 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11188 }
11189 else
11190 {
11191 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11192 ClosePopupToLevel(remaining: current_stack_size, restore_focus_to_window_under_popup: true);
11193 g.OpenPopupStack.push_back(v: popup_ref);
11194 }
11195
11196 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11197 // This is equivalent to what ClosePopupToLevel() does.
11198 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11199 // FocusWindow(parent_window);
11200 }
11201}
11202
11203// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11204// This function closes any popups that are over 'ref_window'.
11205void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11206{
11207 ImGuiContext& g = *GImGui;
11208 if (g.OpenPopupStack.Size == 0)
11209 return;
11210
11211 // Don't close our own child popup windows.
11212 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11213 int popup_count_to_keep = 0;
11214 if (ref_window)
11215 {
11216 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11217 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11218 {
11219 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11220 if (!popup.Window)
11221 continue;
11222 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11223
11224 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11225 // - Clicking/Focusing Window2 won't close Popup1:
11226 // Window -> Popup1 -> Window2(Ref)
11227 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11228 // Window -> Popup1(Ref) -> Popup2 -> Popup3
11229 // - Each popups may contain child windows, which is why we compare ->RootWindow!
11230 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11231 // We step through every popup from bottom to top to validate their position relative to reference window.
11232 bool ref_window_is_descendent_of_popup = false;
11233 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11234 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11235 if (IsWindowWithinBeginStackOf(window: ref_window, potential_parent: popup_window))
11236 {
11237 ref_window_is_descendent_of_popup = true;
11238 break;
11239 }
11240 if (!ref_window_is_descendent_of_popup)
11241 break;
11242 }
11243 }
11244 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
11245 {
11246 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11247 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup);
11248 }
11249}
11250
11251void ImGui::ClosePopupsExceptModals()
11252{
11253 ImGuiContext& g = *GImGui;
11254
11255 int popup_count_to_keep;
11256 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11257 {
11258 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11259 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11260 break;
11261 }
11262 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
11263 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup: true);
11264}
11265
11266void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11267{
11268 ImGuiContext& g = *GImGui;
11269 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11270 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11271
11272 // Trim open popup stack
11273 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11274 g.OpenPopupStack.resize(new_size: remaining);
11275
11276 // 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)
11277 if (restore_focus_to_window_under_popup && prev_popup.Window)
11278 {
11279 ImGuiWindow* popup_window = prev_popup.Window;
11280 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11281 if (focus_window && !focus_window->WasActive)
11282 FocusTopMostWindowUnderOne(under_this_window: popup_window, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11283 else
11284 FocusWindow(window: focus_window, flags: (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11285 }
11286}
11287
11288// Close the popup we have begin-ed into.
11289void ImGui::CloseCurrentPopup()
11290{
11291 ImGuiContext& g = *GImGui;
11292 int popup_idx = g.BeginPopupStack.Size - 1;
11293 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11294 return;
11295
11296 // Closing a menu closes its top-most parent popup (unless a modal)
11297 while (popup_idx > 0)
11298 {
11299 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11300 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11301 bool close_parent = false;
11302 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11303 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11304 close_parent = true;
11305 if (!close_parent)
11306 break;
11307 popup_idx--;
11308 }
11309 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11310 ClosePopupToLevel(remaining: popup_idx, restore_focus_to_window_under_popup: true);
11311
11312 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11313 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11314 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11315 if (ImGuiWindow* window = g.NavWindow)
11316 window->DC.NavHideHighlightOneFrame = true;
11317}
11318
11319// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
11320bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
11321{
11322 ImGuiContext& g = *GImGui;
11323 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
11324 {
11325 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11326 return false;
11327 }
11328
11329 char name[20];
11330 if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
11331 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11332 else
11333 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11334
11335 bool is_open = Begin(name, NULL, flags: extra_window_flags | ImGuiWindowFlags_Popup);
11336 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11337 EndPopup();
11338
11339 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11340
11341 return is_open;
11342}
11343
11344bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11345{
11346 ImGuiContext& g = *GImGui;
11347 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11348 {
11349 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11350 return false;
11351 }
11352 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11353 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
11354 return BeginPopupEx(id, extra_window_flags: flags);
11355}
11356
11357// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11358// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11359// - *p_open set back to false in BeginPopupModal() when popup is not open.
11360// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11361bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11362{
11363 ImGuiContext& g = *GImGui;
11364 ImGuiWindow* window = g.CurrentWindow;
11365 const ImGuiID id = window->GetID(str: name);
11366 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
11367 {
11368 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11369 if (p_open && *p_open)
11370 *p_open = false;
11371 return false;
11372 }
11373
11374 // Center modal windows by default for increased visibility
11375 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11376 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11377 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11378 {
11379 const ImGuiViewport* viewport = GetMainViewport();
11380 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_FirstUseEver, pivot: ImVec2(0.5f, 0.5f));
11381 }
11382
11383 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
11384 const bool is_open = Begin(name, p_open, flags);
11385 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11386 {
11387 EndPopup();
11388 if (is_open)
11389 ClosePopupToLevel(remaining: g.BeginPopupStack.Size, restore_focus_to_window_under_popup: true);
11390 return false;
11391 }
11392 return is_open;
11393}
11394
11395void ImGui::EndPopup()
11396{
11397 ImGuiContext& g = *GImGui;
11398 ImGuiWindow* window = g.CurrentWindow;
11399 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
11400 IM_ASSERT(g.BeginPopupStack.Size > 0);
11401
11402 // 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)
11403 if (g.NavWindow == window)
11404 NavMoveRequestTryWrapping(window, move_flags: ImGuiNavMoveFlags_LoopY);
11405
11406 // Child-popups don't need to be laid out
11407 IM_ASSERT(g.WithinEndChild == false);
11408 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11409 g.WithinEndChild = true;
11410 End();
11411 g.WithinEndChild = false;
11412}
11413
11414// Helper to open a popup if mouse button is released over the item
11415// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11416void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11417{
11418 ImGuiContext& g = *GImGui;
11419 ImGuiWindow* window = g.CurrentWindow;
11420 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11421 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11422 {
11423 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!
11424 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11425 OpenPopupEx(id, popup_flags);
11426 }
11427}
11428
11429// This is a helper to handle the simplest case of associating one named popup to one given widget.
11430// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11431// - To create a popup with a specific identifier, pass it in str_id.
11432// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11433// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11434// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11435// This is essentially the same as:
11436// id = str_id ? GetID(str_id) : GetItemID();
11437// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11438// return BeginPopup(id);
11439// Which is essentially the same as:
11440// id = str_id ? GetID(str_id) : GetItemID();
11441// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11442// OpenPopup(id);
11443// return BeginPopup(id);
11444// The main difference being that this is tweaked to avoid computing the ID twice.
11445bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11446{
11447 ImGuiContext& g = *GImGui;
11448 ImGuiWindow* window = g.CurrentWindow;
11449 if (window->SkipItems)
11450 return false;
11451 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!
11452 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11453 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11454 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11455 OpenPopupEx(id, popup_flags);
11456 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11457}
11458
11459bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11460{
11461 ImGuiContext& g = *GImGui;
11462 ImGuiWindow* window = g.CurrentWindow;
11463 if (!str_id)
11464 str_id = "window_context";
11465 ImGuiID id = window->GetID(str: str_id);
11466 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11467 if (IsMouseReleased(button: mouse_button) && IsWindowHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11468 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11469 OpenPopupEx(id, popup_flags);
11470 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11471}
11472
11473bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11474{
11475 ImGuiContext& g = *GImGui;
11476 ImGuiWindow* window = g.CurrentWindow;
11477 if (!str_id)
11478 str_id = "void_context";
11479 ImGuiID id = window->GetID(str: str_id);
11480 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11481 if (IsMouseReleased(button: mouse_button) && !IsWindowHovered(flags: ImGuiHoveredFlags_AnyWindow))
11482 if (GetTopMostPopupModal() == NULL)
11483 OpenPopupEx(id, popup_flags);
11484 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11485}
11486
11487// 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.)
11488// 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.
11489// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11490// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11491// this allows us to have tooltips/popups displayed out of the parent viewport.)
11492ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11493{
11494 ImVec2 base_pos_clamped = ImClamp(v: ref_pos, mn: r_outer.Min, mx: r_outer.Max - size);
11495 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11496 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11497
11498 // Combo Box policy (we want a connecting edge)
11499 if (policy == ImGuiPopupPositionPolicy_ComboBox)
11500 {
11501 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11502 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11503 {
11504 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11505 if (n != -1 && dir == *last_dir) // Already tried this direction?
11506 continue;
11507 ImVec2 pos;
11508 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
11509 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11510 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11511 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11512 if (!r_outer.Contains(r: ImRect(pos, pos + size)))
11513 continue;
11514 *last_dir = dir;
11515 return pos;
11516 }
11517 }
11518
11519 // Tooltip and Default popup policy
11520 // (Always first try the direction we used on the last frame, if any)
11521 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11522 {
11523 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11524 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11525 {
11526 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11527 if (n != -1 && dir == *last_dir) // Already tried this direction?
11528 continue;
11529
11530 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);
11531 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);
11532
11533 // 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)
11534 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11535 continue;
11536 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11537 continue;
11538
11539 ImVec2 pos;
11540 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11541 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11542
11543 // Clamp top-left corner of popup
11544 pos.x = ImMax(lhs: pos.x, rhs: r_outer.Min.x);
11545 pos.y = ImMax(lhs: pos.y, rhs: r_outer.Min.y);
11546
11547 *last_dir = dir;
11548 return pos;
11549 }
11550 }
11551
11552 // Fallback when not enough room:
11553 *last_dir = ImGuiDir_None;
11554
11555 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11556 if (policy == ImGuiPopupPositionPolicy_Tooltip)
11557 return ref_pos + ImVec2(2, 2);
11558
11559 // Otherwise try to keep within display
11560 ImVec2 pos = ref_pos;
11561 pos.x = ImMax(lhs: ImMin(lhs: pos.x + size.x, rhs: r_outer.Max.x) - size.x, rhs: r_outer.Min.x);
11562 pos.y = ImMax(lhs: ImMin(lhs: pos.y + size.y, rhs: r_outer.Max.y) - size.y, rhs: r_outer.Min.y);
11563 return pos;
11564}
11565
11566// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11567ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11568{
11569 ImGuiContext& g = *GImGui;
11570 IM_UNUSED(window);
11571 ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
11572 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11573 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));
11574 return r_screen;
11575}
11576
11577ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11578{
11579 ImGuiContext& g = *GImGui;
11580
11581 ImRect r_outer = GetPopupAllowedExtentRect(window);
11582 if (window->Flags & ImGuiWindowFlags_ChildMenu)
11583 {
11584 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11585 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11586 IM_ASSERT(g.CurrentWindow == window);
11587 ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;
11588 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).
11589 ImRect r_avoid;
11590 if (parent_window->DC.MenuBarAppending)
11591 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
11592 else
11593 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);
11594 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Default);
11595 }
11596 if (window->Flags & ImGuiWindowFlags_Popup)
11597 {
11598 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
11599 }
11600 if (window->Flags & ImGuiWindowFlags_Tooltip)
11601 {
11602 // Position tooltip (always follows mouse + clamp within outer boundaries)
11603 // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11604 // 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()
11605 IM_ASSERT(g.CurrentWindow == window);
11606 const float scale = g.Style.MouseCursorScale;
11607 const ImVec2 ref_pos = NavCalcPreferredRefPos();
11608 const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11609 ImRect r_avoid;
11610 if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11611 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11612 else
11613 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.
11614 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11615 return FindBestWindowPosForPopupEx(ref_pos: tooltip_pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Tooltip);
11616 }
11617 IM_ASSERT(0);
11618 return window->Pos;
11619}
11620
11621//-----------------------------------------------------------------------------
11622// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11623//-----------------------------------------------------------------------------
11624
11625// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11626// In our terminology those should be interchangeable, yet right now this is super confusing.
11627// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11628
11629void ImGui::SetNavWindow(ImGuiWindow* window)
11630{
11631 ImGuiContext& g = *GImGui;
11632 if (g.NavWindow != window)
11633 {
11634 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11635 g.NavWindow = window;
11636 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11637 }
11638 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11639 NavUpdateAnyRequestFlag();
11640}
11641
11642void ImGui::NavHighlightActivated(ImGuiID id)
11643{
11644 ImGuiContext& g = *GImGui;
11645 g.NavHighlightActivatedId = id;
11646 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
11647}
11648
11649void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11650{
11651 ImGuiContext& g = *GImGui;
11652 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11653}
11654
11655void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11656{
11657 ImGuiContext& g = *GImGui;
11658 IM_ASSERT(g.NavWindow != NULL);
11659 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11660 g.NavId = id;
11661 g.NavLayer = nav_layer;
11662 SetNavFocusScope(focus_scope_id);
11663 g.NavWindow->NavLastIds[nav_layer] = id;
11664 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11665
11666 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11667 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
11668 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
11669}
11670
11671void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11672{
11673 ImGuiContext& g = *GImGui;
11674 IM_ASSERT(id != 0);
11675
11676 if (g.NavWindow != window)
11677 SetNavWindow(window);
11678
11679 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11680 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11681 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11682 g.NavId = id;
11683 g.NavLayer = nav_layer;
11684 SetNavFocusScope(g.CurrentFocusScopeId);
11685 window->NavLastIds[nav_layer] = id;
11686 if (g.LastItemData.ID == id)
11687 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
11688
11689 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11690 g.NavDisableMouseHover = true;
11691 else
11692 g.NavDisableHighlight = true;
11693
11694 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11695 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
11696 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
11697}
11698
11699static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11700{
11701 if (ImFabs(dx) > ImFabs(dy))
11702 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11703 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11704}
11705
11706static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11707{
11708 if (cand_max < curr_min)
11709 return cand_max - curr_min;
11710 if (curr_max < cand_min)
11711 return cand_min - curr_max;
11712 return 0.0f;
11713}
11714
11715// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11716static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11717{
11718 ImGuiContext& g = *GImGui;
11719 ImGuiWindow* window = g.CurrentWindow;
11720 if (g.NavLayer != window->DC.NavLayerCurrent)
11721 return false;
11722
11723 // FIXME: Those are not good variables names
11724 ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
11725 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)
11726 g.NavScoringDebugCount++;
11727
11728 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11729 if (window->ParentWindow == g.NavWindow)
11730 {
11731 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
11732 if (!window->ClipRect.Overlaps(r: cand))
11733 return false;
11734 cand.ClipWithFull(r: window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11735 }
11736
11737 // Compute distance between boxes
11738 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11739 float dbx = NavScoreItemDistInterval(cand_min: cand.Min.x, cand_max: cand.Max.x, curr_min: curr.Min.x, curr_max: curr.Max.x);
11740 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
11741 if (dby != 0.0f && dbx != 0.0f)
11742 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11743 float dist_box = ImFabs(dbx) + ImFabs(dby);
11744
11745 // 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)
11746 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11747 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11748 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11749
11750 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11751 ImGuiDir quadrant;
11752 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11753 if (dbx != 0.0f || dby != 0.0f)
11754 {
11755 // For non-overlapping boxes, use distance between boxes
11756 // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y
11757 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
11758 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
11759 dax = dbx;
11760 day = dby;
11761 dist_axial = dist_box;
11762 quadrant = ImGetDirQuadrantFromDelta(dx: dbx, dy: dby);
11763 }
11764 else if (dcx != 0.0f || dcy != 0.0f)
11765 {
11766 // For overlapping boxes with different centers, use distance between centers
11767 dax = dcx;
11768 day = dcy;
11769 dist_axial = dist_center;
11770 quadrant = ImGetDirQuadrantFromDelta(dx: dcx, dy: dcy);
11771 }
11772 else
11773 {
11774 // 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)
11775 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11776 }
11777
11778 const ImGuiDir move_dir = g.NavMoveDir;
11779#if IMGUI_DEBUG_NAV_SCORING
11780 char buf[200];
11781 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11782 {
11783 if (quadrant == move_dir)
11784 {
11785 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11786 ImDrawList* draw_list = GetForegroundDrawList(window);
11787 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11788 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11789 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11790 }
11791 }
11792 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11793 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11794 if (debug_hovering || debug_tty)
11795 {
11796 ImFormatString(buf, IM_ARRAYSIZE(buf),
11797 "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",
11798 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11799 if (debug_hovering)
11800 {
11801 ImDrawList* draw_list = GetForegroundDrawList(window);
11802 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11803 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11804 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11805 draw_list->AddText(cand.Max, ~0U, buf);
11806 }
11807 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11808 }
11809#endif
11810
11811 // Is it in the quadrant we're interested in moving to?
11812 bool new_best = false;
11813 if (quadrant == move_dir)
11814 {
11815 // Does it beat the current best candidate?
11816 if (dist_box < result->DistBox)
11817 {
11818 result->DistBox = dist_box;
11819 result->DistCenter = dist_center;
11820 return true;
11821 }
11822 if (dist_box == result->DistBox)
11823 {
11824 // Try using distance between center points to break ties
11825 if (dist_center < result->DistCenter)
11826 {
11827 result->DistCenter = dist_center;
11828 new_best = true;
11829 }
11830 else if (dist_center == result->DistCenter)
11831 {
11832 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11833 // (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),
11834 // 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.
11835 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11836 new_best = true;
11837 }
11838 }
11839 }
11840
11841 // 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
11842 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11843 // 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.
11844 // 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.
11845 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11846 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
11847 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11848 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))
11849 {
11850 result->DistAxial = dist_axial;
11851 new_best = true;
11852 }
11853
11854 return new_best;
11855}
11856
11857static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11858{
11859 ImGuiContext& g = *GImGui;
11860 ImGuiWindow* window = g.CurrentWindow;
11861 result->Window = window;
11862 result->ID = g.LastItemData.ID;
11863 result->FocusScopeId = g.CurrentFocusScopeId;
11864 result->InFlags = g.LastItemData.InFlags;
11865 result->RectRel = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
11866 if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
11867 {
11868 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11869 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11870 }
11871}
11872
11873// True when current work location may be scrolled horizontally when moving left / right.
11874// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11875void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11876{
11877 ImGuiContext& g = *GImGui;
11878 ImGuiWindow* window = g.CurrentWindow;
11879 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11880}
11881
11882// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11883// This is called after LastItemData is set, but NextItemData is also still valid.
11884static void ImGui::NavProcessItem()
11885{
11886 ImGuiContext& g = *GImGui;
11887 ImGuiWindow* window = g.CurrentWindow;
11888 const ImGuiID id = g.LastItemData.ID;
11889 const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11890
11891 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11892 if (window->DC.NavIsScrollPushableX == false)
11893 {
11894 g.LastItemData.NavRect.Min.x = ImClamp(v: g.LastItemData.NavRect.Min.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
11895 g.LastItemData.NavRect.Max.x = ImClamp(v: g.LastItemData.NavRect.Max.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
11896 }
11897 const ImRect nav_bb = g.LastItemData.NavRect;
11898
11899 // Process Init Request
11900 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11901 {
11902 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11903 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11904 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11905 {
11906 NavApplyItemToResult(result: &g.NavInitResult);
11907 }
11908 if (candidate_for_nav_default_focus)
11909 {
11910 g.NavInitRequest = false; // Found a match, clear request
11911 NavUpdateAnyRequestFlag();
11912 }
11913 }
11914
11915 // Process Move Request (scoring for navigation)
11916 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11917 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11918 {
11919 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
11920 {
11921 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
11922 if (is_tabbing)
11923 {
11924 NavProcessItemForTabbingRequest(id, item_flags, move_flags: g.NavMoveFlags);
11925 }
11926 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11927 {
11928 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11929 if (NavScoreItem(result))
11930 NavApplyItemToResult(result);
11931
11932 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11933 const float VISIBLE_RATIO = 0.70f;
11934 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(r: nav_bb))
11935 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)
11936 if (NavScoreItem(result: &g.NavMoveResultLocalVisible))
11937 NavApplyItemToResult(result: &g.NavMoveResultLocalVisible);
11938 }
11939 }
11940 }
11941
11942 // Update information for currently focused/navigated item
11943 if (g.NavId == id)
11944 {
11945 if (g.NavWindow != window)
11946 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11947 g.NavLayer = window->DC.NavLayerCurrent;
11948 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
11949 g.NavFocusScopeId = g.CurrentFocusScopeId;
11950 g.NavIdIsAlive = true;
11951 if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
11952 {
11953 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11954 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11955 }
11956 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, r: nav_bb); // Store item bounding box (relative to window position)
11957 }
11958}
11959
11960// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11961// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11962// - Case 1: no nav/active id: set result to first eligible item, stop storing.
11963// - Case 2: tab forward: on ref id set counter, on counter elapse store result
11964// - 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
11965// - Case 4: tab backward: store all results, on ref id pick prev, stop storing
11966// - 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
11967void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11968{
11969 ImGuiContext& g = *GImGui;
11970
11971 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11972 {
11973 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11974 return;
11975 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
11976 return;
11977 }
11978
11979 // - Can always land on an item when using API call.
11980 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11981 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11982 bool can_stop;
11983 if (move_flags & ImGuiNavMoveFlags_FocusApi)
11984 can_stop = true;
11985 else
11986 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11987
11988 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11989 ImGuiNavItemData* result = &g.NavMoveResultLocal;
11990 if (g.NavTabbingDir == +1)
11991 {
11992 // Tab Forward or SetKeyboardFocusHere() with >= 0
11993 if (can_stop && g.NavTabbingResultFirst.ID == 0)
11994 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
11995 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11996 NavMoveRequestResolveWithLastItem(result);
11997 else if (g.NavId == id)
11998 g.NavTabbingCounter = 1;
11999 }
12000 else if (g.NavTabbingDir == -1)
12001 {
12002 // Tab Backward
12003 if (g.NavId == id)
12004 {
12005 if (result->ID)
12006 {
12007 g.NavMoveScoringItems = false;
12008 NavUpdateAnyRequestFlag();
12009 }
12010 }
12011 else if (can_stop)
12012 {
12013 // Keep applying until reaching NavId
12014 NavApplyItemToResult(result);
12015 }
12016 }
12017 else if (g.NavTabbingDir == 0)
12018 {
12019 if (can_stop && g.NavId == id)
12020 NavMoveRequestResolveWithLastItem(result);
12021 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12022 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
12023 }
12024}
12025
12026bool ImGui::NavMoveRequestButNoResultYet()
12027{
12028 ImGuiContext& g = *GImGui;
12029 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12030}
12031
12032// FIXME: ScoringRect is not set
12033void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12034{
12035 ImGuiContext& g = *GImGui;
12036 IM_ASSERT(g.NavWindow != NULL);
12037 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
12038
12039 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12040 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12041
12042 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12043 g.NavMoveDir = move_dir;
12044 g.NavMoveDirForDebug = move_dir;
12045 g.NavMoveClipDir = clip_dir;
12046 g.NavMoveFlags = move_flags;
12047 g.NavMoveScrollFlags = scroll_flags;
12048 g.NavMoveForwardToNextFrame = false;
12049 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12050 g.NavMoveResultLocal.Clear();
12051 g.NavMoveResultLocalVisible.Clear();
12052 g.NavMoveResultOther.Clear();
12053 g.NavTabbingCounter = 0;
12054 g.NavTabbingResultFirst.Clear();
12055 NavUpdateAnyRequestFlag();
12056}
12057
12058void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12059{
12060 ImGuiContext& g = *GImGui;
12061 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12062 NavApplyItemToResult(result);
12063 NavUpdateAnyRequestFlag();
12064}
12065
12066// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12067void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data)
12068{
12069 ImGuiContext& g = *GImGui;
12070 g.NavMoveScoringItems = false;
12071 g.LastItemData.ID = tree_node_data->ID;
12072 g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12073 g.LastItemData.NavRect = tree_node_data->NavRect;
12074 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12075 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
12076 NavUpdateAnyRequestFlag();
12077}
12078
12079void ImGui::NavMoveRequestCancel()
12080{
12081 ImGuiContext& g = *GImGui;
12082 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12083 NavUpdateAnyRequestFlag();
12084}
12085
12086// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12087void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12088{
12089 ImGuiContext& g = *GImGui;
12090 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12091 NavMoveRequestCancel();
12092 g.NavMoveForwardToNextFrame = true;
12093 g.NavMoveDir = move_dir;
12094 g.NavMoveClipDir = clip_dir;
12095 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12096 g.NavMoveScrollFlags = scroll_flags;
12097}
12098
12099// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12100// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12101void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12102{
12103 ImGuiContext& g = *GImGui;
12104 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12105
12106 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12107 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12108 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12109 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12110}
12111
12112// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12113// This way we could find the last focused window among our children. It would be much less confusing this way?
12114static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12115{
12116 ImGuiWindow* parent = nav_window;
12117 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12118 parent = parent->ParentWindow;
12119 if (parent && parent != nav_window)
12120 parent->NavLastChildNavWindow = nav_window;
12121}
12122
12123// Restore the last focused child.
12124// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12125static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12126{
12127 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12128 return window->NavLastChildNavWindow;
12129 return window;
12130}
12131
12132void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12133{
12134 ImGuiContext& g = *GImGui;
12135 if (layer == ImGuiNavLayer_Main)
12136 {
12137 ImGuiWindow* prev_nav_window = g.NavWindow;
12138 g.NavWindow = NavRestoreLastChildNavWindow(window: g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
12139 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12140 if (prev_nav_window)
12141 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12142 }
12143 ImGuiWindow* window = g.NavWindow;
12144 if (window->NavLastIds[layer] != 0)
12145 {
12146 SetNavID(id: window->NavLastIds[layer], nav_layer: layer, focus_scope_id: 0, rect_rel: window->NavRectRel[layer]);
12147 }
12148 else
12149 {
12150 g.NavLayer = layer;
12151 NavInitWindow(window, force_reinit: true);
12152 }
12153}
12154
12155void ImGui::NavRestoreHighlightAfterMove()
12156{
12157 ImGuiContext& g = *GImGui;
12158 g.NavDisableHighlight = false;
12159 g.NavDisableMouseHover = g.NavMousePosDirty = true;
12160}
12161
12162static inline void ImGui::NavUpdateAnyRequestFlag()
12163{
12164 ImGuiContext& g = *GImGui;
12165 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12166 if (g.NavAnyRequest)
12167 IM_ASSERT(g.NavWindow != NULL);
12168}
12169
12170// This needs to be called before we submit any widget (aka in or before Begin)
12171void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12172{
12173 ImGuiContext& g = *GImGui;
12174 IM_ASSERT(window == g.NavWindow);
12175
12176 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12177 {
12178 g.NavId = 0;
12179 SetNavFocusScope(window->NavRootFocusScopeId);
12180 return;
12181 }
12182
12183 bool init_for_nav = false;
12184 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12185 init_for_nav = true;
12186 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12187 if (init_for_nav)
12188 {
12189 SetNavID(id: 0, nav_layer: g.NavLayer, focus_scope_id: window->NavRootFocusScopeId, rect_rel: ImRect());
12190 g.NavInitRequest = true;
12191 g.NavInitRequestFromMove = false;
12192 g.NavInitResult.ID = 0;
12193 NavUpdateAnyRequestFlag();
12194 }
12195 else
12196 {
12197 g.NavId = window->NavLastIds[0];
12198 SetNavFocusScope(window->NavRootFocusScopeId);
12199 }
12200}
12201
12202static ImVec2 ImGui::NavCalcPreferredRefPos()
12203{
12204 ImGuiContext& g = *GImGui;
12205 ImGuiWindow* window = g.NavWindow;
12206 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12207
12208 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12209 if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
12210 {
12211 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12212 // 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.
12213 // In theory we could move that +1.0f offset in OpenPopupEx()
12214 ImVec2 p = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12215 return ImVec2(p.x + 1.0f, p.y);
12216 }
12217 else
12218 {
12219 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12220 ImRect ref_rect;
12221 if (activated_shortcut)
12222 ref_rect = g.LastItemData.NavRect;
12223 else
12224 ref_rect = WindowRectRelToAbs(window, r: window->NavRectRel[g.NavLayer]);
12225
12226 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12227 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12228 {
12229 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12230 ref_rect.Translate(d: window->Scroll - next_scroll);
12231 }
12232 ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(lhs: g.Style.FramePadding.x * 4, rhs: ref_rect.GetWidth()), ref_rect.Max.y - ImMin(lhs: g.Style.FramePadding.y, rhs: ref_rect.GetHeight()));
12233 ImGuiViewport* viewport = GetMainViewport();
12234 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.
12235 }
12236}
12237
12238float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12239{
12240 ImGuiContext& g = *GImGui;
12241 float repeat_delay, repeat_rate;
12242 GetTypematicRepeatRate(flags: ImGuiInputFlags_RepeatRateNavTweak, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
12243
12244 ImGuiKey key_less, key_more;
12245 if (g.NavInputSource == ImGuiInputSource_Gamepad)
12246 {
12247 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12248 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12249 }
12250 else
12251 {
12252 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12253 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12254 }
12255 float amount = (float)GetKeyPressedAmount(key: key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key: key_less, repeat_delay, repeat_rate);
12256 if (amount != 0.0f && IsKeyDown(key: key_less) && IsKeyDown(key: key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12257 amount = 0.0f;
12258 return amount;
12259}
12260
12261static void ImGui::NavUpdate()
12262{
12263 ImGuiContext& g = *GImGui;
12264 ImGuiIO& io = g.IO;
12265
12266 io.WantSetMousePos = false;
12267 //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);
12268
12269 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12270 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12271 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12272 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12273 if (nav_gamepad_active)
12274 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12275 if (IsKeyDown(key))
12276 g.NavInputSource = ImGuiInputSource_Gamepad;
12277 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12278 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12279 if (nav_keyboard_active)
12280 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12281 if (IsKeyDown(key))
12282 g.NavInputSource = ImGuiInputSource_Keyboard;
12283
12284 // Process navigation init request (select first/default focus)
12285 g.NavJustMovedToId = 0;
12286 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
12287 if (g.NavInitResult.ID != 0)
12288 NavInitRequestApplyResult();
12289 g.NavInitRequest = false;
12290 g.NavInitRequestFromMove = false;
12291 g.NavInitResult.ID = 0;
12292
12293 // Process navigation move request
12294 if (g.NavMoveSubmitted)
12295 NavMoveRequestApplyResult();
12296 g.NavTabbingCounter = 0;
12297 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12298
12299 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12300 bool set_mouse_pos = false;
12301 if (g.NavMousePosDirty && g.NavIdIsAlive)
12302 if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12303 set_mouse_pos = true;
12304 g.NavMousePosDirty = false;
12305 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12306
12307 // 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
12308 if (g.NavWindow)
12309 NavSaveLastChildNavWindowIntoParent(nav_window: g.NavWindow);
12310 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12311 g.NavWindow->NavLastChildNavWindow = NULL;
12312
12313 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12314 NavUpdateWindowing();
12315
12316 // Set output flags for user application
12317 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12318 io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12319
12320 // Process NavCancel input (to close a popup, get back to parent, clear focus)
12321 NavUpdateCancelRequest();
12322
12323 // Process manual activation request
12324 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12325 g.NavActivateFlags = ImGuiActivateFlags_None;
12326 if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12327 {
12328 const bool activate_down = (nav_keyboard_active && IsKeyDown(key: ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
12329 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Space, flags: 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, flags: 0, ImGuiKeyOwner_NoOwner)));
12330 const bool input_down = (nav_keyboard_active && (IsKeyDown(key: ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(key: ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
12331 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(key: ImGuiKey_Enter, flags: 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(key: ImGuiKey_KeypadEnter, flags: 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, flags: 0, ImGuiKeyOwner_NoOwner)));
12332 if (g.ActiveId == 0 && activate_pressed)
12333 {
12334 g.NavActivateId = g.NavId;
12335 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12336 }
12337 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12338 {
12339 g.NavActivateId = g.NavId;
12340 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12341 }
12342 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12343 g.NavActivateDownId = g.NavId;
12344 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12345 {
12346 g.NavActivatePressedId = g.NavId;
12347 NavHighlightActivated(id: g.NavId);
12348 }
12349 }
12350 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12351 g.NavDisableHighlight = true;
12352 if (g.NavActivateId != 0)
12353 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12354
12355 // Highlight
12356 if (g.NavHighlightActivatedTimer > 0.0f)
12357 g.NavHighlightActivatedTimer = ImMax(lhs: 0.0f, rhs: g.NavHighlightActivatedTimer - io.DeltaTime);
12358 if (g.NavHighlightActivatedTimer == 0.0f)
12359 g.NavHighlightActivatedId = 0;
12360
12361 // Process programmatic activation request
12362 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12363 if (g.NavNextActivateId != 0)
12364 {
12365 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12366 g.NavActivateFlags = g.NavNextActivateFlags;
12367 }
12368 g.NavNextActivateId = 0;
12369
12370 // Process move requests
12371 NavUpdateCreateMoveRequest();
12372 if (g.NavMoveDir == ImGuiDir_None)
12373 NavUpdateCreateTabbingRequest();
12374 NavUpdateAnyRequestFlag();
12375 g.NavIdIsAlive = false;
12376
12377 // Scrolling
12378 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12379 {
12380 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12381 ImGuiWindow* window = g.NavWindow;
12382 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.
12383 const ImGuiDir move_dir = g.NavMoveDir;
12384 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12385 {
12386 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12387 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12388 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12389 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12390 }
12391
12392 // *Normal* Manual scroll with LStick
12393 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12394 if (nav_gamepad_active)
12395 {
12396 const ImVec2 scroll_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
12397 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12398 if (scroll_dir.x != 0.0f && window->ScrollbarX)
12399 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12400 if (scroll_dir.y != 0.0f)
12401 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12402 }
12403 }
12404
12405 // Always prioritize mouse highlight if navigation is disabled
12406 if (!nav_keyboard_active && !nav_gamepad_active)
12407 {
12408 g.NavDisableHighlight = true;
12409 g.NavDisableMouseHover = set_mouse_pos = false;
12410 }
12411
12412 // Update mouse position if requested
12413 // (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)
12414 if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12415 TeleportMousePos(pos: NavCalcPreferredRefPos());
12416
12417 // [DEBUG]
12418 g.NavScoringDebugCount = 0;
12419#if IMGUI_DEBUG_NAV_RECTS
12420 if (ImGuiWindow* debug_window = g.NavWindow)
12421 {
12422 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12423 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)); }
12424 //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); }
12425 }
12426#endif
12427}
12428
12429void ImGui::NavInitRequestApplyResult()
12430{
12431 // 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)
12432 ImGuiContext& g = *GImGui;
12433 if (!g.NavWindow)
12434 return;
12435
12436 ImGuiNavItemData* result = &g.NavInitResult;
12437 if (g.NavId != result->ID)
12438 {
12439 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
12440 g.NavJustMovedToId = result->ID;
12441 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12442 g.NavJustMovedToKeyMods = 0;
12443 g.NavJustMovedToIsTabbing = false;
12444 g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
12445 }
12446
12447 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12448 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12449 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12450 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
12451 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12452 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12453 g.NavLastValidSelectionUserData = result->SelectionUserData;
12454 if (g.NavInitRequestFromMove)
12455 NavRestoreHighlightAfterMove();
12456}
12457
12458// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12459static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12460{
12461 // Bias initial rect
12462 ImGuiContext& g = *GImGui;
12463 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12464
12465 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12466 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12467 // - But each successful move sets new bias on one axis, only cleared when using mouse.
12468 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12469 {
12470 if (preferred_pos_rel.x == FLT_MAX)
12471 preferred_pos_rel.x = ImMin(lhs: r.Min.x + 1.0f, rhs: r.Max.x) - rel_to_abs_offset.x;
12472 if (preferred_pos_rel.y == FLT_MAX)
12473 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12474 }
12475
12476 // Apply general bias on the other axis
12477 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12478 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12479 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12480 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12481}
12482
12483void ImGui::NavUpdateCreateMoveRequest()
12484{
12485 ImGuiContext& g = *GImGui;
12486 ImGuiIO& io = g.IO;
12487 ImGuiWindow* window = g.NavWindow;
12488 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12489 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12490
12491 if (g.NavMoveForwardToNextFrame && window != NULL)
12492 {
12493 // 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)
12494 // (preserve most state, which were already set by the NavMoveRequestForward() function)
12495 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12496 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12497 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12498 }
12499 else
12500 {
12501 // Initiate directional inputs request
12502 g.NavMoveDir = ImGuiDir_None;
12503 g.NavMoveFlags = ImGuiNavMoveFlags_None;
12504 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12505 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12506 {
12507 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12508 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadLeft, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_LeftArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
12509 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadRight, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_RightArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
12510 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadUp, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_UpArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
12511 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadDown, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_DownArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
12512 }
12513 g.NavMoveClipDir = g.NavMoveDir;
12514 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12515 }
12516
12517 // Update PageUp/PageDown/Home/End scroll
12518 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12519 float scoring_rect_offset_y = 0.0f;
12520 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12521 scoring_rect_offset_y = NavUpdatePageUpPageDown();
12522 if (scoring_rect_offset_y != 0.0f)
12523 {
12524 g.NavScoringNoClipRect = window->InnerRect;
12525 g.NavScoringNoClipRect.TranslateY(dy: scoring_rect_offset_y);
12526 }
12527
12528 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12529#if IMGUI_DEBUG_NAV_SCORING
12530 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12531 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12532 if (io.KeyCtrl)
12533 {
12534 if (g.NavMoveDir == ImGuiDir_None)
12535 g.NavMoveDir = g.NavMoveDirForDebug;
12536 g.NavMoveClipDir = g.NavMoveDir;
12537 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12538 }
12539#endif
12540
12541 // Submit
12542 g.NavMoveForwardToNextFrame = false;
12543 if (g.NavMoveDir != ImGuiDir_None)
12544 NavMoveRequestSubmit(move_dir: g.NavMoveDir, clip_dir: g.NavMoveClipDir, move_flags: g.NavMoveFlags, scroll_flags: g.NavMoveScrollFlags);
12545
12546 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12547 if (g.NavMoveSubmitted && g.NavId == 0)
12548 {
12549 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12550 g.NavInitRequest = g.NavInitRequestFromMove = true;
12551 g.NavInitResult.ID = 0;
12552 g.NavDisableHighlight = false;
12553 }
12554
12555 // When using gamepad, we project the reference nav bounding box into window visible area.
12556 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12557 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12558 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12559 {
12560 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12561 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12562 ImRect inner_rect_rel = WindowRectAbsToRel(window, r: ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12563
12564 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12565 // Otherwise 'inner_rect_rel' would be off on the move result frame.
12566 inner_rect_rel.Translate(d: CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12567
12568 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(r: window->NavRectRel[g.NavLayer]))
12569 {
12570 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12571 float pad_x = ImMin(lhs: inner_rect_rel.GetWidth(), rhs: window->CalcFontSize() * 0.5f);
12572 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
12573 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12574 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12575 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12576 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12577 window->NavRectRel[g.NavLayer].ClipWithFull(r: inner_rect_rel);
12578 g.NavId = 0;
12579 }
12580 }
12581
12582 // 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)
12583 ImRect scoring_rect;
12584 if (window != NULL)
12585 {
12586 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12587 scoring_rect = WindowRectRelToAbs(window, r: nav_rect_rel);
12588 scoring_rect.TranslateY(dy: scoring_rect_offset_y);
12589 if (g.NavMoveSubmitted)
12590 NavBiasScoringRect(r&: scoring_rect, preferred_pos_rel&: window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], move_dir: g.NavMoveDir, move_flags: g.NavMoveFlags);
12591 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12592 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12593 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12594 }
12595 g.NavScoringRect = scoring_rect;
12596 g.NavScoringNoClipRect.Add(r: scoring_rect);
12597}
12598
12599void ImGui::NavUpdateCreateTabbingRequest()
12600{
12601 ImGuiContext& g = *GImGui;
12602 ImGuiWindow* window = g.NavWindow;
12603 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12604 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12605 return;
12606
12607 const bool tab_pressed = IsKeyPressed(key: ImGuiKey_Tab, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12608 if (!tab_pressed)
12609 return;
12610
12611 // Initiate tabbing request
12612 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12613 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12614 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12615 if (nav_keyboard_active)
12616 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12617 else
12618 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12619 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12620 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12621 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12622 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.
12623 g.NavTabbingCounter = -1;
12624}
12625
12626// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12627void ImGui::NavMoveRequestApplyResult()
12628{
12629 ImGuiContext& g = *GImGui;
12630#if IMGUI_DEBUG_NAV_SCORING
12631 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12632 return;
12633#endif
12634
12635 // Select which result to use
12636 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12637
12638 // Tabbing forward wrap
12639 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12640 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12641 result = &g.NavTabbingResultFirst;
12642
12643 // 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)
12644 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12645 if (result == NULL)
12646 {
12647 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12648 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12649 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12650 NavRestoreHighlightAfterMove();
12651 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12652 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12653 return;
12654 }
12655
12656 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12657 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12658 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12659 result = &g.NavMoveResultLocalVisible;
12660
12661 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12662 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12663 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12664 result = &g.NavMoveResultOther;
12665 IM_ASSERT(g.NavWindow && result->Window);
12666
12667 // Scroll to keep newly navigated item fully into view.
12668 if (g.NavLayer == ImGuiNavLayer_Main)
12669 {
12670 ImRect rect_abs = WindowRectRelToAbs(window: result->Window, r: result->RectRel);
12671 ScrollToRectEx(window: result->Window, item_rect: rect_abs, flags: g.NavMoveScrollFlags);
12672
12673 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12674 {
12675 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12676 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12677 SetScrollY(window: result->Window, scroll_y: scroll_target);
12678 }
12679 }
12680
12681 if (g.NavWindow != result->Window)
12682 {
12683 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12684 g.NavWindow = result->Window;
12685 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12686 }
12687
12688 // Clear active id unless requested not to
12689 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
12690 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
12691 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
12692 ClearActiveID();
12693
12694 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12695 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
12696 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12697 {
12698 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
12699 g.NavJustMovedToId = result->ID;
12700 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12701 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12702 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12703 g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
12704 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
12705 }
12706
12707 // Apply new NavID/Focus
12708 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12709 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12710 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
12711 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12712 g.NavLastValidSelectionUserData = result->SelectionUserData;
12713
12714 // Restore last preferred position for current axis
12715 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12716 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
12717 {
12718 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12719 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12720 }
12721
12722 // Tabbing: Activates Inputable, otherwise only Focus
12723 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12724 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12725
12726 // Activate
12727 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12728 {
12729 g.NavNextActivateId = result->ID;
12730 g.NavNextActivateFlags = ImGuiActivateFlags_None;
12731 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12732 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
12733 }
12734
12735 // Enable nav highlight
12736 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12737 NavRestoreHighlightAfterMove();
12738}
12739
12740// Process NavCancel input (to close a popup, get back to parent, clear focus)
12741// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12742// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12743// - 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
12744static void ImGui::NavUpdateCancelRequest()
12745{
12746 ImGuiContext& g = *GImGui;
12747 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12748 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12749 if (!(nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Escape, flags: 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, flags: 0, ImGuiKeyOwner_NoOwner)))
12750 return;
12751
12752 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12753 if (g.ActiveId != 0)
12754 {
12755 ClearActiveID();
12756 }
12757 else if (g.NavLayer != ImGuiNavLayer_Main)
12758 {
12759 // Leave the "menu" layer
12760 NavRestoreLayer(layer: ImGuiNavLayer_Main);
12761 NavRestoreHighlightAfterMove();
12762 }
12763 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
12764 {
12765 // Exit child window
12766 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
12767 ImGuiWindow* parent_window = child_window->ParentWindow;
12768 IM_ASSERT(child_window->ChildId != 0);
12769 FocusWindow(window: parent_window);
12770 SetNavID(id: child_window->ChildId, nav_layer: ImGuiNavLayer_Main, focus_scope_id: 0, rect_rel: WindowRectAbsToRel(window: parent_window, r: child_window->Rect()));
12771 NavRestoreHighlightAfterMove();
12772 }
12773 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12774 {
12775 // Close open popup/menu
12776 ClosePopupToLevel(remaining: g.OpenPopupStack.Size - 1, restore_focus_to_window_under_popup: true);
12777 }
12778 else
12779 {
12780 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12781 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12782 g.NavWindow->NavLastIds[0] = 0;
12783 g.NavId = 0;
12784 }
12785}
12786
12787// Handle PageUp/PageDown/Home/End keys
12788// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12789// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12790// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12791static float ImGui::NavUpdatePageUpPageDown()
12792{
12793 ImGuiContext& g = *GImGui;
12794 ImGuiWindow* window = g.NavWindow;
12795 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12796 return 0.0f;
12797
12798 const bool page_up_held = IsKeyDown(key: ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
12799 const bool page_down_held = IsKeyDown(key: ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
12800 const bool home_pressed = IsKeyPressed(key: ImGuiKey_Home, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
12801 const bool end_pressed = IsKeyPressed(key: ImGuiKey_End, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
12802 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12803 return 0.0f;
12804
12805 if (g.NavLayer != ImGuiNavLayer_Main)
12806 NavRestoreLayer(layer: ImGuiNavLayer_Main);
12807
12808 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12809 {
12810 // Fallback manual-scroll when window has no navigable item
12811 if (IsKeyPressed(key: ImGuiKey_PageUp, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
12812 SetScrollY(window, scroll_y: window->Scroll.y - window->InnerRect.GetHeight());
12813 else if (IsKeyPressed(key: ImGuiKey_PageDown, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
12814 SetScrollY(window, scroll_y: window->Scroll.y + window->InnerRect.GetHeight());
12815 else if (home_pressed)
12816 SetScrollY(window, scroll_y: 0.0f);
12817 else if (end_pressed)
12818 SetScrollY(window, scroll_y: window->ScrollMax.y);
12819 }
12820 else
12821 {
12822 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12823 const float page_offset_y = ImMax(lhs: 0.0f, rhs: window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12824 float nav_scoring_rect_offset_y = 0.0f;
12825 if (IsKeyPressed(key: ImGuiKey_PageUp, repeat: true))
12826 {
12827 nav_scoring_rect_offset_y = -page_offset_y;
12828 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)
12829 g.NavMoveClipDir = ImGuiDir_Up;
12830 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12831 }
12832 else if (IsKeyPressed(key: ImGuiKey_PageDown, repeat: true))
12833 {
12834 nav_scoring_rect_offset_y = +page_offset_y;
12835 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)
12836 g.NavMoveClipDir = ImGuiDir_Down;
12837 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12838 }
12839 else if (home_pressed)
12840 {
12841 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12842 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12843 // Preserve current horizontal position if we have any.
12844 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12845 if (nav_rect_rel.IsInverted())
12846 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12847 g.NavMoveDir = ImGuiDir_Down;
12848 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12849 // FIXME-NAV: MoveClipDir left to _None, intentional?
12850 }
12851 else if (end_pressed)
12852 {
12853 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12854 if (nav_rect_rel.IsInverted())
12855 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12856 g.NavMoveDir = ImGuiDir_Up;
12857 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12858 // FIXME-NAV: MoveClipDir left to _None, intentional?
12859 }
12860 return nav_scoring_rect_offset_y;
12861 }
12862 return 0.0f;
12863}
12864
12865static void ImGui::NavEndFrame()
12866{
12867 ImGuiContext& g = *GImGui;
12868
12869 // Show CTRL+TAB list window
12870 if (g.NavWindowingTarget != NULL)
12871 NavUpdateWindowingOverlay();
12872
12873 // Perform wrap-around in menus
12874 // 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.
12875 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12876 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12877 NavUpdateCreateWrappingRequest();
12878}
12879
12880static void ImGui::NavUpdateCreateWrappingRequest()
12881{
12882 ImGuiContext& g = *GImGui;
12883 ImGuiWindow* window = g.NavWindow;
12884
12885 bool do_forward = false;
12886 ImRect bb_rel = window->NavRectRel[g.NavLayer];
12887 ImGuiDir clip_dir = g.NavMoveDir;
12888
12889 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12890 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12891 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12892 {
12893 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12894 if (move_flags & ImGuiNavMoveFlags_WrapX)
12895 {
12896 bb_rel.TranslateY(dy: -bb_rel.GetHeight()); // Previous row
12897 clip_dir = ImGuiDir_Up;
12898 }
12899 do_forward = true;
12900 }
12901 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12902 {
12903 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12904 if (move_flags & ImGuiNavMoveFlags_WrapX)
12905 {
12906 bb_rel.TranslateY(dy: +bb_rel.GetHeight()); // Next row
12907 clip_dir = ImGuiDir_Down;
12908 }
12909 do_forward = true;
12910 }
12911 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12912 {
12913 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12914 if (move_flags & ImGuiNavMoveFlags_WrapY)
12915 {
12916 bb_rel.TranslateX(dx: -bb_rel.GetWidth()); // Previous column
12917 clip_dir = ImGuiDir_Left;
12918 }
12919 do_forward = true;
12920 }
12921 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12922 {
12923 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12924 if (move_flags & ImGuiNavMoveFlags_WrapY)
12925 {
12926 bb_rel.TranslateX(dx: +bb_rel.GetWidth()); // Next column
12927 clip_dir = ImGuiDir_Right;
12928 }
12929 do_forward = true;
12930 }
12931 if (!do_forward)
12932 return;
12933 window->NavRectRel[g.NavLayer] = bb_rel;
12934 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
12935 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
12936 NavMoveRequestForward(move_dir: g.NavMoveDir, clip_dir, move_flags, scroll_flags: g.NavMoveScrollFlags);
12937}
12938
12939static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12940{
12941 ImGuiContext& g = *GImGui;
12942 IM_UNUSED(g);
12943 int order = window->FocusOrder;
12944 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12945 IM_ASSERT(g.WindowsFocusOrder[order] == window);
12946 return order;
12947}
12948
12949static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12950{
12951 ImGuiContext& g = *GImGui;
12952 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12953 if (ImGui::IsWindowNavFocusable(window: g.WindowsFocusOrder[i]))
12954 return g.WindowsFocusOrder[i];
12955 return NULL;
12956}
12957
12958static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12959{
12960 ImGuiContext& g = *GImGui;
12961 IM_ASSERT(g.NavWindowingTarget);
12962 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12963 return;
12964
12965 const int i_current = ImGui::FindWindowFocusIndex(window: g.NavWindowingTarget);
12966 ImGuiWindow* window_target = FindWindowNavFocusable(i_start: i_current + focus_change_dir, i_stop: -INT_MAX, dir: focus_change_dir);
12967 if (!window_target)
12968 window_target = FindWindowNavFocusable(i_start: (focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_stop: i_current, dir: focus_change_dir);
12969 if (window_target) // Don't reset windowing target if there's a single window in the list
12970 {
12971 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12972 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12973 }
12974 g.NavWindowingToggleLayer = false;
12975}
12976
12977// Windowing management mode
12978// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12979// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12980static void ImGui::NavUpdateWindowing()
12981{
12982 ImGuiContext& g = *GImGui;
12983 ImGuiIO& io = g.IO;
12984
12985 ImGuiWindow* apply_focus_window = NULL;
12986 bool apply_toggle_layer = false;
12987
12988 ImGuiWindow* modal_window = GetTopMostPopupModal();
12989 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.
12990 if (!allow_windowing)
12991 g.NavWindowingTarget = NULL;
12992
12993 // Fade out
12994 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12995 {
12996 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, rhs: 0.0f);
12997 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12998 g.NavWindowingTargetAnim = NULL;
12999 }
13000
13001 // Start CTRL+Tab or Square+L/R window selection
13002 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13003 const ImGuiID owner_id = ImHashStr(data_p: "###NavUpdateWindowing");
13004 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13005 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13006 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(key_chord: g.ConfigNavWindowingKeyNext, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13007 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(key_chord: g.ConfigNavWindowingKeyPrev, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13008 const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, flags: ImGuiInputFlags_None);
13009 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13010 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13011 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(i_start: g.WindowsFocusOrder.Size - 1, i_stop: -INT_MAX, dir: -1))
13012 {
13013 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13014 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13015 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13016 g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13017 g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13018
13019 // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13020 if (keyboard_next_window || keyboard_prev_window)
13021 SetKeyOwnersForKeyChord(key_chord: (g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13022 }
13023
13024 // Gamepad update
13025 g.NavWindowingTimer += io.DeltaTime;
13026 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13027 {
13028 // 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
13029 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha, rhs: ImSaturate(f: (g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13030
13031 // Select window to focus
13032 const int focus_change_dir = (int)IsKeyPressed(key: ImGuiKey_GamepadL1) - (int)IsKeyPressed(key: ImGuiKey_GamepadR1);
13033 if (focus_change_dir != 0)
13034 {
13035 NavUpdateWindowingHighlightWindow(focus_change_dir);
13036 g.NavWindowingHighlightAlpha = 1.0f;
13037 }
13038
13039 // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13040 if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13041 {
13042 g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13043 if (g.NavWindowingToggleLayer && g.NavWindow)
13044 apply_toggle_layer = true;
13045 else if (!g.NavWindowingToggleLayer)
13046 apply_focus_window = g.NavWindowingTarget;
13047 g.NavWindowingTarget = NULL;
13048 }
13049 }
13050
13051 // Keyboard: Focus
13052 if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13053 {
13054 // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13055 ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13056 IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13057 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha, rhs: ImSaturate(f: (g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13058 if (keyboard_next_window || keyboard_prev_window)
13059 NavUpdateWindowingHighlightWindow(focus_change_dir: keyboard_next_window ? -1 : +1);
13060 else if ((io.KeyMods & shared_mods) != shared_mods)
13061 apply_focus_window = g.NavWindowingTarget;
13062 }
13063
13064 // Keyboard: Press and Release ALT to toggle menu layer
13065 const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13066 for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13067 if (nav_keyboard_active && IsKeyPressed(key: windowing_toggle_key, flags: 0, ImGuiKeyOwner_NoOwner))
13068 {
13069 g.NavWindowingToggleLayer = true;
13070 g.NavWindowingToggleKey = windowing_toggle_key;
13071 g.NavInputSource = ImGuiInputSource_Keyboard;
13072 break;
13073 }
13074 if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13075 {
13076 // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13077 // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13078 // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13079 // We cancel toggling nav layer if an owner has claimed the key.
13080 if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13081 g.NavWindowingToggleLayer = false;
13082 if (TestKeyOwner(key: g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(key: ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13083 g.NavWindowingToggleLayer = false;
13084
13085 // Apply layer toggle on Alt release
13086 // 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.
13087 if (IsKeyReleased(key: g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13088 if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13089 if (IsMousePosValid(mouse_pos: &io.MousePos) == IsMousePosValid(mouse_pos: &io.MousePosPrev))
13090 apply_toggle_layer = true;
13091 if (!IsKeyDown(key: g.NavWindowingToggleKey))
13092 g.NavWindowingToggleLayer = false;
13093 }
13094
13095 // Move window
13096 if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13097 {
13098 ImVec2 nav_move_dir;
13099 if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13100 nav_move_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
13101 if (g.NavInputSource == ImGuiInputSource_Gamepad)
13102 nav_move_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
13103 if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13104 {
13105 const float NAV_MOVE_SPEED = 800.0f;
13106 const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(lhs: io.DisplayFramebufferScale.x, rhs: io.DisplayFramebufferScale.y);
13107 g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13108 g.NavDisableMouseHover = true;
13109 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaPos);
13110 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13111 {
13112 ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
13113 SetWindowPos(window: moving_window, pos: moving_window->Pos + accum_floored, cond: ImGuiCond_Always);
13114 g.NavWindowingAccumDeltaPos -= accum_floored;
13115 }
13116 }
13117 }
13118
13119 // Apply final focus
13120 if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13121 {
13122 ClearActiveID();
13123 NavRestoreHighlightAfterMove();
13124 ClosePopupsOverWindow(ref_window: apply_focus_window, restore_focus_to_window_under_popup: false);
13125 FocusWindow(window: apply_focus_window, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
13126 apply_focus_window = g.NavWindow;
13127 if (apply_focus_window->NavLastIds[0] == 0)
13128 NavInitWindow(window: apply_focus_window, force_reinit: false);
13129
13130 // If the window has ONLY a menu layer (no main layer), select it directly
13131 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13132 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13133 // the target window as already been previewed once.
13134 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13135 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13136 // won't be valid.
13137 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13138 g.NavLayer = ImGuiNavLayer_Menu;
13139 }
13140 if (apply_focus_window)
13141 g.NavWindowingTarget = NULL;
13142
13143 // Apply menu/layer toggle
13144 if (apply_toggle_layer && g.NavWindow)
13145 {
13146 ClearActiveID();
13147
13148 // Move to parent menu if necessary
13149 ImGuiWindow* new_nav_window = g.NavWindow;
13150 while (new_nav_window->ParentWindow
13151 && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13152 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13153 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13154 new_nav_window = new_nav_window->ParentWindow;
13155 if (new_nav_window != g.NavWindow)
13156 {
13157 ImGuiWindow* old_nav_window = g.NavWindow;
13158 FocusWindow(window: new_nav_window);
13159 new_nav_window->NavLastChildNavWindow = old_nav_window;
13160 }
13161
13162 // Toggle layer
13163 const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13164 if (new_nav_layer != g.NavLayer)
13165 {
13166 // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13167 if (new_nav_layer == ImGuiNavLayer_Menu)
13168 g.NavWindow->NavLastIds[new_nav_layer] = 0;
13169 NavRestoreLayer(layer: new_nav_layer);
13170 NavRestoreHighlightAfterMove();
13171 }
13172 }
13173}
13174
13175// Window has already passed the IsWindowNavFocusable()
13176static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13177{
13178 if (window->Flags & ImGuiWindowFlags_Popup)
13179 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingPopup);
13180 if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(s1: window->Name, s2: "##MainMenuBar") == 0)
13181 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingMainMenuBar);
13182 return ImGui::LocalizeGetMsg(key: ImGuiLocKey_WindowingUntitled);
13183}
13184
13185// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13186void ImGui::NavUpdateWindowingOverlay()
13187{
13188 ImGuiContext& g = *GImGui;
13189 IM_ASSERT(g.NavWindowingTarget != NULL);
13190
13191 if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13192 return;
13193
13194 if (g.NavWindowingListWindow == NULL)
13195 g.NavWindowingListWindow = FindWindowByName(name: "###NavWindowingList");
13196 const ImGuiViewport* viewport = GetMainViewport();
13197 SetNextWindowSizeConstraints(size_min: ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), size_max: ImVec2(FLT_MAX, FLT_MAX));
13198 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_Always, pivot: ImVec2(0.5f, 0.5f));
13199 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.WindowPadding * 2.0f);
13200 Begin(name: "###NavWindowingList", NULL, flags: ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13201 if (g.ContextName[0] != 0)
13202 SeparatorText(label: g.ContextName);
13203 for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13204 {
13205 ImGuiWindow* window = g.WindowsFocusOrder[n];
13206 IM_ASSERT(window != NULL); // Fix static analyzers
13207 if (!IsWindowNavFocusable(window))
13208 continue;
13209 const char* label = window->Name;
13210 if (label == FindRenderedTextEnd(text: label))
13211 label = GetFallbackWindowNameForWindowingList(window);
13212 Selectable(label, selected: g.NavWindowingTarget == window);
13213 }
13214 End();
13215 PopStyleVar();
13216}
13217
13218
13219//-----------------------------------------------------------------------------
13220// [SECTION] DRAG AND DROP
13221//-----------------------------------------------------------------------------
13222
13223bool ImGui::IsDragDropActive()
13224{
13225 ImGuiContext& g = *GImGui;
13226 return g.DragDropActive;
13227}
13228
13229void ImGui::ClearDragDrop()
13230{
13231 ImGuiContext& g = *GImGui;
13232 if (g.DragDropActive)
13233 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13234 g.DragDropActive = false;
13235 g.DragDropPayload.Clear();
13236 g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13237 g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13238 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13239 g.DragDropAcceptFrameCount = -1;
13240
13241 g.DragDropPayloadBufHeap.clear();
13242 memset(s: &g.DragDropPayloadBufLocal, c: 0, n: sizeof(g.DragDropPayloadBufLocal));
13243}
13244
13245bool ImGui::BeginTooltipHidden()
13246{
13247 ImGuiContext& g = *GImGui;
13248 bool ret = Begin(name: "##Tooltip_Hidden", NULL, flags: ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13249 SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13250 return ret;
13251}
13252
13253// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13254// If the item has an identifier:
13255// - This assume/require the item to be activated (typically via ButtonBehavior).
13256// - 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.
13257// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13258// If the item has no identifier:
13259// - Currently always assume left mouse button.
13260bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13261{
13262 ImGuiContext& g = *GImGui;
13263 ImGuiWindow* window = g.CurrentWindow;
13264
13265 // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13266 // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13267 ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13268
13269 bool source_drag_active = false;
13270 ImGuiID source_id = 0;
13271 ImGuiID source_parent_id = 0;
13272 if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13273 {
13274 source_id = g.LastItemData.ID;
13275 if (source_id != 0)
13276 {
13277 // Common path: items with ID
13278 if (g.ActiveId != source_id)
13279 return false;
13280 if (g.ActiveIdMouseButton != -1)
13281 mouse_button = g.ActiveIdMouseButton;
13282 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13283 return false;
13284 g.ActiveIdAllowOverlap = false;
13285 }
13286 else
13287 {
13288 // Uncommon path: items without ID
13289 if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13290 return false;
13291 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13292 return false;
13293
13294 // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13295 // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13296 if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13297 {
13298 IM_ASSERT(0);
13299 return false;
13300 }
13301
13302 // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13303 // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13304 // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13305 // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13306 // Rely on keeping other window->LastItemXXX fields intact.
13307 source_id = g.LastItemData.ID = window->GetIDFromRectangle(r_abs: g.LastItemData.Rect);
13308 KeepAliveID(id: source_id);
13309 bool is_hovered = ItemHoverable(bb: g.LastItemData.Rect, id: source_id, item_flags: g.LastItemData.InFlags);
13310 if (is_hovered && g.IO.MouseClicked[mouse_button])
13311 {
13312 SetActiveID(id: source_id, window);
13313 FocusWindow(window);
13314 }
13315 if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13316 g.ActiveIdAllowOverlap = is_hovered;
13317 }
13318 if (g.ActiveId != source_id)
13319 return false;
13320 source_parent_id = window->IDStack.back();
13321 source_drag_active = IsMouseDragging(button: mouse_button);
13322
13323 // Disable navigation and key inputs while dragging + cancel existing request if any
13324 SetActiveIdUsingAllKeyboardKeys();
13325 }
13326 else
13327 {
13328 // When ImGuiDragDropFlags_SourceExtern is set:
13329 window = NULL;
13330 source_id = ImHashStr(data_p: "#SourceExtern");
13331 source_drag_active = true;
13332 mouse_button = g.IO.MouseDown[0] ? 0 : -1;
13333 KeepAliveID(id: source_id);
13334 SetActiveID(id: source_id, NULL);
13335 }
13336
13337 IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13338 if (!source_drag_active)
13339 return false;
13340
13341 // Activate drag and drop
13342 if (!g.DragDropActive)
13343 {
13344 IM_ASSERT(source_id != 0);
13345 ClearDragDrop();
13346 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
13347 source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
13348 ImGuiPayload& payload = g.DragDropPayload;
13349 payload.SourceId = source_id;
13350 payload.SourceParentId = source_parent_id;
13351 g.DragDropActive = true;
13352 g.DragDropSourceFlags = flags;
13353 g.DragDropMouseButton = mouse_button;
13354 if (payload.SourceId == g.ActiveId)
13355 g.ActiveIdNoClearOnFocusLoss = true;
13356 }
13357 g.DragDropSourceFrameCount = g.FrameCount;
13358 g.DragDropWithinSource = true;
13359
13360 if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13361 {
13362 // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13363 // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13364 bool ret;
13365 if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13366 ret = BeginTooltipHidden();
13367 else
13368 ret = BeginTooltip();
13369 IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13370 IM_UNUSED(ret);
13371 }
13372
13373 if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13374 g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13375
13376 return true;
13377}
13378
13379void ImGui::EndDragDropSource()
13380{
13381 ImGuiContext& g = *GImGui;
13382 IM_ASSERT(g.DragDropActive);
13383 IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13384
13385 if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13386 EndTooltip();
13387
13388 // Discard the drag if have not called SetDragDropPayload()
13389 if (g.DragDropPayload.DataFrameCount == -1)
13390 ClearDragDrop();
13391 g.DragDropWithinSource = false;
13392}
13393
13394// Use 'cond' to choose to submit payload on drag start or every frame
13395bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13396{
13397 ImGuiContext& g = *GImGui;
13398 ImGuiPayload& payload = g.DragDropPayload;
13399 if (cond == 0)
13400 cond = ImGuiCond_Always;
13401
13402 IM_ASSERT(type != NULL);
13403 IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13404 IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13405 IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13406 IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
13407
13408 if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13409 {
13410 // Copy payload
13411 ImStrncpy(dst: payload.DataType, src: type, IM_ARRAYSIZE(payload.DataType));
13412 g.DragDropPayloadBufHeap.resize(new_size: 0);
13413 if (data_size > sizeof(g.DragDropPayloadBufLocal))
13414 {
13415 // Store in heap
13416 g.DragDropPayloadBufHeap.resize(new_size: (int)data_size);
13417 payload.Data = g.DragDropPayloadBufHeap.Data;
13418 memcpy(dest: payload.Data, src: data, n: data_size);
13419 }
13420 else if (data_size > 0)
13421 {
13422 // Store locally
13423 memset(s: &g.DragDropPayloadBufLocal, c: 0, n: sizeof(g.DragDropPayloadBufLocal));
13424 payload.Data = g.DragDropPayloadBufLocal;
13425 memcpy(dest: payload.Data, src: data, n: data_size);
13426 }
13427 else
13428 {
13429 payload.Data = NULL;
13430 }
13431 payload.DataSize = (int)data_size;
13432 }
13433 payload.DataFrameCount = g.FrameCount;
13434
13435 // Return whether the payload has been accepted
13436 return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13437}
13438
13439bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13440{
13441 ImGuiContext& g = *GImGui;
13442 if (!g.DragDropActive)
13443 return false;
13444
13445 ImGuiWindow* window = g.CurrentWindow;
13446 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13447 if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
13448 return false;
13449 IM_ASSERT(id != 0);
13450 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max) || (id == g.DragDropPayload.SourceId))
13451 return false;
13452 if (window->SkipItems)
13453 return false;
13454
13455 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13456 g.DragDropTargetRect = bb;
13457 g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
13458 g.DragDropTargetId = id;
13459 g.DragDropWithinTarget = true;
13460 return true;
13461}
13462
13463// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13464// 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.
13465// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13466// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13467bool ImGui::BeginDragDropTarget()
13468{
13469 ImGuiContext& g = *GImGui;
13470 if (!g.DragDropActive)
13471 return false;
13472
13473 ImGuiWindow* window = g.CurrentWindow;
13474 if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13475 return false;
13476 ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13477 if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)
13478 return false;
13479
13480 const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13481 ImGuiID id = g.LastItemData.ID;
13482 if (id == 0)
13483 {
13484 id = window->GetIDFromRectangle(r_abs: display_rect);
13485 KeepAliveID(id);
13486 }
13487 if (g.DragDropPayload.SourceId == id)
13488 return false;
13489
13490 IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13491 g.DragDropTargetRect = display_rect;
13492 g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
13493 g.DragDropTargetId = id;
13494 g.DragDropWithinTarget = true;
13495 return true;
13496}
13497
13498bool ImGui::IsDragDropPayloadBeingAccepted()
13499{
13500 ImGuiContext& g = *GImGui;
13501 return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13502}
13503
13504const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13505{
13506 ImGuiContext& g = *GImGui;
13507 ImGuiPayload& payload = g.DragDropPayload;
13508 IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13509 IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
13510 if (type != NULL && !payload.IsDataType(type))
13511 return NULL;
13512
13513 // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13514 // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13515 const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13516 ImRect r = g.DragDropTargetRect;
13517 float r_surface = r.GetWidth() * r.GetHeight();
13518 if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13519 return NULL;
13520
13521 g.DragDropAcceptFlags = flags;
13522 g.DragDropAcceptIdCurr = g.DragDropTargetId;
13523 g.DragDropAcceptIdCurrRectSurface = r_surface;
13524 //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13525
13526 // Render default drop visuals
13527 payload.Preview = was_accepted_previously;
13528 flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13529 if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13530 RenderDragDropTargetRect(bb: r, item_clip_rect: g.DragDropTargetClipRect);
13531
13532 g.DragDropAcceptFrameCount = g.FrameCount;
13533 if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
13534 payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
13535 else
13536 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()
13537 if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13538 return NULL;
13539
13540 if (payload.Delivery)
13541 IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
13542 return &payload;
13543}
13544
13545// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13546void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
13547{
13548 ImGuiContext& g = *GImGui;
13549 ImGuiWindow* window = g.CurrentWindow;
13550 ImRect bb_display = bb;
13551 bb_display.ClipWith(r: item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13552 bb_display.Expand(amount: 3.5f);
13553 bool push_clip_rect = !window->ClipRect.Contains(r: bb_display);
13554 if (push_clip_rect)
13555 window->DrawList->PushClipRectFullScreen();
13556 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);
13557 if (push_clip_rect)
13558 window->DrawList->PopClipRect();
13559}
13560
13561const ImGuiPayload* ImGui::GetDragDropPayload()
13562{
13563 ImGuiContext& g = *GImGui;
13564 return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13565}
13566
13567void ImGui::EndDragDropTarget()
13568{
13569 ImGuiContext& g = *GImGui;
13570 IM_ASSERT(g.DragDropActive);
13571 IM_ASSERT(g.DragDropWithinTarget);
13572 g.DragDropWithinTarget = false;
13573
13574 // Clear drag and drop state payload right after delivery
13575 if (g.DragDropPayload.Delivery)
13576 ClearDragDrop();
13577}
13578
13579//-----------------------------------------------------------------------------
13580// [SECTION] LOGGING/CAPTURING
13581//-----------------------------------------------------------------------------
13582// All text output from the interface can be captured into tty/file/clipboard.
13583// By default, tree nodes are automatically opened during logging.
13584//-----------------------------------------------------------------------------
13585
13586// Pass text data straight to log (without being displayed)
13587static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13588{
13589 if (g.LogFile)
13590 {
13591 g.LogBuffer.Buf.resize(new_size: 0);
13592 g.LogBuffer.appendfv(fmt, args);
13593 ImFileWrite(data: g.LogBuffer.c_str(), sz: sizeof(char), count: (ImU64)g.LogBuffer.size(), f: g.LogFile);
13594 }
13595 else
13596 {
13597 g.LogBuffer.appendfv(fmt, args);
13598 }
13599}
13600
13601void ImGui::LogText(const char* fmt, ...)
13602{
13603 ImGuiContext& g = *GImGui;
13604 if (!g.LogEnabled)
13605 return;
13606
13607 va_list args;
13608 va_start(args, fmt);
13609 LogTextV(g, fmt, args);
13610 va_end(args);
13611}
13612
13613void ImGui::LogTextV(const char* fmt, va_list args)
13614{
13615 ImGuiContext& g = *GImGui;
13616 if (!g.LogEnabled)
13617 return;
13618
13619 LogTextV(g, fmt, args);
13620}
13621
13622// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13623// We split text into individual lines to add current tree level padding
13624// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13625void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13626{
13627 ImGuiContext& g = *GImGui;
13628 ImGuiWindow* window = g.CurrentWindow;
13629
13630 const char* prefix = g.LogNextPrefix;
13631 const char* suffix = g.LogNextSuffix;
13632 g.LogNextPrefix = g.LogNextSuffix = NULL;
13633
13634 if (!text_end)
13635 text_end = FindRenderedTextEnd(text, text_end);
13636
13637 const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13638 if (ref_pos)
13639 g.LogLinePosY = ref_pos->y;
13640 if (log_new_line)
13641 {
13642 LogText(IM_NEWLINE);
13643 g.LogLineFirstItem = true;
13644 }
13645
13646 if (prefix)
13647 LogRenderedText(ref_pos, text: prefix, text_end: prefix + strlen(s: prefix)); // Calculate end ourself to ensure "##" are included here.
13648
13649 // Re-adjust padding if we have popped out of our starting depth
13650 if (g.LogDepthRef > window->DC.TreeDepth)
13651 g.LogDepthRef = window->DC.TreeDepth;
13652 const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13653
13654 const char* text_remaining = text;
13655 for (;;)
13656 {
13657 // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13658 // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13659 const char* line_start = text_remaining;
13660 const char* line_end = ImStreolRange(str: line_start, str_end: text_end);
13661 const bool is_last_line = (line_end == text_end);
13662 if (line_start != line_end || !is_last_line)
13663 {
13664 const int line_length = (int)(line_end - line_start);
13665 const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13666 LogText(fmt: "%*s%.*s", indentation, "", line_length, line_start);
13667 g.LogLineFirstItem = false;
13668 if (*line_end == '\n')
13669 {
13670 LogText(IM_NEWLINE);
13671 g.LogLineFirstItem = true;
13672 }
13673 }
13674 if (is_last_line)
13675 break;
13676 text_remaining = line_end + 1;
13677 }
13678
13679 if (suffix)
13680 LogRenderedText(ref_pos, text: suffix, text_end: suffix + strlen(s: suffix));
13681}
13682
13683// Start logging/capturing text output
13684void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13685{
13686 ImGuiContext& g = *GImGui;
13687 ImGuiWindow* window = g.CurrentWindow;
13688 IM_ASSERT(g.LogEnabled == false);
13689 IM_ASSERT(g.LogFile == NULL);
13690 IM_ASSERT(g.LogBuffer.empty());
13691 g.LogEnabled = g.ItemUnclipByLog = true;
13692 g.LogType = type;
13693 g.LogNextPrefix = g.LogNextSuffix = NULL;
13694 g.LogDepthRef = window->DC.TreeDepth;
13695 g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13696 g.LogLinePosY = FLT_MAX;
13697 g.LogLineFirstItem = true;
13698}
13699
13700// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13701void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13702{
13703 ImGuiContext& g = *GImGui;
13704 g.LogNextPrefix = prefix;
13705 g.LogNextSuffix = suffix;
13706}
13707
13708void ImGui::LogToTTY(int auto_open_depth)
13709{
13710 ImGuiContext& g = *GImGui;
13711 if (g.LogEnabled)
13712 return;
13713 IM_UNUSED(auto_open_depth);
13714#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13715 LogBegin(type: ImGuiLogType_TTY, auto_open_depth);
13716 g.LogFile = stdout;
13717#endif
13718}
13719
13720// Start logging/capturing text output to given file
13721void ImGui::LogToFile(int auto_open_depth, const char* filename)
13722{
13723 ImGuiContext& g = *GImGui;
13724 if (g.LogEnabled)
13725 return;
13726
13727 // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13728 // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13729 // By opening the file in binary mode "ab" we have consistent output everywhere.
13730 if (!filename)
13731 filename = g.IO.LogFilename;
13732 if (!filename || !filename[0])
13733 return;
13734 ImFileHandle f = ImFileOpen(filename, mode: "ab");
13735 if (!f)
13736 {
13737 IM_ASSERT(0);
13738 return;
13739 }
13740
13741 LogBegin(type: ImGuiLogType_File, auto_open_depth);
13742 g.LogFile = f;
13743}
13744
13745// Start logging/capturing text output to clipboard
13746void ImGui::LogToClipboard(int auto_open_depth)
13747{
13748 ImGuiContext& g = *GImGui;
13749 if (g.LogEnabled)
13750 return;
13751 LogBegin(type: ImGuiLogType_Clipboard, auto_open_depth);
13752}
13753
13754void ImGui::LogToBuffer(int auto_open_depth)
13755{
13756 ImGuiContext& g = *GImGui;
13757 if (g.LogEnabled)
13758 return;
13759 LogBegin(type: ImGuiLogType_Buffer, auto_open_depth);
13760}
13761
13762void ImGui::LogFinish()
13763{
13764 ImGuiContext& g = *GImGui;
13765 if (!g.LogEnabled)
13766 return;
13767
13768 LogText(IM_NEWLINE);
13769 switch (g.LogType)
13770 {
13771 case ImGuiLogType_TTY:
13772#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13773 fflush(stream: g.LogFile);
13774#endif
13775 break;
13776 case ImGuiLogType_File:
13777 ImFileClose(f: g.LogFile);
13778 break;
13779 case ImGuiLogType_Buffer:
13780 break;
13781 case ImGuiLogType_Clipboard:
13782 if (!g.LogBuffer.empty())
13783 SetClipboardText(g.LogBuffer.begin());
13784 break;
13785 case ImGuiLogType_None:
13786 IM_ASSERT(0);
13787 break;
13788 }
13789
13790 g.LogEnabled = g.ItemUnclipByLog = false;
13791 g.LogType = ImGuiLogType_None;
13792 g.LogFile = NULL;
13793 g.LogBuffer.clear();
13794}
13795
13796// Helper to display logging buttons
13797// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13798void ImGui::LogButtons()
13799{
13800 ImGuiContext& g = *GImGui;
13801
13802 PushID(str_id: "LogButtons");
13803#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13804 const bool log_to_tty = Button(label: "Log To TTY"); SameLine();
13805#else
13806 const bool log_to_tty = false;
13807#endif
13808 const bool log_to_file = Button(label: "Log To File"); SameLine();
13809 const bool log_to_clipboard = Button(label: "Log To Clipboard"); SameLine();
13810 PushItemFlag(option: ImGuiItemFlags_NoTabStop, enabled: true);
13811 SetNextItemWidth(80.0f);
13812 SliderInt(label: "Default Depth", v: &g.LogDepthToExpandDefault, v_min: 0, v_max: 9, NULL);
13813 PopItemFlag();
13814 PopID();
13815
13816 // Start logging at the end of the function so that the buttons don't appear in the log
13817 if (log_to_tty)
13818 LogToTTY();
13819 if (log_to_file)
13820 LogToFile();
13821 if (log_to_clipboard)
13822 LogToClipboard();
13823}
13824
13825
13826//-----------------------------------------------------------------------------
13827// [SECTION] SETTINGS
13828//-----------------------------------------------------------------------------
13829// - UpdateSettings() [Internal]
13830// - MarkIniSettingsDirty() [Internal]
13831// - FindSettingsHandler() [Internal]
13832// - ClearIniSettings() [Internal]
13833// - LoadIniSettingsFromDisk()
13834// - LoadIniSettingsFromMemory()
13835// - SaveIniSettingsToDisk()
13836// - SaveIniSettingsToMemory()
13837//-----------------------------------------------------------------------------
13838// - CreateNewWindowSettings() [Internal]
13839// - FindWindowSettingsByID() [Internal]
13840// - FindWindowSettingsByWindow() [Internal]
13841// - ClearWindowSettings() [Internal]
13842// - WindowSettingsHandler_***() [Internal]
13843//-----------------------------------------------------------------------------
13844
13845// Called by NewFrame()
13846void ImGui::UpdateSettings()
13847{
13848 // Load settings on first frame (if not explicitly loaded manually before)
13849 ImGuiContext& g = *GImGui;
13850 if (!g.SettingsLoaded)
13851 {
13852 IM_ASSERT(g.SettingsWindows.empty());
13853 if (g.IO.IniFilename)
13854 LoadIniSettingsFromDisk(ini_filename: g.IO.IniFilename);
13855 g.SettingsLoaded = true;
13856 }
13857
13858 // Save settings (with a delay after the last modification, so we don't spam disk too much)
13859 if (g.SettingsDirtyTimer > 0.0f)
13860 {
13861 g.SettingsDirtyTimer -= g.IO.DeltaTime;
13862 if (g.SettingsDirtyTimer <= 0.0f)
13863 {
13864 if (g.IO.IniFilename != NULL)
13865 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
13866 else
13867 g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13868 g.SettingsDirtyTimer = 0.0f;
13869 }
13870 }
13871}
13872
13873void ImGui::MarkIniSettingsDirty()
13874{
13875 ImGuiContext& g = *GImGui;
13876 if (g.SettingsDirtyTimer <= 0.0f)
13877 g.SettingsDirtyTimer = g.IO.IniSavingRate;
13878}
13879
13880void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13881{
13882 ImGuiContext& g = *GImGui;
13883 if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13884 if (g.SettingsDirtyTimer <= 0.0f)
13885 g.SettingsDirtyTimer = g.IO.IniSavingRate;
13886}
13887
13888void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13889{
13890 ImGuiContext& g = *GImGui;
13891 IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13892 g.SettingsHandlers.push_back(v: *handler);
13893}
13894
13895void ImGui::RemoveSettingsHandler(const char* type_name)
13896{
13897 ImGuiContext& g = *GImGui;
13898 if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13899 g.SettingsHandlers.erase(it: handler);
13900}
13901
13902ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13903{
13904 ImGuiContext& g = *GImGui;
13905 const ImGuiID type_hash = ImHashStr(data_p: type_name);
13906 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13907 if (handler.TypeHash == type_hash)
13908 return &handler;
13909 return NULL;
13910}
13911
13912// Clear all settings (windows, tables, docking etc.)
13913void ImGui::ClearIniSettings()
13914{
13915 ImGuiContext& g = *GImGui;
13916 g.SettingsIniData.clear();
13917 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13918 if (handler.ClearAllFn != NULL)
13919 handler.ClearAllFn(&g, &handler);
13920}
13921
13922void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13923{
13924 size_t file_data_size = 0;
13925 char* file_data = (char*)ImFileLoadToMemory(filename: ini_filename, mode: "rb", out_file_size: &file_data_size);
13926 if (!file_data)
13927 return;
13928 if (file_data_size > 0)
13929 LoadIniSettingsFromMemory(ini_data: file_data, ini_size: (size_t)file_data_size);
13930 IM_FREE(file_data);
13931}
13932
13933// Zero-tolerance, no error reporting, cheap .ini parsing
13934// 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!
13935void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13936{
13937 ImGuiContext& g = *GImGui;
13938 IM_ASSERT(g.Initialized);
13939 //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13940 //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13941
13942 // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13943 // 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..
13944 if (ini_size == 0)
13945 ini_size = strlen(s: ini_data);
13946 g.SettingsIniData.Buf.resize(new_size: (int)ini_size + 1);
13947 char* const buf = g.SettingsIniData.Buf.Data;
13948 char* const buf_end = buf + ini_size;
13949 memcpy(dest: buf, src: ini_data, n: ini_size);
13950 buf_end[0] = 0;
13951
13952 // Call pre-read handlers
13953 // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13954 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13955 if (handler.ReadInitFn != NULL)
13956 handler.ReadInitFn(&g, &handler);
13957
13958 void* entry_data = NULL;
13959 ImGuiSettingsHandler* entry_handler = NULL;
13960
13961 char* line_end = NULL;
13962 for (char* line = buf; line < buf_end; line = line_end + 1)
13963 {
13964 // Skip new lines markers, then find end of the line
13965 while (*line == '\n' || *line == '\r')
13966 line++;
13967 line_end = line;
13968 while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13969 line_end++;
13970 line_end[0] = 0;
13971 if (line[0] == ';')
13972 continue;
13973 if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13974 {
13975 // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13976 line_end[-1] = 0;
13977 const char* name_end = line_end - 1;
13978 const char* type_start = line + 1;
13979 char* type_end = (char*)(void*)ImStrchrRange(str: type_start, str_end: name_end, c: ']');
13980 const char* name_start = type_end ? ImStrchrRange(str: type_end + 1, str_end: name_end, c: '[') : NULL;
13981 if (!type_end || !name_start)
13982 continue;
13983 *type_end = 0; // Overwrite first ']'
13984 name_start++; // Skip second '['
13985 entry_handler = FindSettingsHandler(type_name: type_start);
13986 entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13987 }
13988 else if (entry_handler != NULL && entry_data != NULL)
13989 {
13990 // Let type handler parse the line
13991 entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13992 }
13993 }
13994 g.SettingsLoaded = true;
13995
13996 // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13997 memcpy(dest: buf, src: ini_data, n: ini_size);
13998
13999 // Call post-read handlers
14000 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14001 if (handler.ApplyAllFn != NULL)
14002 handler.ApplyAllFn(&g, &handler);
14003}
14004
14005void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14006{
14007 ImGuiContext& g = *GImGui;
14008 g.SettingsDirtyTimer = 0.0f;
14009 if (!ini_filename)
14010 return;
14011
14012 size_t ini_data_size = 0;
14013 const char* ini_data = SaveIniSettingsToMemory(out_ini_size: &ini_data_size);
14014 ImFileHandle f = ImFileOpen(filename: ini_filename, mode: "wt");
14015 if (!f)
14016 return;
14017 ImFileWrite(data: ini_data, sz: sizeof(char), count: ini_data_size, f);
14018 ImFileClose(f);
14019}
14020
14021// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14022const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14023{
14024 ImGuiContext& g = *GImGui;
14025 g.SettingsDirtyTimer = 0.0f;
14026 g.SettingsIniData.Buf.resize(new_size: 0);
14027 g.SettingsIniData.Buf.push_back(v: 0);
14028 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14029 handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14030 if (out_size)
14031 *out_size = (size_t)g.SettingsIniData.size();
14032 return g.SettingsIniData.c_str();
14033}
14034
14035ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14036{
14037 ImGuiContext& g = *GImGui;
14038
14039 if (g.IO.ConfigDebugIniSettings == false)
14040 {
14041 // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14042 // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14043 if (const char* p = strstr(haystack: name, needle: "###"))
14044 name = p;
14045 }
14046 const size_t name_len = strlen(s: name);
14047
14048 // Allocate chunk
14049 const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14050 ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(sz: chunk_size);
14051 IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14052 settings->ID = ImHashStr(data_p: name, data_size: name_len);
14053 memcpy(dest: settings->GetName(), src: name, n: name_len + 1); // Store with zero terminator
14054
14055 return settings;
14056}
14057
14058// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14059// This is called once per window .ini entry + once per newly instantiated window.
14060ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14061{
14062 ImGuiContext& g = *GImGui;
14063 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
14064 if (settings->ID == id && !settings->WantDelete)
14065 return settings;
14066 return NULL;
14067}
14068
14069// This is faster if you are holding on a Window already as we don't need to perform a search.
14070ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14071{
14072 ImGuiContext& g = *GImGui;
14073 if (window->SettingsOffset != -1)
14074 return g.SettingsWindows.ptr_from_offset(off: window->SettingsOffset);
14075 return FindWindowSettingsByID(id: window->ID);
14076}
14077
14078// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14079void ImGui::ClearWindowSettings(const char* name)
14080{
14081 //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14082 ImGuiWindow* window = FindWindowByName(name);
14083 if (window != NULL)
14084 {
14085 window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14086 InitOrLoadWindowSettings(window, NULL);
14087 }
14088 if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(id: ImHashStr(data_p: name)))
14089 settings->WantDelete = true;
14090}
14091
14092static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14093{
14094 ImGuiContext& g = *ctx;
14095 for (ImGuiWindow* window : g.Windows)
14096 window->SettingsOffset = -1;
14097 g.SettingsWindows.clear();
14098}
14099
14100static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14101{
14102 ImGuiID id = ImHashStr(data_p: name);
14103 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14104 if (settings)
14105 *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14106 else
14107 settings = ImGui::CreateNewWindowSettings(name);
14108 settings->ID = id;
14109 settings->WantApply = true;
14110 return (void*)settings;
14111}
14112
14113static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14114{
14115 ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14116 int x, y;
14117 int i;
14118 if (sscanf(s: line, format: "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
14119 else if (sscanf(s: line, format: "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
14120 else if (sscanf(s: line, format: "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
14121 else if (sscanf(s: line, format: "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); }
14122}
14123
14124// Apply to existing windows (if any)
14125static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14126{
14127 ImGuiContext& g = *ctx;
14128 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
14129 if (settings->WantApply)
14130 {
14131 if (ImGuiWindow* window = ImGui::FindWindowByID(id: settings->ID))
14132 ApplyWindowSettings(window, settings);
14133 settings->WantApply = false;
14134 }
14135}
14136
14137static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14138{
14139 // Gather data from windows that were active during this session
14140 // (if a window wasn't opened in this session we preserve its settings)
14141 ImGuiContext& g = *ctx;
14142 for (ImGuiWindow* window : g.Windows)
14143 {
14144 if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14145 continue;
14146
14147 ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14148 if (!settings)
14149 {
14150 settings = ImGui::CreateNewWindowSettings(name: window->Name);
14151 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
14152 }
14153 IM_ASSERT(settings->ID == window->ID);
14154 settings->Pos = ImVec2ih(window->Pos);
14155 settings->Size = ImVec2ih(window->SizeFull);
14156 settings->IsChild = (window->Flags & ImGuiWindowFlags_ChildWindow) != 0;
14157 settings->Collapsed = window->Collapsed;
14158 settings->WantDelete = false;
14159 }
14160
14161 // Write to text buffer
14162 buf->reserve(capacity: buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14163 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
14164 {
14165 if (settings->WantDelete)
14166 continue;
14167 const char* settings_name = settings->GetName();
14168 buf->appendf(fmt: "[%s][%s]\n", handler->TypeName, settings_name);
14169 if (settings->IsChild)
14170 {
14171 buf->appendf(fmt: "IsChild=1\n");
14172 buf->appendf(fmt: "Size=%d,%d\n", settings->Size.x, settings->Size.y);
14173 }
14174 else
14175 {
14176 buf->appendf(fmt: "Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14177 buf->appendf(fmt: "Size=%d,%d\n", settings->Size.x, settings->Size.y);
14178 if (settings->Collapsed)
14179 buf->appendf(fmt: "Collapsed=1\n");
14180 }
14181 buf->append(str: "\n");
14182 }
14183}
14184
14185
14186//-----------------------------------------------------------------------------
14187// [SECTION] LOCALIZATION
14188//-----------------------------------------------------------------------------
14189
14190void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14191{
14192 ImGuiContext& g = *GImGui;
14193 for (int n = 0; n < count; n++)
14194 g.LocalizationTable[entries[n].Key] = entries[n].Text;
14195}
14196
14197
14198//-----------------------------------------------------------------------------
14199// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14200//-----------------------------------------------------------------------------
14201// - GetMainViewport()
14202// - SetWindowViewport() [Internal]
14203// - UpdateViewportsNewFrame() [Internal]
14204// (this section is more complete in the 'docking' branch)
14205//-----------------------------------------------------------------------------
14206
14207ImGuiViewport* ImGui::GetMainViewport()
14208{
14209 ImGuiContext& g = *GImGui;
14210 return g.Viewports[0];
14211}
14212
14213void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14214{
14215 window->Viewport = viewport;
14216}
14217
14218// Update viewports and monitor infos
14219static void ImGui::UpdateViewportsNewFrame()
14220{
14221 ImGuiContext& g = *GImGui;
14222 IM_ASSERT(g.Viewports.Size == 1);
14223
14224 // Update main viewport with current platform position.
14225 // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14226 ImGuiViewportP* main_viewport = g.Viewports[0];
14227 main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
14228 main_viewport->Pos = ImVec2(0.0f, 0.0f);
14229 main_viewport->Size = g.IO.DisplaySize;
14230
14231 for (ImGuiViewportP* viewport : g.Viewports)
14232 {
14233 // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.
14234 viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14235 viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14236 viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14237 viewport->UpdateWorkRect();
14238 }
14239}
14240
14241//-----------------------------------------------------------------------------
14242// [SECTION] DOCKING
14243//-----------------------------------------------------------------------------
14244
14245// (this section is filled in the 'docking' branch)
14246
14247
14248//-----------------------------------------------------------------------------
14249// [SECTION] PLATFORM DEPENDENT HELPERS
14250//-----------------------------------------------------------------------------
14251// - Default clipboard handlers
14252// - Default shell function handlers
14253// - Default IME handlers
14254//-----------------------------------------------------------------------------
14255
14256#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
14257
14258#ifdef _MSC_VER
14259#pragma comment(lib, "user32")
14260#pragma comment(lib, "kernel32")
14261#endif
14262
14263// Win32 clipboard implementation
14264// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
14265static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
14266{
14267 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
14268 g.ClipboardHandlerData.clear();
14269 if (!::OpenClipboard(NULL))
14270 return NULL;
14271 HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
14272 if (wbuf_handle == NULL)
14273 {
14274 ::CloseClipboard();
14275 return NULL;
14276 }
14277 if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
14278 {
14279 int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
14280 g.ClipboardHandlerData.resize(buf_len);
14281 ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
14282 }
14283 ::GlobalUnlock(wbuf_handle);
14284 ::CloseClipboard();
14285 return g.ClipboardHandlerData.Data;
14286}
14287
14288static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
14289{
14290 if (!::OpenClipboard(NULL))
14291 return;
14292 const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
14293 HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
14294 if (wbuf_handle == NULL)
14295 {
14296 ::CloseClipboard();
14297 return;
14298 }
14299 WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
14300 ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
14301 ::GlobalUnlock(wbuf_handle);
14302 ::EmptyClipboard();
14303 if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
14304 ::GlobalFree(wbuf_handle);
14305 ::CloseClipboard();
14306}
14307
14308#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
14309
14310#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
14311static PasteboardRef main_clipboard = 0;
14312
14313// OSX clipboard implementation
14314// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
14315static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
14316{
14317 if (!main_clipboard)
14318 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
14319 PasteboardClear(main_clipboard);
14320 CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
14321 if (cf_data)
14322 {
14323 PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
14324 CFRelease(cf_data);
14325 }
14326}
14327
14328static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
14329{
14330 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
14331 if (!main_clipboard)
14332 PasteboardCreate(kPasteboardClipboard, &main_clipboard);
14333 PasteboardSynchronize(main_clipboard);
14334
14335 ItemCount item_count = 0;
14336 PasteboardGetItemCount(main_clipboard, &item_count);
14337 for (ItemCount i = 0; i < item_count; i++)
14338 {
14339 PasteboardItemID item_id = 0;
14340 PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
14341 CFArrayRef flavor_type_array = 0;
14342 PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
14343 for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
14344 {
14345 CFDataRef cf_data;
14346 if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
14347 {
14348 g.ClipboardHandlerData.clear();
14349 int length = (int)CFDataGetLength(cf_data);
14350 g.ClipboardHandlerData.resize(length + 1);
14351 CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
14352 g.ClipboardHandlerData[length] = 0;
14353 CFRelease(cf_data);
14354 return g.ClipboardHandlerData.Data;
14355 }
14356 }
14357 }
14358 return NULL;
14359}
14360
14361#else
14362
14363// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
14364static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
14365{
14366 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
14367 return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
14368}
14369
14370static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
14371{
14372 ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
14373 g.ClipboardHandlerData.clear();
14374 const char* text_end = text + strlen(s: text);
14375 g.ClipboardHandlerData.resize(new_size: (int)(text_end - text) + 1);
14376 memcpy(dest: &g.ClipboardHandlerData[0], src: text, n: (size_t)(text_end - text));
14377 g.ClipboardHandlerData[(int)(text_end - text)] = 0;
14378}
14379
14380#endif // Default clipboard handlers
14381
14382//-----------------------------------------------------------------------------
14383
14384#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14385#if defined(__APPLE__) && TARGET_OS_IPHONE
14386#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14387#endif
14388
14389#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
14390#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14391#endif
14392#endif
14393
14394#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
14395#ifdef _WIN32
14396#include <shellapi.h> // ShellExecuteA()
14397#ifdef _MSC_VER
14398#pragma comment(lib, "shell32")
14399#endif
14400static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
14401{
14402 return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
14403}
14404#else
14405#include <sys/wait.h>
14406#include <unistd.h>
14407static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
14408{
14409#if defined(__APPLE__)
14410 const char* args[] { "open", "--", path, NULL };
14411#else
14412 const char* args[] { "xdg-open", path, NULL };
14413#endif
14414 pid_t pid = fork();
14415 if (pid < 0)
14416 return false;
14417 if (!pid)
14418 {
14419 execvp(file: args[0], argv: const_cast<char **>(args));
14420 exit(status: -1);
14421 }
14422 else
14423 {
14424 int status;
14425 waitpid(pid: pid, stat_loc: &status, options: 0);
14426 return WEXITSTATUS(status) == 0;
14427 }
14428}
14429#endif
14430#else
14431static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
14432#endif // Default shell handlers
14433
14434//-----------------------------------------------------------------------------
14435
14436// Win32 API IME support (for Asian languages, etc.)
14437#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
14438
14439#include <imm.h>
14440#ifdef _MSC_VER
14441#pragma comment(lib, "imm32")
14442#endif
14443
14444static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
14445{
14446 // Notify OS Input Method Editor of text input position
14447 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
14448 if (hwnd == 0)
14449 return;
14450
14451 //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
14452 if (HIMC himc = ::ImmGetContext(hwnd))
14453 {
14454 COMPOSITIONFORM composition_form = {};
14455 composition_form.ptCurrentPos.x = (LONG)data->InputPos.x;
14456 composition_form.ptCurrentPos.y = (LONG)data->InputPos.y;
14457 composition_form.dwStyle = CFS_FORCE_POSITION;
14458 ::ImmSetCompositionWindow(himc, &composition_form);
14459 CANDIDATEFORM candidate_form = {};
14460 candidate_form.dwStyle = CFS_CANDIDATEPOS;
14461 candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x;
14462 candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y;
14463 ::ImmSetCandidateWindow(himc, &candidate_form);
14464 ::ImmReleaseContext(hwnd, himc);
14465 }
14466}
14467
14468#else
14469
14470static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
14471
14472#endif // Default IME handlers
14473
14474//-----------------------------------------------------------------------------
14475// [SECTION] METRICS/DEBUGGER WINDOW
14476//-----------------------------------------------------------------------------
14477// - DebugRenderViewportThumbnail() [Internal]
14478// - RenderViewportsThumbnails() [Internal]
14479// - DebugTextEncoding()
14480// - MetricsHelpMarker() [Internal]
14481// - ShowFontAtlas() [Internal]
14482// - ShowMetricsWindow()
14483// - DebugNodeColumns() [Internal]
14484// - DebugNodeDrawList() [Internal]
14485// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
14486// - DebugNodeFont() [Internal]
14487// - DebugNodeFontGlyph() [Internal]
14488// - DebugNodeStorage() [Internal]
14489// - DebugNodeTabBar() [Internal]
14490// - DebugNodeViewport() [Internal]
14491// - DebugNodeWindow() [Internal]
14492// - DebugNodeWindowSettings() [Internal]
14493// - DebugNodeWindowsList() [Internal]
14494// - DebugNodeWindowsListByBeginStackParent() [Internal]
14495//-----------------------------------------------------------------------------
14496
14497#ifndef IMGUI_DISABLE_DEBUG_TOOLS
14498
14499void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
14500{
14501 ImGuiContext& g = *GImGui;
14502 ImGuiWindow* window = g.CurrentWindow;
14503
14504 ImVec2 scale = bb.GetSize() / viewport->Size;
14505 ImVec2 off = bb.Min - viewport->Pos * scale;
14506 float alpha_mul = 1.0f;
14507 window->DrawList->AddRectFilled(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul: alpha_mul * 0.40f));
14508 for (ImGuiWindow* thumb_window : g.Windows)
14509 {
14510 if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
14511 continue;
14512
14513 ImRect thumb_r = thumb_window->Rect();
14514 ImRect title_r = thumb_window->TitleBarRect();
14515 thumb_r = ImRect(ImTrunc(v: off + thumb_r.Min * scale), ImTrunc(v: off + thumb_r.Max * scale));
14516 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
14517 thumb_r.ClipWithFull(r: bb);
14518 title_r.ClipWithFull(r: bb);
14519 const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
14520 window->DrawList->AddRectFilled(p_min: thumb_r.Min, p_max: thumb_r.Max, col: GetColorU32(idx: ImGuiCol_WindowBg, alpha_mul));
14521 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));
14522 window->DrawList->AddRect(p_min: thumb_r.Min, p_max: thumb_r.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul));
14523 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));
14524 }
14525 draw_list->AddRect(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_Border, alpha_mul));
14526 if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
14527 window->DrawList->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
14528}
14529
14530static void RenderViewportsThumbnails()
14531{
14532 ImGuiContext& g = *GImGui;
14533 ImGuiWindow* window = g.CurrentWindow;
14534
14535 float SCALE = 1.0f / 8.0f;
14536 ImRect bb_full(g.Viewports[0]->Pos, g.Viewports[0]->Pos + g.Viewports[0]->Size);
14537 ImVec2 p = window->DC.CursorPos;
14538 ImVec2 off = p - bb_full.Min * SCALE;
14539
14540 // Draw viewports
14541 for (ImGuiViewportP* viewport : g.Viewports)
14542 {
14543 ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
14544 ImGui::DebugRenderViewportThumbnail(draw_list: window->DrawList, viewport, bb: viewport_draw_bb);
14545 }
14546 ImGui::Dummy(size: bb_full.GetSize() * SCALE);
14547}
14548
14549// Draw an arbitrary US keyboard layout to visualize translated keys
14550void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
14551{
14552 const float scale = ImGui::GetFontSize() / 13.0f;
14553 const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
14554 const float key_rounding = 3.0f * scale;
14555 const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
14556 const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
14557 const float key_face_rounding = 2.0f * scale;
14558 const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
14559 const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
14560 const float key_row_offset = 9.0f * scale;
14561
14562 ImVec2 board_min = GetCursorScreenPos();
14563 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);
14564 ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
14565
14566 struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
14567 const KeyLayoutData keys_to_display[] =
14568 {
14569 { .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 },
14570 { .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 },
14571 { .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 }
14572 };
14573
14574 // Elements rendered manually via ImDrawList API are not clipped automatically.
14575 // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
14576 Dummy(size: board_max - board_min);
14577 if (!IsItemVisible())
14578 return;
14579 draw_list->PushClipRect(clip_rect_min: board_min, clip_rect_max: board_max, intersect_with_current_clip_rect: true);
14580 for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
14581 {
14582 const KeyLayoutData* key_data = &keys_to_display[n];
14583 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);
14584 ImVec2 key_max = key_min + key_size;
14585 draw_list->AddRectFilled(p_min: key_min, p_max: key_max, IM_COL32(204, 204, 204, 255), rounding: key_rounding);
14586 draw_list->AddRect(p_min: key_min, p_max: key_max, IM_COL32(24, 24, 24, 255), rounding: key_rounding);
14587 ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
14588 ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
14589 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);
14590 draw_list->AddRectFilled(p_min: face_min, p_max: face_max, IM_COL32(252, 252, 252, 255), rounding: key_face_rounding);
14591 ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
14592 draw_list->AddText(pos: label_min, IM_COL32(64, 64, 64, 255), text_begin: key_data->Label);
14593 if (IsKeyDown(key: key_data->Key))
14594 draw_list->AddRectFilled(p_min: key_min, p_max: key_max, IM_COL32(255, 0, 0, 128), rounding: key_rounding);
14595 }
14596 draw_list->PopClipRect();
14597}
14598
14599// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
14600void ImGui::DebugTextEncoding(const char* str)
14601{
14602 Text(fmt: "Text: \"%s\"", str);
14603 if (!BeginTable(str_id: "##DebugTextEncoding", columns: 4, flags: ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
14604 return;
14605 TableSetupColumn(label: "Offset");
14606 TableSetupColumn(label: "UTF-8");
14607 TableSetupColumn(label: "Glyph");
14608 TableSetupColumn(label: "Codepoint");
14609 TableHeadersRow();
14610 for (const char* p = str; *p != 0; )
14611 {
14612 unsigned int c;
14613 const int c_utf8_len = ImTextCharFromUtf8(out_char: &c, in_text: p, NULL);
14614 TableNextColumn();
14615 Text(fmt: "%d", (int)(p - str));
14616 TableNextColumn();
14617 for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
14618 {
14619 if (byte_index > 0)
14620 SameLine();
14621 Text(fmt: "0x%02X", (int)(unsigned char)p[byte_index]);
14622 }
14623 TableNextColumn();
14624 if (GetFont()->FindGlyphNoFallback(c: (ImWchar)c))
14625 TextUnformatted(text: p, text_end: p + c_utf8_len);
14626 else
14627 TextUnformatted(text: (c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
14628 TableNextColumn();
14629 Text(fmt: "U+%04X", (int)c);
14630 p += c_utf8_len;
14631 }
14632 EndTable();
14633}
14634
14635static void DebugFlashStyleColorStop()
14636{
14637 ImGuiContext& g = *GImGui;
14638 if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
14639 g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
14640 g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
14641}
14642
14643// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
14644void ImGui::DebugFlashStyleColor(ImGuiCol idx)
14645{
14646 ImGuiContext& g = *GImGui;
14647 DebugFlashStyleColorStop();
14648 g.DebugFlashStyleColorTime = 0.5f;
14649 g.DebugFlashStyleColorIdx = idx;
14650 g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
14651}
14652
14653void ImGui::UpdateDebugToolFlashStyleColor()
14654{
14655 ImGuiContext& g = *GImGui;
14656 if (g.DebugFlashStyleColorTime <= 0.0f)
14657 return;
14658 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);
14659 g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
14660 if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
14661 DebugFlashStyleColorStop();
14662}
14663
14664// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
14665static void MetricsHelpMarker(const char* desc)
14666{
14667 ImGui::TextDisabled(fmt: "(?)");
14668 if (ImGui::BeginItemTooltip())
14669 {
14670 ImGui::PushTextWrapPos(wrap_pos_x: ImGui::GetFontSize() * 35.0f);
14671 ImGui::TextUnformatted(text: desc);
14672 ImGui::PopTextWrapPos();
14673 ImGui::EndTooltip();
14674 }
14675}
14676
14677// [DEBUG] List fonts in a font atlas and display its texture
14678void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
14679{
14680 for (ImFont* font : atlas->Fonts)
14681 {
14682 PushID(ptr_id: font);
14683 DebugNodeFont(font);
14684 PopID();
14685 }
14686 if (TreeNode(str_id: "Font Atlas", fmt: "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
14687 {
14688 ImGuiContext& g = *GImGui;
14689 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
14690 Checkbox(label: "Tint with Text Color", v: &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
14691 ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(idx: ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
14692 ImVec4 border_col = GetStyleColorVec4(idx: ImGuiCol_Border);
14693 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);
14694 TreePop();
14695 }
14696}
14697
14698void ImGui::ShowMetricsWindow(bool* p_open)
14699{
14700 ImGuiContext& g = *GImGui;
14701 ImGuiIO& io = g.IO;
14702 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
14703 if (cfg->ShowDebugLog)
14704 ShowDebugLogWindow(p_open: &cfg->ShowDebugLog);
14705 if (cfg->ShowIDStackTool)
14706 ShowIDStackToolWindow(p_open: &cfg->ShowIDStackTool);
14707
14708 if (!Begin(name: "Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
14709 {
14710 End();
14711 return;
14712 }
14713
14714 // [DEBUG] Clear debug breaks hooks after exactly one cycle.
14715 DebugBreakClearData();
14716
14717 // Basic info
14718 Text(fmt: "Dear ImGui %s", GetVersion());
14719 if (g.ContextName[0] != 0)
14720 {
14721 SameLine();
14722 Text(fmt: "(Context Name: \"%s\")", g.ContextName);
14723 }
14724 Text(fmt: "Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
14725 Text(fmt: "%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
14726 Text(fmt: "%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
14727 //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
14728
14729 Separator();
14730
14731 // Debugging enums
14732 enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
14733 const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
14734 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
14735 const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
14736 if (cfg->ShowWindowsRectsType < 0)
14737 cfg->ShowWindowsRectsType = WRT_WorkRect;
14738 if (cfg->ShowTablesRectsType < 0)
14739 cfg->ShowTablesRectsType = TRT_WorkRect;
14740
14741 struct Funcs
14742 {
14743 static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
14744 {
14745 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent); // Always using last submitted instance
14746 if (rect_type == TRT_OuterRect) { return table->OuterRect; }
14747 else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
14748 else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
14749 else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
14750 else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
14751 else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
14752 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); }
14753 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); }
14754 else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
14755 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
14756 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); }
14757 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); }
14758 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); }
14759 IM_ASSERT(0);
14760 return ImRect();
14761 }
14762
14763 static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
14764 {
14765 if (rect_type == WRT_OuterRect) { return window->Rect(); }
14766 else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
14767 else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
14768 else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
14769 else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
14770 else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
14771 else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
14772 else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
14773 IM_ASSERT(0);
14774 return ImRect();
14775 }
14776 };
14777
14778 // Tools
14779 if (TreeNode(label: "Tools"))
14780 {
14781 // Debug Break features
14782 // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
14783 SeparatorTextEx(id: 0, label: "Debug breaks", NULL, extra_width: CalcTextSize(text: "(?)").x + g.Style.SeparatorTextPadding.x);
14784 SameLine();
14785 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.");
14786 if (Checkbox(label: "Show Item Picker", v: &g.DebugItemPickerActive) && g.DebugItemPickerActive)
14787 DebugStartItemPicker();
14788 Checkbox(label: "Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", v: &g.IO.ConfigDebugIsDebuggerPresent);
14789
14790 SeparatorText(label: "Visualize");
14791
14792 Checkbox(label: "Show Debug Log", v: &cfg->ShowDebugLog);
14793 SameLine();
14794 MetricsHelpMarker(desc: "You can also call ImGui::ShowDebugLogWindow() from your code.");
14795
14796 Checkbox(label: "Show ID Stack Tool", v: &cfg->ShowIDStackTool);
14797 SameLine();
14798 MetricsHelpMarker(desc: "You can also call ImGui::ShowIDStackToolWindow() from your code.");
14799
14800 Checkbox(label: "Show windows begin order", v: &cfg->ShowWindowsBeginOrder);
14801 Checkbox(label: "Show windows rectangles", v: &cfg->ShowWindowsRects);
14802 SameLine();
14803 SetNextItemWidth(GetFontSize() * 12);
14804 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);
14805 if (cfg->ShowWindowsRects && g.NavWindow != NULL)
14806 {
14807 BulletText(fmt: "'%s':", g.NavWindow->Name);
14808 Indent();
14809 for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
14810 {
14811 ImRect r = Funcs::GetWindowRect(window: g.NavWindow, rect_type: rect_n);
14812 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]);
14813 }
14814 Unindent();
14815 }
14816
14817 Checkbox(label: "Show tables rectangles", v: &cfg->ShowTablesRects);
14818 SameLine();
14819 SetNextItemWidth(GetFontSize() * 12);
14820 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);
14821 if (cfg->ShowTablesRects && g.NavWindow != NULL)
14822 {
14823 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
14824 {
14825 ImGuiTable* table = g.Tables.TryGetMapData(n: table_n);
14826 if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
14827 continue;
14828
14829 BulletText(fmt: "Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
14830 if (IsItemHovered())
14831 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);
14832 Indent();
14833 char buf[128];
14834 for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
14835 {
14836 if (rect_n >= TRT_ColumnsRect)
14837 {
14838 if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
14839 continue;
14840 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
14841 {
14842 ImRect r = Funcs::GetTableRect(table, rect_type: rect_n, n: column_n);
14843 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]);
14844 Selectable(label: buf);
14845 if (IsItemHovered())
14846 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);
14847 }
14848 }
14849 else
14850 {
14851 ImRect r = Funcs::GetTableRect(table, rect_type: rect_n, n: -1);
14852 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]);
14853 Selectable(label: buf);
14854 if (IsItemHovered())
14855 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);
14856 }
14857 }
14858 Unindent();
14859 }
14860 }
14861 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
14862
14863 SeparatorText(label: "Validate");
14864
14865 Checkbox(label: "Debug Begin/BeginChild return value", v: &io.ConfigDebugBeginReturnValueLoop);
14866 SameLine();
14867 MetricsHelpMarker(desc: "Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
14868
14869 Checkbox(label: "UTF-8 Encoding viewer", v: &cfg->ShowTextEncodingViewer);
14870 SameLine();
14871 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.");
14872 if (cfg->ShowTextEncodingViewer)
14873 {
14874 static char buf[64] = "";
14875 SetNextItemWidth(-FLT_MIN);
14876 InputText(label: "##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
14877 if (buf[0] != 0)
14878 DebugTextEncoding(str: buf);
14879 }
14880
14881 TreePop();
14882 }
14883
14884 // Windows
14885 if (TreeNode(str_id: "Windows", fmt: "Windows (%d)", g.Windows.Size))
14886 {
14887 //SetNextItemOpen(true, ImGuiCond_Once);
14888 DebugNodeWindowsList(windows: &g.Windows, label: "By display order");
14889 DebugNodeWindowsList(windows: &g.WindowsFocusOrder, label: "By focus order (root windows)");
14890 if (TreeNode(label: "By submission order (begin stack)"))
14891 {
14892 // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
14893 ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
14894 temp_buffer.resize(new_size: 0);
14895 for (ImGuiWindow* window : g.Windows)
14896 if (window->LastFrameActive + 1 >= g.FrameCount)
14897 temp_buffer.push_back(v: window);
14898 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); } };
14899 ImQsort(base: temp_buffer.Data, count: (size_t)temp_buffer.Size, size_of_element: sizeof(ImGuiWindow*), compare_func: Func::WindowComparerByBeginOrder);
14900 DebugNodeWindowsListByBeginStackParent(windows: temp_buffer.Data, windows_size: temp_buffer.Size, NULL);
14901 TreePop();
14902 }
14903
14904 TreePop();
14905 }
14906
14907 // DrawLists
14908 int drawlist_count = 0;
14909 for (ImGuiViewportP* viewport : g.Viewports)
14910 drawlist_count += viewport->DrawDataP.CmdLists.Size;
14911 if (TreeNode(str_id: "DrawLists", fmt: "DrawLists (%d)", drawlist_count))
14912 {
14913 Checkbox(label: "Show ImDrawCmd mesh when hovering", v: &cfg->ShowDrawCmdMesh);
14914 Checkbox(label: "Show ImDrawCmd bounding boxes when hovering", v: &cfg->ShowDrawCmdBoundingBoxes);
14915 for (ImGuiViewportP* viewport : g.Viewports)
14916 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
14917 DebugNodeDrawList(NULL, viewport, draw_list, label: "DrawList");
14918 TreePop();
14919 }
14920
14921 // Viewports
14922 if (TreeNode(str_id: "Viewports", fmt: "Viewports (%d)", g.Viewports.Size))
14923 {
14924 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
14925 if (TreeNode(label: "Windows Minimap"))
14926 {
14927 RenderViewportsThumbnails();
14928 TreePop();
14929 }
14930 cfg->HighlightViewportID = 0;
14931
14932 for (ImGuiViewportP* viewport : g.Viewports)
14933 DebugNodeViewport(viewport);
14934 TreePop();
14935 }
14936
14937 // Details for Popups
14938 if (TreeNode(str_id: "Popups", fmt: "Popups (%d)", g.OpenPopupStack.Size))
14939 {
14940 for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
14941 {
14942 // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
14943 ImGuiWindow* window = popup_data.Window;
14944 BulletText(fmt: "PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
14945 popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
14946 popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
14947 }
14948 TreePop();
14949 }
14950
14951 // Details for TabBars
14952 if (TreeNode(str_id: "TabBars", fmt: "Tab Bars (%d)", g.TabBars.GetAliveCount()))
14953 {
14954 for (int n = 0; n < g.TabBars.GetMapSize(); n++)
14955 if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
14956 {
14957 PushID(ptr_id: tab_bar);
14958 DebugNodeTabBar(tab_bar, label: "TabBar");
14959 PopID();
14960 }
14961 TreePop();
14962 }
14963
14964 // Details for Tables
14965 if (TreeNode(str_id: "Tables", fmt: "Tables (%d)", g.Tables.GetAliveCount()))
14966 {
14967 for (int n = 0; n < g.Tables.GetMapSize(); n++)
14968 if (ImGuiTable* table = g.Tables.TryGetMapData(n))
14969 DebugNodeTable(table);
14970 TreePop();
14971 }
14972
14973 // Details for Fonts
14974 ImFontAtlas* atlas = g.IO.Fonts;
14975 if (TreeNode(str_id: "Fonts", fmt: "Fonts (%d)", atlas->Fonts.Size))
14976 {
14977 ShowFontAtlas(atlas);
14978 TreePop();
14979 }
14980
14981 // Details for InputText
14982 if (TreeNode(label: "InputText"))
14983 {
14984 DebugNodeInputTextState(state: &g.InputTextState);
14985 TreePop();
14986 }
14987
14988 // Details for TypingSelect
14989 if (TreeNode(str_id: "TypingSelect", fmt: "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
14990 {
14991 DebugNodeTypingSelectState(state: &g.TypingSelectState);
14992 TreePop();
14993 }
14994
14995 // Details for MultiSelect
14996 if (TreeNode(str_id: "MultiSelect", fmt: "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
14997 {
14998 ImGuiBoxSelectState* bs = &g.BoxSelectState;
14999 BulletText(fmt: "BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
15000 for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
15001 if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
15002 DebugNodeMultiSelectState(state);
15003 TreePop();
15004 }
15005
15006 // Details for Docking
15007#ifdef IMGUI_HAS_DOCK
15008 if (TreeNode("Docking"))
15009 {
15010 TreePop();
15011 }
15012#endif // #ifdef IMGUI_HAS_DOCK
15013
15014 // Settings
15015 if (TreeNode(label: "Settings"))
15016 {
15017 if (SmallButton(label: "Clear"))
15018 ClearIniSettings();
15019 SameLine();
15020 if (SmallButton(label: "Save to memory"))
15021 SaveIniSettingsToMemory();
15022 SameLine();
15023 if (SmallButton(label: "Save to disk"))
15024 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
15025 SameLine();
15026 if (g.IO.IniFilename)
15027 Text(fmt: "\"%s\"", g.IO.IniFilename);
15028 else
15029 TextUnformatted(text: "<NULL>");
15030 Checkbox(label: "io.ConfigDebugIniSettings", v: &io.ConfigDebugIniSettings);
15031 Text(fmt: "SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
15032 if (TreeNode(str_id: "SettingsHandlers", fmt: "Settings handlers: (%d)", g.SettingsHandlers.Size))
15033 {
15034 for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
15035 BulletText(fmt: "\"%s\"", handler.TypeName);
15036 TreePop();
15037 }
15038 if (TreeNode(str_id: "SettingsWindows", fmt: "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
15039 {
15040 for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(p: settings))
15041 DebugNodeWindowSettings(settings);
15042 TreePop();
15043 }
15044
15045 if (TreeNode(str_id: "SettingsTables", fmt: "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
15046 {
15047 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(p: settings))
15048 DebugNodeTableSettings(settings);
15049 TreePop();
15050 }
15051
15052#ifdef IMGUI_HAS_DOCK
15053#endif // #ifdef IMGUI_HAS_DOCK
15054
15055 if (TreeNode(str_id: "SettingsIniData", fmt: "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
15056 {
15057 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);
15058 TreePop();
15059 }
15060 TreePop();
15061 }
15062
15063 // Settings
15064 if (TreeNode(label: "Memory allocations"))
15065 {
15066 ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
15067 Text(fmt: "%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
15068 if (SmallButton(label: "GC now")) { g.GcCompactAll = true; }
15069 Text(fmt: "Recent frames with allocations:");
15070 int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
15071 for (int n = buf_size - 1; n >= 0; n--)
15072 {
15073 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
15074 BulletText(fmt: "Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
15075 if (n == 0)
15076 {
15077 SameLine();
15078 Text(fmt: "<- %d frames ago", g.FrameCount - entry->FrameCount);
15079 }
15080 }
15081 TreePop();
15082 }
15083
15084 if (TreeNode(label: "Inputs"))
15085 {
15086 Text(fmt: "KEYBOARD/GAMEPAD/MOUSE KEYS");
15087 {
15088 // 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.
15089 // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
15090 Indent();
15091#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
15092 struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
15093#else
15094 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
15095 //Text("Legacy raw:"); for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
15096#endif
15097 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); }
15098 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); }
15099 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); }
15100 Text(fmt: "Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
15101 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.
15102 DebugRenderKeyboardPreview(draw_list: GetWindowDrawList());
15103 Unindent();
15104 }
15105
15106 Text(fmt: "MOUSE STATE");
15107 {
15108 Indent();
15109 if (IsMousePosValid())
15110 Text(fmt: "Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
15111 else
15112 Text(fmt: "Mouse pos: <INVALID>");
15113 Text(fmt: "Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
15114 int count = IM_ARRAYSIZE(io.MouseDown);
15115 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]); }
15116 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]); }
15117 Text(fmt: "Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(button: i)) { SameLine(); Text(fmt: "b%d", i); }
15118 Text(fmt: "Mouse wheel: %.1f", io.MouseWheel);
15119 Text(fmt: "MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
15120 Text(fmt: "Mouse source: %s", GetMouseSourceName(source: io.MouseSource));
15121 Text(fmt: "Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
15122 Unindent();
15123 }
15124
15125 Text(fmt: "MOUSE WHEELING");
15126 {
15127 Indent();
15128 Text(fmt: "WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
15129 Text(fmt: "WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
15130 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>");
15131 Unindent();
15132 }
15133
15134 Text(fmt: "KEY OWNERS");
15135 {
15136 Indent();
15137 if (BeginChild(str_id: "##owners", size_arg: ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), child_flags: ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, window_flags: ImGuiWindowFlags_NoSavedSettings))
15138 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
15139 {
15140 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
15141 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
15142 continue;
15143 Text(fmt: "%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
15144 owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
15145 DebugLocateItemOnHover(target_id: owner_data->OwnerCurr);
15146 }
15147 EndChild();
15148 Unindent();
15149 }
15150 Text(fmt: "SHORTCUT ROUTING");
15151 SameLine();
15152 MetricsHelpMarker(desc: "Declared shortcut routes automatically set key owner when mods matches.");
15153 {
15154 Indent();
15155 if (BeginChild(str_id: "##routes", size_arg: ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), child_flags: ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, window_flags: ImGuiWindowFlags_NoSavedSettings))
15156 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
15157 {
15158 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
15159 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
15160 {
15161 ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
15162 ImGuiKeyChord key_chord = key | routing_data->Mods;
15163 Text(fmt: "%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
15164 DebugLocateItemOnHover(target_id: routing_data->RoutingCurr);
15165 if (g.IO.ConfigDebugIsDebuggerPresent)
15166 {
15167 SameLine();
15168 if (DebugBreakButton(label: "**DebugBreak**", description_of_location: "in SetShortcutRouting() for this KeyChord"))
15169 g.DebugBreakInShortcutRouting = key_chord;
15170 }
15171 idx = routing_data->NextEntryIndex;
15172 }
15173 }
15174 EndChild();
15175 Text(fmt: "(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
15176 Unindent();
15177 }
15178 TreePop();
15179 }
15180
15181 if (TreeNode(label: "Internal state"))
15182 {
15183 Text(fmt: "WINDOWING");
15184 Indent();
15185 Text(fmt: "HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
15186 Text(fmt: "HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
15187 Text(fmt: "HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
15188 Text(fmt: "MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
15189 Unindent();
15190
15191 Text(fmt: "ITEMS");
15192 Indent();
15193 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));
15194 DebugLocateItemOnHover(target_id: g.ActiveId);
15195 Text(fmt: "ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
15196 Text(fmt: "ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
15197 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
15198 Text(fmt: "HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
15199 Text(fmt: "DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
15200 DebugLocateItemOnHover(target_id: g.DragDropPayload.SourceId);
15201 Unindent();
15202
15203 Text(fmt: "NAV,FOCUS");
15204 Indent();
15205 Text(fmt: "NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
15206 Text(fmt: "NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
15207 DebugLocateItemOnHover(target_id: g.NavId);
15208 Text(fmt: "NavInputSource: %s", GetInputSourceName(source: g.NavInputSource));
15209 Text(fmt: "NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
15210 Text(fmt: "NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
15211 Text(fmt: "NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
15212 Text(fmt: "NavActivateFlags: %04X", g.NavActivateFlags);
15213 Text(fmt: "NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
15214 Text(fmt: "NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
15215 Text(fmt: "NavFocusRoute[] = ");
15216 for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
15217 {
15218 const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
15219 SameLine(offset_from_start_x: 0.0f, spacing_w: 0.0f);
15220 Text(fmt: "0x%08X/", focus_scope.ID);
15221 SetItemTooltip("In window \"%s\"", FindWindowByID(id: focus_scope.WindowID)->Name);
15222 }
15223 Text(fmt: "NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
15224 Unindent();
15225
15226 TreePop();
15227 }
15228
15229 // Overlay: Display windows Rectangles and Begin Order
15230 if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
15231 {
15232 for (ImGuiWindow* window : g.Windows)
15233 {
15234 if (!window->WasActive)
15235 continue;
15236 ImDrawList* draw_list = GetForegroundDrawList(window);
15237 if (cfg->ShowWindowsRects)
15238 {
15239 ImRect r = Funcs::GetWindowRect(window, rect_type: cfg->ShowWindowsRectsType);
15240 draw_list->AddRect(p_min: r.Min, p_max: r.Max, IM_COL32(255, 0, 128, 255));
15241 }
15242 if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
15243 {
15244 char buf[32];
15245 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "%d", window->BeginOrderWithinContext);
15246 float font_size = GetFontSize();
15247 draw_list->AddRectFilled(p_min: window->Pos, p_max: window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
15248 draw_list->AddText(pos: window->Pos, IM_COL32(255, 255, 255, 255), text_begin: buf);
15249 }
15250 }
15251 }
15252
15253 // Overlay: Display Tables Rectangles
15254 if (cfg->ShowTablesRects)
15255 {
15256 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
15257 {
15258 ImGuiTable* table = g.Tables.TryGetMapData(n: table_n);
15259 if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
15260 continue;
15261 ImDrawList* draw_list = GetForegroundDrawList(window: table->OuterWindow);
15262 if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
15263 {
15264 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
15265 {
15266 ImRect r = Funcs::GetTableRect(table, rect_type: cfg->ShowTablesRectsType, n: column_n);
15267 ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
15268 float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
15269 draw_list->AddRect(p_min: r.Min, p_max: r.Max, col, rounding: 0.0f, flags: 0, thickness);
15270 }
15271 }
15272 else
15273 {
15274 ImRect r = Funcs::GetTableRect(table, rect_type: cfg->ShowTablesRectsType, n: -1);
15275 draw_list->AddRect(p_min: r.Min, p_max: r.Max, IM_COL32(255, 0, 128, 255));
15276 }
15277 }
15278 }
15279
15280#ifdef IMGUI_HAS_DOCK
15281 // Overlay: Display Docking info
15282 if (show_docking_nodes && g.IO.KeyCtrl)
15283 {
15284 }
15285#endif // #ifdef IMGUI_HAS_DOCK
15286
15287 End();
15288}
15289
15290void ImGui::DebugBreakClearData()
15291{
15292 // Those fields are scattered in their respective subsystem to stay in hot-data locations
15293 ImGuiContext& g = *GImGui;
15294 g.DebugBreakInWindow = 0;
15295 g.DebugBreakInTable = 0;
15296 g.DebugBreakInShortcutRouting = ImGuiKey_None;
15297}
15298
15299void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
15300{
15301 if (!BeginItemTooltip())
15302 return;
15303 Text(fmt: "To call IM_DEBUG_BREAK() %s:", description_of_location);
15304 Separator();
15305 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.");
15306 Separator();
15307 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!");
15308 EndTooltip();
15309}
15310
15311// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
15312// In order to reduce interferences with the contents we are trying to debug into.
15313bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
15314{
15315 ImGuiWindow* window = GetCurrentWindow();
15316 if (window->SkipItems)
15317 return false;
15318
15319 ImGuiContext& g = *GImGui;
15320 const ImGuiID id = window->GetID(str: label);
15321 const ImVec2 label_size = CalcTextSize(text: label, NULL, hide_text_after_double_hash: true);
15322 ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
15323 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
15324
15325 const ImRect bb(pos, pos + size);
15326 ItemSize(size, text_baseline_y: 0.0f);
15327 if (!ItemAdd(bb, id))
15328 return false;
15329
15330 // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
15331 bool hovered = ItemHoverable(bb, id, item_flags: g.CurrentItemFlags);
15332 bool pressed = hovered && (IsKeyChordPressed(key_chord: g.DebugBreakKeyChord) || IsMouseClicked(button: 0) || g.NavActivateId == id);
15333 DebugBreakButtonTooltip(keyboard_only: false, description_of_location);
15334
15335 ImVec4 col4f = GetStyleColorVec4(idx: hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
15336 ImVec4 hsv;
15337 ColorConvertRGBtoHSV(r: col4f.x, g: col4f.y, b: col4f.z, out_h&: hsv.x, out_s&: hsv.y, out_v&: hsv.z);
15338 ColorConvertHSVtoRGB(h: hsv.x + 0.20f, s: hsv.y, v: hsv.z, out_r&: col4f.x, out_g&: col4f.y, out_b&: col4f.z);
15339
15340 RenderNavHighlight(bb, id);
15341 RenderFrame(p_min: bb.Min, p_max: bb.Max, fill_col: GetColorU32(col: col4f), border: true, rounding: g.Style.FrameRounding);
15342 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);
15343
15344 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
15345 return pressed;
15346}
15347
15348// [DEBUG] Display contents of Columns
15349void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
15350{
15351 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))
15352 return;
15353 BulletText(fmt: "Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
15354 for (ImGuiOldColumnData& column : columns->Columns)
15355 BulletText(fmt: "Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(it: &column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, offset_norm: column.OffsetNorm));
15356 TreePop();
15357}
15358
15359static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
15360{
15361 union { void* ptr; int integer; } tex_id_opaque;
15362 memcpy(dest: &tex_id_opaque, src: &tex_id, n: ImMin(lhs: sizeof(void*), rhs: sizeof(tex_id)));
15363 if (sizeof(tex_id) >= sizeof(void*))
15364 ImFormatString(buf, buf_size, fmt: "0x%p", tex_id_opaque.ptr);
15365 else
15366 ImFormatString(buf, buf_size, fmt: "0x%04X", tex_id_opaque.integer);
15367}
15368
15369// [DEBUG] Display contents of ImDrawList
15370void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
15371{
15372 ImGuiContext& g = *GImGui;
15373 IM_UNUSED(viewport); // Used in docking branch
15374 ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
15375 int cmd_count = draw_list->CmdBuffer.Size;
15376 if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
15377 cmd_count--;
15378 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);
15379 if (draw_list == GetWindowDrawList())
15380 {
15381 SameLine();
15382 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)
15383 if (node_open)
15384 TreePop();
15385 return;
15386 }
15387
15388 ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
15389 if (window && IsItemHovered() && fg_draw_list)
15390 fg_draw_list->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
15391 if (!node_open)
15392 return;
15393
15394 if (window && !window->WasActive)
15395 TextDisabled(fmt: "Warning: owning Window is inactive. This DrawList is not being rendered!");
15396
15397 for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
15398 {
15399 if (pcmd->UserCallback)
15400 {
15401 BulletText(fmt: "Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
15402 continue;
15403 }
15404
15405 char texid_desc[20];
15406 FormatTextureIDForDebugDisplay(buf: texid_desc, IM_ARRAYSIZE(texid_desc), tex_id: pcmd->TextureId);
15407 char buf[300];
15408 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
15409 pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
15410 bool pcmd_node_open = TreeNode(ptr_id: (void*)(pcmd - draw_list->CmdBuffer.begin()), fmt: "%s", buf);
15411 if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
15412 DebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list: fg_draw_list, draw_list, draw_cmd: pcmd, show_mesh: cfg->ShowDrawCmdMesh, show_aabb: cfg->ShowDrawCmdBoundingBoxes);
15413 if (!pcmd_node_open)
15414 continue;
15415
15416 // Calculate approximate coverage area (touched pixel count)
15417 // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
15418 const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
15419 const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
15420 float total_area = 0.0f;
15421 for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
15422 {
15423 ImVec2 triangle[3];
15424 for (int n = 0; n < 3; n++, idx_n++)
15425 triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
15426 total_area += ImTriangleArea(a: triangle[0], b: triangle[1], c: triangle[2]);
15427 }
15428
15429 // Display vertex information summary. Hover to get all triangles drawn in wire-frame
15430 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);
15431 Selectable(label: buf);
15432 if (IsItemHovered() && fg_draw_list)
15433 DebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list: fg_draw_list, draw_list, draw_cmd: pcmd, show_mesh: true, show_aabb: false);
15434
15435 // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
15436 ImGuiListClipper clipper;
15437 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.
15438 while (clipper.Step())
15439 for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
15440 {
15441 char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
15442 ImVec2 triangle[3];
15443 for (int n = 0; n < 3; n++, idx_i++)
15444 {
15445 const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
15446 triangle[n] = v.pos;
15447 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",
15448 (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
15449 }
15450
15451 Selectable(label: buf, selected: false);
15452 if (fg_draw_list && IsItemHovered())
15453 {
15454 ImDrawListFlags backup_flags = fg_draw_list->Flags;
15455 fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
15456 fg_draw_list->AddPolyline(points: triangle, num_points: 3, IM_COL32(255, 255, 0, 255), flags: ImDrawFlags_Closed, thickness: 1.0f);
15457 fg_draw_list->Flags = backup_flags;
15458 }
15459 }
15460 TreePop();
15461 }
15462 TreePop();
15463}
15464
15465// [DEBUG] Display mesh/aabb of a ImDrawCmd
15466void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
15467{
15468 IM_ASSERT(show_mesh || show_aabb);
15469
15470 // Draw wire-frame version of all triangles
15471 ImRect clip_rect = draw_cmd->ClipRect;
15472 ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
15473 ImDrawListFlags backup_flags = out_draw_list->Flags;
15474 out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
15475 for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
15476 {
15477 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
15478 ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
15479
15480 ImVec2 triangle[3];
15481 for (int n = 0; n < 3; n++, idx_n++)
15482 vtxs_rect.Add(p: (triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
15483 if (show_mesh)
15484 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
15485 }
15486 // Draw bounding boxes
15487 if (show_aabb)
15488 {
15489 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
15490 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
15491 }
15492 out_draw_list->Flags = backup_flags;
15493}
15494
15495// [DEBUG] Display details for a single font, called by ShowStyleEditor().
15496void ImGui::DebugNodeFont(ImFont* font)
15497{
15498 bool opened = TreeNode(ptr_id: font, fmt: "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
15499 font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
15500 SameLine();
15501 if (SmallButton(label: "Set as default"))
15502 GetIO().FontDefault = font;
15503 if (!opened)
15504 return;
15505
15506 // Display preview text
15507 PushFont(font);
15508 Text(fmt: "The quick brown fox jumps over the lazy dog");
15509 PopFont();
15510
15511 // Display details
15512 SetNextItemWidth(GetFontSize() * 8);
15513 DragFloat(label: "Font scale", v: &font->Scale, v_speed: 0.005f, v_min: 0.3f, v_max: 2.0f, format: "%.1f");
15514 SameLine(); MetricsHelpMarker(
15515 desc: "Note that the default embedded font is NOT meant to be scaled.\n\n"
15516 "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
15517 "You may oversample them to get some flexibility with scaling. "
15518 "You can also render at multiple sizes and select which one to use at runtime.\n\n"
15519 "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
15520 Text(fmt: "Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
15521 char c_str[5];
15522 Text(fmt: "Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(out_buf: c_str, c: font->FallbackChar), font->FallbackChar);
15523 Text(fmt: "Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(out_buf: c_str, c: font->EllipsisChar), font->EllipsisChar);
15524 const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
15525 Text(fmt: "Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
15526 for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
15527 if (font->ConfigData)
15528 if (const ImFontConfig* cfg = &font->ConfigData[config_i])
15529 BulletText(fmt: "Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
15530 config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
15531
15532 // Display all glyphs of the fonts in separate pages of 256 characters
15533 if (TreeNode(str_id: "Glyphs", fmt: "Glyphs (%d)", font->Glyphs.Size))
15534 {
15535 ImDrawList* draw_list = GetWindowDrawList();
15536 const ImU32 glyph_col = GetColorU32(idx: ImGuiCol_Text);
15537 const float cell_size = font->FontSize * 1;
15538 const float cell_spacing = GetStyle().ItemSpacing.y;
15539 for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
15540 {
15541 // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
15542 // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
15543 // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
15544 if (!(base & 4095) && font->IsGlyphRangeUnused(c_begin: base, c_last: base + 4095))
15545 {
15546 base += 4096 - 256;
15547 continue;
15548 }
15549
15550 int count = 0;
15551 for (unsigned int n = 0; n < 256; n++)
15552 if (font->FindGlyphNoFallback(c: (ImWchar)(base + n)))
15553 count++;
15554 if (count <= 0)
15555 continue;
15556 if (!TreeNode(ptr_id: (void*)(intptr_t)base, fmt: "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
15557 continue;
15558
15559 // Draw a 16x16 grid of glyphs
15560 ImVec2 base_pos = GetCursorScreenPos();
15561 for (unsigned int n = 0; n < 256; n++)
15562 {
15563 // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
15564 // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
15565 ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
15566 ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
15567 const ImFontGlyph* glyph = font->FindGlyphNoFallback(c: (ImWchar)(base + n));
15568 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));
15569 if (!glyph)
15570 continue;
15571 font->RenderChar(draw_list, size: cell_size, pos: cell_p1, col: glyph_col, c: (ImWchar)(base + n));
15572 if (IsMouseHoveringRect(r_min: cell_p1, r_max: cell_p2) && BeginTooltip())
15573 {
15574 DebugNodeFontGlyph(font, glyph);
15575 EndTooltip();
15576 }
15577 }
15578 Dummy(size: ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
15579 TreePop();
15580 }
15581 TreePop();
15582 }
15583 TreePop();
15584}
15585
15586void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
15587{
15588 Text(fmt: "Codepoint: U+%04X", glyph->Codepoint);
15589 Separator();
15590 Text(fmt: "Visible: %d", glyph->Visible);
15591 Text(fmt: "AdvanceX: %.1f", glyph->AdvanceX);
15592 Text(fmt: "Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
15593 Text(fmt: "UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
15594}
15595
15596// [DEBUG] Display contents of ImGuiStorage
15597void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
15598{
15599 if (!TreeNode(str_id: label, fmt: "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
15600 return;
15601 for (const ImGuiStoragePair& p : storage->Data)
15602 {
15603 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.
15604 DebugLocateItemOnHover(target_id: p.key);
15605 }
15606 TreePop();
15607}
15608
15609// [DEBUG] Display contents of ImGuiTabBar
15610void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
15611{
15612 // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
15613 char buf[256];
15614 char* p = buf;
15615 const char* buf_end = buf + IM_ARRAYSIZE(buf);
15616 const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
15617 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*");
15618 for (int tab_n = 0; tab_n < ImMin(lhs: tab_bar->Tabs.Size, rhs: 3); tab_n++)
15619 {
15620 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
15621 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
15622 }
15623 p += ImFormatString(buf: p, buf_size: buf_end - p, fmt: (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
15624 if (!is_active) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
15625 bool open = TreeNode(str_id: label, fmt: "%s", buf);
15626 if (!is_active) { PopStyleColor(); }
15627 if (is_active && IsItemHovered())
15628 {
15629 ImDrawList* draw_list = GetForegroundDrawList();
15630 draw_list->AddRect(p_min: tab_bar->BarRect.Min, p_max: tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
15631 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));
15632 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));
15633 }
15634 if (open)
15635 {
15636 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
15637 {
15638 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
15639 PushID(ptr_id: tab);
15640 if (SmallButton(label: "<")) { TabBarQueueReorder(tab_bar, tab, offset: -1); } SameLine(offset_from_start_x: 0, spacing_w: 2);
15641 if (SmallButton(label: ">")) { TabBarQueueReorder(tab_bar, tab, offset: +1); } SameLine();
15642 Text(fmt: "%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
15643 tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
15644 PopID();
15645 }
15646 TreePop();
15647 }
15648}
15649
15650void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
15651{
15652 ImGuiContext& g = *GImGui;
15653 SetNextItemOpen(is_open: true, cond: ImGuiCond_Once);
15654 bool open = TreeNode(str_id: "viewport0", fmt: "Viewport #%d", 0);
15655 if (IsItemHovered())
15656 g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
15657 if (open)
15658 {
15659 ImGuiWindowFlags flags = viewport->Flags;
15660 BulletText(fmt: "Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
15661 viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
15662 viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y);
15663 BulletText(fmt: "Flags: 0x%04X =%s%s%s", viewport->Flags,
15664 (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "",
15665 (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
15666 (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "");
15667 for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
15668 DebugNodeDrawList(NULL, viewport, draw_list, label: "DrawList");
15669 TreePop();
15670 }
15671}
15672
15673void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
15674{
15675 if (window == NULL)
15676 {
15677 BulletText(fmt: "%s: NULL", label);
15678 return;
15679 }
15680
15681 ImGuiContext& g = *GImGui;
15682 const bool is_active = window->WasActive;
15683 ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
15684 if (!is_active) { PushStyleColor(idx: ImGuiCol_Text, col: GetStyleColorVec4(idx: ImGuiCol_TextDisabled)); }
15685 const bool open = TreeNodeEx(str_id: label, flags: tree_node_flags, fmt: "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
15686 if (!is_active) { PopStyleColor(); }
15687 if (IsItemHovered() && is_active)
15688 GetForegroundDrawList(window)->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
15689 if (!open)
15690 return;
15691
15692 if (window->MemoryCompacted)
15693 TextDisabled(fmt: "Note: some memory buffers have been compacted/freed.");
15694
15695 if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton(label: "**DebugBreak**", description_of_location: "in Begin()"))
15696 g.DebugBreakInWindow = window->ID;
15697
15698 ImGuiWindowFlags flags = window->Flags;
15699 DebugNodeDrawList(window, viewport: window->Viewport, draw_list: window->DrawList, label: "DrawList");
15700 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);
15701 BulletText(fmt: "Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
15702 (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
15703 (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
15704 (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
15705 if (flags & ImGuiWindowFlags_ChildWindow)
15706 BulletText(fmt: "ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
15707 (window->ChildFlags & ImGuiChildFlags_Border) ? "Border " : "",
15708 (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
15709 (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
15710 (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
15711 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" : "");
15712 BulletText(fmt: "Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
15713 BulletText(fmt: "Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
15714 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
15715 {
15716 ImRect r = window->NavRectRel[layer];
15717 if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
15718 BulletText(fmt: "NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
15719 else
15720 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);
15721 DebugLocateItemOnHover(target_id: window->NavLastIds[layer]);
15722 }
15723 const ImVec2* pr = window->NavPreferredScoringPosRel;
15724 for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
15725 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.
15726 BulletText(fmt: "NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
15727 if (window->RootWindow != window) { DebugNodeWindow(window: window->RootWindow, label: "RootWindow"); }
15728 if (window->ParentWindow != NULL) { DebugNodeWindow(window: window->ParentWindow, label: "ParentWindow"); }
15729 if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window: window->ParentWindowForFocusRoute, label: "ParentWindowForFocusRoute"); }
15730 if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(windows: &window->DC.ChildWindows, label: "ChildWindows"); }
15731 if (window->ColumnsStorage.Size > 0 && TreeNode(str_id: "Columns", fmt: "Columns sets (%d)", window->ColumnsStorage.Size))
15732 {
15733 for (ImGuiOldColumns& columns : window->ColumnsStorage)
15734 DebugNodeColumns(columns: &columns);
15735 TreePop();
15736 }
15737 DebugNodeStorage(storage: &window->StateStorage, label: "Storage");
15738 TreePop();
15739}
15740
15741void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
15742{
15743 if (settings->WantDelete)
15744 BeginDisabled();
15745 Text(fmt: "0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
15746 settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
15747 if (settings->WantDelete)
15748 EndDisabled();
15749}
15750
15751void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
15752{
15753 if (!TreeNode(str_id: label, fmt: "%s (%d)", label, windows->Size))
15754 return;
15755 for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
15756 {
15757 PushID(ptr_id: (*windows)[i]);
15758 DebugNodeWindow(window: (*windows)[i], label: "Window");
15759 PopID();
15760 }
15761 TreePop();
15762}
15763
15764// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
15765void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
15766{
15767 for (int i = 0; i < windows_size; i++)
15768 {
15769 ImGuiWindow* window = windows[i];
15770 if (window->ParentWindowInBeginStack != parent_in_begin_stack)
15771 continue;
15772 char buf[20];
15773 ImFormatString(buf, IM_ARRAYSIZE(buf), fmt: "[%04d] Window", window->BeginOrderWithinContext);
15774 //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
15775 DebugNodeWindow(window, label: buf);
15776 Indent();
15777 DebugNodeWindowsListByBeginStackParent(windows: windows + i + 1, windows_size: windows_size - i - 1, parent_in_begin_stack: window);
15778 Unindent();
15779 }
15780}
15781
15782//-----------------------------------------------------------------------------
15783// [SECTION] DEBUG LOG WINDOW
15784//-----------------------------------------------------------------------------
15785
15786void ImGui::DebugLog(const char* fmt, ...)
15787{
15788 va_list args;
15789 va_start(args, fmt);
15790 DebugLogV(fmt, args);
15791 va_end(args);
15792}
15793
15794void ImGui::DebugLogV(const char* fmt, va_list args)
15795{
15796 ImGuiContext& g = *GImGui;
15797 const int old_size = g.DebugLogBuf.size();
15798 if (g.ContextName[0] != 0)
15799 g.DebugLogBuf.appendf(fmt: "[%s] [%05d] ", g.ContextName, g.FrameCount);
15800 else
15801 g.DebugLogBuf.appendf(fmt: "[%05d] ", g.FrameCount);
15802 g.DebugLogBuf.appendfv(fmt, args);
15803 g.DebugLogIndex.append(base: g.DebugLogBuf.c_str(), old_size, new_size: g.DebugLogBuf.size());
15804 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
15805 IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
15806#ifdef IMGUI_ENABLE_TEST_ENGINE
15807 // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
15808 const int new_size = g.DebugLogBuf.size();
15809 const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
15810 if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
15811 IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
15812#endif
15813}
15814
15815// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
15816static void SameLineOrWrap(const ImVec2& size)
15817{
15818 ImGuiContext& g = *GImGui;
15819 ImGuiWindow* window = g.CurrentWindow;
15820 ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
15821 if (window->WorkRect.Contains(r: ImRect(pos, pos + size)))
15822 ImGui::SameLine();
15823}
15824
15825static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
15826{
15827 ImGuiContext& g = *GImGui;
15828 ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(text: name).x, ImGui::GetFrameHeight());
15829 SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
15830 if (ImGui::CheckboxFlags(label: name, flags: &g.DebugLogFlags, flags_value: flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
15831 {
15832 g.DebugLogAutoDisableFrames = 2;
15833 g.DebugLogAutoDisableFlags |= flags;
15834 }
15835 ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
15836}
15837
15838void ImGui::ShowDebugLogWindow(bool* p_open)
15839{
15840 ImGuiContext& g = *GImGui;
15841 if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
15842 SetNextWindowSize(size: ImVec2(0.0f, GetFontSize() * 12.0f), cond: ImGuiCond_FirstUseEver);
15843 if (!Begin(name: "Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
15844 {
15845 End();
15846 return;
15847 }
15848
15849 ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
15850 CheckboxFlags(label: "All", flags: &g.DebugLogFlags, flags_value: all_enable_flags);
15851 SetItemTooltip("(except InputRouting which is spammy)");
15852
15853 ShowDebugLogFlag(name: "ActiveId", flags: ImGuiDebugLogFlags_EventActiveId);
15854 ShowDebugLogFlag(name: "Clipper", flags: ImGuiDebugLogFlags_EventClipper);
15855 ShowDebugLogFlag(name: "Focus", flags: ImGuiDebugLogFlags_EventFocus);
15856 ShowDebugLogFlag(name: "IO", flags: ImGuiDebugLogFlags_EventIO);
15857 ShowDebugLogFlag(name: "Nav", flags: ImGuiDebugLogFlags_EventNav);
15858 ShowDebugLogFlag(name: "Popup", flags: ImGuiDebugLogFlags_EventPopup);
15859 ShowDebugLogFlag(name: "Selection", flags: ImGuiDebugLogFlags_EventSelection);
15860 ShowDebugLogFlag(name: "InputRouting", flags: ImGuiDebugLogFlags_EventInputRouting);
15861
15862 if (SmallButton(label: "Clear"))
15863 {
15864 g.DebugLogBuf.clear();
15865 g.DebugLogIndex.clear();
15866 }
15867 SameLine();
15868 if (SmallButton(label: "Copy"))
15869 SetClipboardText(g.DebugLogBuf.c_str());
15870 SameLine();
15871 if (SmallButton(label: "Configure Outputs.."))
15872 OpenPopup(str_id: "Outputs");
15873 if (BeginPopup(str_id: "Outputs"))
15874 {
15875 CheckboxFlags(label: "OutputToTTY", flags: &g.DebugLogFlags, flags_value: ImGuiDebugLogFlags_OutputToTTY);
15876#ifndef IMGUI_ENABLE_TEST_ENGINE
15877 BeginDisabled();
15878#endif
15879 CheckboxFlags(label: "OutputToTestEngine", flags: &g.DebugLogFlags, flags_value: ImGuiDebugLogFlags_OutputToTestEngine);
15880#ifndef IMGUI_ENABLE_TEST_ENGINE
15881 EndDisabled();
15882#endif
15883 EndPopup();
15884 }
15885
15886 BeginChild(str_id: "##log", size_arg: ImVec2(0.0f, 0.0f), child_flags: ImGuiChildFlags_Border, window_flags: ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
15887
15888 const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
15889 g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
15890
15891 ImGuiListClipper clipper;
15892 clipper.Begin(items_count: g.DebugLogIndex.size());
15893 while (clipper.Step())
15894 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
15895 DebugTextUnformattedWithLocateItem(line_begin: g.DebugLogIndex.get_line_begin(base: g.DebugLogBuf.c_str(), n: line_no), line_end: g.DebugLogIndex.get_line_end(base: g.DebugLogBuf.c_str(), n: line_no));
15896 g.DebugLogFlags = backup_log_flags;
15897 if (GetScrollY() >= GetScrollMaxY())
15898 SetScrollHereY(1.0f);
15899 EndChild();
15900
15901 End();
15902}
15903
15904// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
15905void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
15906{
15907 TextUnformatted(text: line_begin, text_end: line_end);
15908 if (!IsItemHovered())
15909 return;
15910 ImGuiContext& g = *GImGui;
15911 ImRect text_rect = g.LastItemData.Rect;
15912 for (const char* p = line_begin; p <= line_end - 10; p++)
15913 {
15914 ImGuiID id = 0;
15915 if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(s: p + 2, format: "%X", &id) != 1 || ImCharIsXdigitA(c: p[10]))
15916 continue;
15917 ImVec2 p0 = CalcTextSize(text: line_begin, text_end: p);
15918 ImVec2 p1 = CalcTextSize(text: p, text_end: p + 10);
15919 g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
15920 if (IsMouseHoveringRect(r_min: g.LastItemData.Rect.Min, r_max: g.LastItemData.Rect.Max, clip: true))
15921 DebugLocateItemOnHover(target_id: id);
15922 p += 10;
15923 }
15924}
15925
15926//-----------------------------------------------------------------------------
15927// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
15928//-----------------------------------------------------------------------------
15929
15930// Draw a small cross at current CursorPos in current window's DrawList
15931void ImGui::DebugDrawCursorPos(ImU32 col)
15932{
15933 ImGuiContext& g = *GImGui;
15934 ImGuiWindow* window = g.CurrentWindow;
15935 ImVec2 pos = window->DC.CursorPos;
15936 window->DrawList->AddLine(p1: ImVec2(pos.x, pos.y - 3.0f), p2: ImVec2(pos.x, pos.y + 4.0f), col, thickness: 1.0f);
15937 window->DrawList->AddLine(p1: ImVec2(pos.x - 3.0f, pos.y), p2: ImVec2(pos.x + 4.0f, pos.y), col, thickness: 1.0f);
15938}
15939
15940// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
15941void ImGui::DebugDrawLineExtents(ImU32 col)
15942{
15943 ImGuiContext& g = *GImGui;
15944 ImGuiWindow* window = g.CurrentWindow;
15945 float curr_x = window->DC.CursorPos.x;
15946 float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
15947 float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
15948 window->DrawList->AddLine(p1: ImVec2(curr_x - 5.0f, line_y1), p2: ImVec2(curr_x + 5.0f, line_y1), col, thickness: 1.0f);
15949 window->DrawList->AddLine(p1: ImVec2(curr_x - 0.5f, line_y1), p2: ImVec2(curr_x - 0.5f, line_y2), col, thickness: 1.0f);
15950 window->DrawList->AddLine(p1: ImVec2(curr_x - 5.0f, line_y2), p2: ImVec2(curr_x + 5.0f, line_y2), col, thickness: 1.0f);
15951}
15952
15953// Draw last item rect in ForegroundDrawList (so it is always visible)
15954void ImGui::DebugDrawItemRect(ImU32 col)
15955{
15956 ImGuiContext& g = *GImGui;
15957 ImGuiWindow* window = g.CurrentWindow;
15958 GetForegroundDrawList(window)->AddRect(p_min: g.LastItemData.Rect.Min, p_max: g.LastItemData.Rect.Max, col);
15959}
15960
15961// [DEBUG] Locate item position/rectangle given an ID.
15962static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255); // Green
15963
15964void ImGui::DebugLocateItem(ImGuiID target_id)
15965{
15966 ImGuiContext& g = *GImGui;
15967 g.DebugLocateId = target_id;
15968 g.DebugLocateFrames = 2;
15969 g.DebugBreakInLocateId = false;
15970}
15971
15972// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
15973void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
15974{
15975 if (target_id == 0 || !IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
15976 return;
15977 ImGuiContext& g = *GImGui;
15978 DebugLocateItem(target_id);
15979 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);
15980
15981 // Can't easily use a context menu here because it will mess with focus, active id etc.
15982 if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
15983 {
15984 DebugBreakButtonTooltip(keyboard_only: false, description_of_location: "in ItemAdd()");
15985 if (IsKeyChordPressed(key_chord: g.DebugBreakKeyChord))
15986 g.DebugBreakInLocateId = true;
15987 }
15988}
15989
15990void ImGui::DebugLocateItemResolveWithLastItem()
15991{
15992 ImGuiContext& g = *GImGui;
15993
15994 // [DEBUG] Debug break requested by user
15995 if (g.DebugBreakInLocateId)
15996 IM_DEBUG_BREAK();
15997
15998 ImGuiLastItemData item_data = g.LastItemData;
15999 g.DebugLocateId = 0;
16000 ImDrawList* draw_list = GetForegroundDrawList(window: g.CurrentWindow);
16001 ImRect r = item_data.Rect;
16002 r.Expand(amount: 3.0f);
16003 ImVec2 p1 = g.IO.MousePos;
16004 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);
16005 draw_list->AddRect(p_min: r.Min, p_max: r.Max, col: DEBUG_LOCATE_ITEM_COLOR);
16006 draw_list->AddLine(p1, p2, col: DEBUG_LOCATE_ITEM_COLOR);
16007}
16008
16009void ImGui::DebugStartItemPicker()
16010{
16011 ImGuiContext& g = *GImGui;
16012 g.DebugItemPickerActive = true;
16013}
16014
16015// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
16016void ImGui::UpdateDebugToolItemPicker()
16017{
16018 ImGuiContext& g = *GImGui;
16019 g.DebugItemPickerBreakId = 0;
16020 if (!g.DebugItemPickerActive)
16021 return;
16022
16023 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
16024 SetMouseCursor(ImGuiMouseCursor_Hand);
16025 if (IsKeyPressed(key: ImGuiKey_Escape))
16026 g.DebugItemPickerActive = false;
16027 const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
16028 if (!change_mapping && IsMouseClicked(button: g.DebugItemPickerMouseButton) && hovered_id)
16029 {
16030 g.DebugItemPickerBreakId = hovered_id;
16031 g.DebugItemPickerActive = false;
16032 }
16033 for (int mouse_button = 0; mouse_button < 3; mouse_button++)
16034 if (change_mapping && IsMouseClicked(button: mouse_button))
16035 g.DebugItemPickerMouseButton = (ImU8)mouse_button;
16036 SetNextWindowBgAlpha(0.70f);
16037 if (!BeginTooltip())
16038 return;
16039 Text(fmt: "HoveredId: 0x%08X", hovered_id);
16040 Text(fmt: "Press ESC to abort picking.");
16041 const char* mouse_button_names[] = { "Left", "Right", "Middle" };
16042 if (change_mapping)
16043 Text(fmt: "Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
16044 else
16045 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]);
16046 EndTooltip();
16047}
16048
16049// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
16050void ImGui::UpdateDebugToolStackQueries()
16051{
16052 ImGuiContext& g = *GImGui;
16053 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
16054
16055 // Clear hook when id stack tool is not visible
16056 g.DebugHookIdInfo = 0;
16057 if (g.FrameCount != tool->LastActiveFrame + 1)
16058 return;
16059
16060 // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
16061 // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
16062 const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
16063 if (tool->QueryId != query_id)
16064 {
16065 tool->QueryId = query_id;
16066 tool->StackLevel = -1;
16067 tool->Results.resize(new_size: 0);
16068 }
16069 if (query_id == 0)
16070 return;
16071
16072 // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
16073 int stack_level = tool->StackLevel;
16074 if (stack_level >= 0 && stack_level < tool->Results.Size)
16075 if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
16076 tool->StackLevel++;
16077
16078 // Update hook
16079 stack_level = tool->StackLevel;
16080 if (stack_level == -1)
16081 g.DebugHookIdInfo = query_id;
16082 if (stack_level >= 0 && stack_level < tool->Results.Size)
16083 {
16084 g.DebugHookIdInfo = tool->Results[stack_level].ID;
16085 tool->Results[stack_level].QueryFrameCount++;
16086 }
16087}
16088
16089// [DEBUG] ID Stack tool: hooks called by GetID() family functions
16090void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
16091{
16092 ImGuiContext& g = *GImGui;
16093 ImGuiWindow* window = g.CurrentWindow;
16094 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
16095
16096 // Step 0: stack query
16097 // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
16098 if (tool->StackLevel == -1)
16099 {
16100 tool->StackLevel++;
16101 tool->Results.resize(new_size: window->IDStack.Size + 1, v: ImGuiStackLevelInfo());
16102 for (int n = 0; n < window->IDStack.Size + 1; n++)
16103 tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
16104 return;
16105 }
16106
16107 // Step 1+: query for individual level
16108 IM_ASSERT(tool->StackLevel >= 0);
16109 if (tool->StackLevel != window->IDStack.Size)
16110 return;
16111 ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
16112 IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
16113
16114 switch (data_type)
16115 {
16116 case ImGuiDataType_S32:
16117 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "%d", (int)(intptr_t)data_id);
16118 break;
16119 case ImGuiDataType_String:
16120 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);
16121 break;
16122 case ImGuiDataType_Pointer:
16123 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "(void*)0x%p", data_id);
16124 break;
16125 case ImGuiDataType_ID:
16126 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.
16127 return;
16128 ImFormatString(buf: info->Desc, IM_ARRAYSIZE(info->Desc), fmt: "0x%08X [override]", id);
16129 break;
16130 default:
16131 IM_ASSERT(0);
16132 }
16133 info->QuerySuccess = true;
16134 info->DataType = data_type;
16135}
16136
16137static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
16138{
16139 ImGuiStackLevelInfo* info = &tool->Results[n];
16140 ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(id: info->ID) : NULL;
16141 if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
16142 return ImFormatString(buf, buf_size, fmt: format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
16143 if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
16144 return ImFormatString(buf, buf_size, fmt: (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
16145 if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
16146 return (*buf = 0);
16147#ifdef IMGUI_ENABLE_TEST_ENGINE
16148 if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
16149 return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
16150#endif
16151 return ImFormatString(buf, buf_size, fmt: "???");
16152}
16153
16154// ID Stack Tool: Display UI
16155void ImGui::ShowIDStackToolWindow(bool* p_open)
16156{
16157 ImGuiContext& g = *GImGui;
16158 if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
16159 SetNextWindowSize(size: ImVec2(0.0f, GetFontSize() * 8.0f), cond: ImGuiCond_FirstUseEver);
16160 if (!Begin(name: "Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
16161 {
16162 End();
16163 return;
16164 }
16165
16166 // Display hovered/active status
16167 ImGuiIDStackTool* tool = &g.DebugIDStackTool;
16168 const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
16169 const ImGuiID active_id = g.ActiveId;
16170#ifdef IMGUI_ENABLE_TEST_ENGINE
16171 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) : "");
16172#else
16173 Text(fmt: "HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
16174#endif
16175 SameLine();
16176 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.");
16177
16178 // CTRL+C to copy path
16179 const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
16180 Checkbox(label: "Ctrl+C: copy path to clipboard", v: &tool->CopyToClipboardOnCtrlC);
16181 SameLine();
16182 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*");
16183 if (tool->CopyToClipboardOnCtrlC && Shortcut(key_chord: ImGuiMod_Ctrl | ImGuiKey_C, flags: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
16184 {
16185 tool->CopyToClipboardLastTime = (float)g.Time;
16186 char* p = g.TempBuffer.Data;
16187 char* p_end = p + g.TempBuffer.Size;
16188 for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
16189 {
16190 *p++ = '/';
16191 char level_desc[256];
16192 StackToolFormatLevelInfo(tool, n: stack_n, format_for_ui: false, buf: level_desc, IM_ARRAYSIZE(level_desc));
16193 for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
16194 {
16195 if (level_desc[n] == '/')
16196 *p++ = '\\';
16197 *p++ = level_desc[n];
16198 }
16199 }
16200 *p = '\0';
16201 SetClipboardText(g.TempBuffer.Data);
16202 }
16203
16204 // Display decorated stack
16205 tool->LastActiveFrame = g.FrameCount;
16206 if (tool->Results.Size > 0 && BeginTable(str_id: "##table", columns: 3, flags: ImGuiTableFlags_Borders))
16207 {
16208 const float id_width = CalcTextSize(text: "0xDDDDDDDD").x;
16209 TableSetupColumn(label: "Seed", flags: ImGuiTableColumnFlags_WidthFixed, init_width_or_weight: id_width);
16210 TableSetupColumn(label: "PushID", flags: ImGuiTableColumnFlags_WidthStretch);
16211 TableSetupColumn(label: "Result", flags: ImGuiTableColumnFlags_WidthFixed, init_width_or_weight: id_width);
16212 TableHeadersRow();
16213 for (int n = 0; n < tool->Results.Size; n++)
16214 {
16215 ImGuiStackLevelInfo* info = &tool->Results[n];
16216 TableNextColumn();
16217 Text(fmt: "0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
16218 TableNextColumn();
16219 StackToolFormatLevelInfo(tool, n, format_for_ui: true, buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size);
16220 TextUnformatted(text: g.TempBuffer.Data);
16221 TableNextColumn();
16222 Text(fmt: "0x%08X", info->ID);
16223 if (n == tool->Results.Size - 1)
16224 TableSetBgColor(target: ImGuiTableBgTarget_CellBg, color: GetColorU32(idx: ImGuiCol_Header));
16225 }
16226 EndTable();
16227 }
16228 End();
16229}
16230
16231#else
16232
16233void ImGui::ShowMetricsWindow(bool*) {}
16234void ImGui::ShowFontAtlas(ImFontAtlas*) {}
16235void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
16236void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
16237void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
16238void ImGui::DebugNodeFont(ImFont*) {}
16239void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
16240void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
16241void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
16242void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
16243void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
16244void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
16245
16246void ImGui::ShowDebugLogWindow(bool*) {}
16247void ImGui::ShowIDStackToolWindow(bool*) {}
16248void ImGui::DebugStartItemPicker() {}
16249void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
16250
16251#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
16252
16253//-----------------------------------------------------------------------------
16254
16255// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
16256// 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.
16257#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
16258#include "imgui_user.inl"
16259#endif
16260
16261//-----------------------------------------------------------------------------
16262
16263#endif // #ifndef IMGUI_DISABLE
16264

source code of qt3d/src/3rdparty/imgui/imgui.cpp