1// dear imgui, v1.92.2b
2// (main code and documentation)
3
4// Help:
5// - See links below.
6// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7// - Read top of imgui.cpp for more details, links and comments.
8
9// Resources:
10// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11// - Homepage ................... https://github.com/ocornut/imgui
12// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!)
14// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
19// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools
20// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21// - Issues & support ........... https://github.com/ocornut/imgui/issues
22// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24// For first-time users having issues compiling/linking/running:
25// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27// Since 1.92, we encourage font loading questions to also be posted in 'Issues'.
28
29// Copyright (c) 2014-2025 Omar Cornut
30// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
31// See LICENSE.txt for copyright and licensing details (standard MIT License).
32// This library is free but needs your support to sustain development and maintenance.
33// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
34// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
35// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
36
37// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
38// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
39// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
40// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
41// to a better solution or official support for them.
42
43/*
44
45Index of this file:
46
47DOCUMENTATION
48
49- MISSION STATEMENT
50- CONTROLS GUIDE
51- PROGRAMMER GUIDE
52 - READ FIRST
53 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
54 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
55 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
56 - USING CUSTOM BACKEND / CUSTOM ENGINE
57- API BREAKING CHANGES (read me when you update!)
58- FREQUENTLY ASKED QUESTIONS (FAQ)
59 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
60
61CODE
62(search for "[SECTION]" in the code to find them)
63
64// [SECTION] INCLUDES
65// [SECTION] FORWARD DECLARATIONS
66// [SECTION] CONTEXT AND MEMORY ALLOCATORS
67// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
68// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
69// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
70// [SECTION] MISC HELPERS/UTILITIES (File functions)
71// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
72// [SECTION] MISC HELPERS/UTILITIES (Color functions)
73// [SECTION] ImGuiStorage
74// [SECTION] ImGuiTextFilter
75// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
76// [SECTION] ImGuiListClipper
77// [SECTION] STYLING
78// [SECTION] RENDER HELPERS
79// [SECTION] INITIALIZATION, SHUTDOWN
80// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
81// [SECTION] FONTS, TEXTURES
82// [SECTION] ID STACK
83// [SECTION] INPUTS
84// [SECTION] ERROR CHECKING, STATE RECOVERY
85// [SECTION] ITEM SUBMISSION
86// [SECTION] LAYOUT
87// [SECTION] SCROLLING
88// [SECTION] TOOLTIPS
89// [SECTION] POPUPS
90// [SECTION] WINDOW FOCUS
91// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
92// [SECTION] DRAG AND DROP
93// [SECTION] LOGGING/CAPTURING
94// [SECTION] SETTINGS
95// [SECTION] LOCALIZATION
96// [SECTION] VIEWPORTS, PLATFORM WINDOWS
97// [SECTION] DOCKING
98// [SECTION] PLATFORM DEPENDENT HELPERS
99// [SECTION] METRICS/DEBUGGER WINDOW
100// [SECTION] DEBUG LOG WINDOW
101// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
102
103*/
104
105//-----------------------------------------------------------------------------
106// DOCUMENTATION
107//-----------------------------------------------------------------------------
108
109/*
110
111 MISSION STATEMENT
112 =================
113
114 - Easy to use to create code-driven and data-driven tools.
115 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
116 - Easy to hack and improve.
117 - Minimize setup and maintenance.
118 - Minimize state storage on user side.
119 - Minimize state synchronization.
120 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
121 - Efficient runtime and memory consumption.
122
123 Designed primarily for developers and content-creators, not the typical end-user!
124 Some of the current weaknesses (which we aim to address in the future) includes:
125
126 - Doesn't look fancy.
127 - Limited layout features, intricate layouts are typically crafted in code.
128
129
130 CONTROLS GUIDE
131 ==============
132
133 - MOUSE CONTROLS
134 - Mouse wheel: Scroll vertically.
135 - SHIFT+Mouse wheel: Scroll horizontally.
136 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
137 - Click ^, Double-Click title: Collapse window.
138 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
139 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
140 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
141
142 - TEXT EDITOR
143 - Hold SHIFT or Drag Mouse: Select text.
144 - CTRL+Left/Right: Word jump.
145 - CTRL+Shift+Left/Right: Select words.
146 - CTRL+A or Double-Click: Select All.
147 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
148 - CTRL+Z Undo.
149 - CTRL+Y or CTRL+Shift+Z: Redo.
150 - ESCAPE: Revert text to its original value.
151 - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
152
153 - KEYBOARD CONTROLS
154 - Basic:
155 - Tab, SHIFT+Tab Cycle through text editable fields.
156 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
157 - CTRL+Click Input text into a Slider or Drag widget.
158 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
159 - Tab, SHIFT+Tab: Cycle through every items.
160 - Arrow keys Move through items using directional navigation. Tweak value.
161 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
162 - Enter Activate item (prefer text input when possible).
163 - Space Activate item (prefer tweaking with arrows when possible).
164 - Escape Deactivate item, leave child window, close popup.
165 - Page Up, Page Down Previous page, next page.
166 - Home, End Scroll to top, scroll to bottom.
167 - Alt Toggle between scrolling layer and menu layer.
168 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
169 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
170 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
171 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
172 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
173
174 - GAMEPAD CONTROLS
175 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
176 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
177 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
178 - Backend support: backend needs to:
179 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
180 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
181 Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
182 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
183 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
184
185 - REMOTE INPUTS SHARING & MOUSE EMULATION
186 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
187 - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
188 in order to share your PC mouse/keyboard.
189 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
190 - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag.
191 Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
192 When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
193 When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
194 (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
195 (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
196 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
197
198
199 PROGRAMMER GUIDE
200 ================
201
202 READ FIRST
203 ----------
204 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
205 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
206 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
207 data retention on your side, less state duplication, less state synchronization, fewer bugs.
208 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
209 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
210 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
211 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
212 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
213 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
214 For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
215 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
216 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
217 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
218 If you get an assert, read the messages and comments around the assert.
219 - This codebase aims to be highly optimized:
220 - A typical idle frame should never call malloc/free.
221 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
222 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
223 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
224 - This codebase aims to be both highly opinionated and highly flexible:
225 - This code works because of the things it choose to solve or not solve.
226 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
227 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
228 This is to increase compatibility, increase maintainability and facilitate use from other languages.
229 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
230 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
231 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
232 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
233 (so don't use ImVector in your code or at our own risk!).
234 - Building: We don't use nor mandate a build system for the main library.
235 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
236 This is also because providing a build system for the main library would be of little-value.
237 The build problems are almost never coming from the main library but from specific backends.
238
239
240 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
241 ----------------------------------------------
242 - Update submodule or copy/overwrite every file.
243 - About imconfig.h:
244 - You may modify your copy of imconfig.h, in this case don't overwrite it.
245 - or you may locally branch to modify imconfig.h and merge/rebase latest.
246 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
247 specify a custom path for your imconfig.h file and instead not have to modify the default one.
248
249 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
250 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
251 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
252 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
253 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
254 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
255 likely be a comment about it. Please report any issue to the GitHub page!
256 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
257 - Try to keep your copy of Dear ImGui reasonably up to date!
258
259
260 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
261 ---------------------------------------------------------------
262 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
263 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
264 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
265 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
266 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
267 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
268 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
269 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
270 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
271 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
272 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
273 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
274
275
276 HOW A SIMPLE APPLICATION MAY LOOK LIKE
277 --------------------------------------
278
279 USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
280 The sub-folders in examples/ contain examples applications following this structure.
281
282 // Application init: create a dear imgui context, setup some options, load fonts
283 ImGui::CreateContext();
284 ImGuiIO& io = ImGui::GetIO();
285 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
286 // TODO: Fill optional fields of the io structure later.
287 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
288
289 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
290 ImGui_ImplWin32_Init(hwnd);
291 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
292
293 // Application main loop
294 while (true)
295 {
296 // Feed inputs to dear imgui, start new frame
297 ImGui_ImplDX11_NewFrame();
298 ImGui_ImplWin32_NewFrame();
299 ImGui::NewFrame();
300
301 // Any application code here
302 ImGui::Text("Hello, world!");
303
304 // Render dear imgui into framebuffer
305 ImGui::Render();
306 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
307 g_pSwapChain->Present(1, 0);
308 }
309
310 // Shutdown
311 ImGui_ImplDX11_Shutdown();
312 ImGui_ImplWin32_Shutdown();
313 ImGui::DestroyContext();
314
315 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
316 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
317 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
318
319
320USING CUSTOM BACKEND / CUSTOM ENGINE
321------------------------------------
322
323IMPLEMENTING YOUR PLATFORM BACKEND:
324 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions.
325 -> the Platform backends in impl_impl_XXX.cpp files contain many implementations.
326
327IMPLEMENTING YOUR RenderDrawData() function:
328 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
329 -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function.
330
331IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures:
332 -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md
333 -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function.
334
335 Basic application/backend skeleton:
336
337 // Application init: create a Dear ImGui context, setup some options, load fonts
338 ImGui::CreateContext();
339 ImGuiIO& io = ImGui::GetIO();
340 // TODO: set io.ConfigXXX values, e.g.
341 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls
342
343 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
344 io.Fonts->AddFontFromFileTTF("NotoSans.ttf");
345
346 // Application main loop
347 while (true)
348 {
349 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
350 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
351 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
352 io.DisplaySize.x = 1920.0f; // set the current display width
353 io.DisplaySize.y = 1280.0f; // set the current display height here
354 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
355 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
356 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
357
358 // Call NewFrame(), after this point you can use ImGui::* functions anytime
359 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
360 ImGui::NewFrame();
361
362 // Most of your application code here
363 ImGui::Text("Hello, world!");
364 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
365 MyGameRender(); // may use any Dear ImGui functions as well!
366
367 // End the dear imgui frame
368 // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
369 ImGui::EndFrame(); // this is automatically called by Render(), but available
370 ImGui::Render();
371
372 // Update textures
373 ImDrawData* draw_data = ImGui::GetDrawData();
374 for (ImTextureData* tex : *draw_data->Textures)
375 if (tex->Status != ImTextureStatus_OK)
376 MyImGuiBackend_UpdateTexture(tex);
377
378 // Render dear imgui contents, swap buffers
379 MyImGuiBackend_RenderDrawData(draw_data);
380 SwapBuffers();
381 }
382
383 // Shutdown
384 ImGui::DestroyContext();
385
386
387
388 API BREAKING CHANGES
389 ====================
390
391 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
392 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
393 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
394 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
395
396(Docking/Viewport Branch)
397 - 2025/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
398 - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
399 you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
400 - likewise io.MousePos and GetMousePos() will use OS coordinates.
401 If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
402
403 - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988)
404 - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete).
405 - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM
406 to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150)
407 - Incorrect way to make a window content size 200x200:
408 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
409 - Correct ways to make a window content size 200x200:
410 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
411 Begin(...) + Dummy(ImVec2(200,200)) + End();
412 - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries.
413 - 2025/06/11 (1.92.0) - Renamed/moved ImGuiConfigFlags_DpiEnableScaleFonts -> bool io.ConfigDpiScaleFonts.
414 - Renamed/moved ImGuiConfigFlags_DpiEnableScaleViewports -> bool io.ConfigDpiScaleViewports. **Neither of those flags are very useful in current code. They will be useful once we merge font changes.**
415 - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED.
416 IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/
417 As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+).
418 If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes.
419 - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this!
420 - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f):
421 This WILL NOT map correctly to the new system! Because font will rasterize as requested size.
422 - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required.
423 - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch.
424 - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized.
425 - PushFont() API now has a REQUIRED size parameter.
426 - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize).
427 - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value.
428 - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site.
429 - Kept inline single parameter function. Will obsolete.
430 - Fonts: **IMPORTANT** on Font Merging:
431 - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph.
432 Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font.
433 - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before!
434 - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1.
435 After the update and when using a new backend, those glyphs may now loaded from Font Source 1!
436 - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source:
437 // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
438 static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
439 ImFontConfig cfg1;
440 cfg1.GlyphExcludeRanges = exclude_ranges;
441 io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
442 // Add Font Source 2, which expects to use the range above
443 ImFontConfig cfg2;
444 cfg2.MergeMode = true;
445 io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
446 - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde
447 - Fonts: **IMPORTANT** on Thread Safety:
448 - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded.
449 - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont().
450 - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font".
451 - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'.
452 - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded().
453 - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete).
454 - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling.
455 - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese().
456 - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327)
457 - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't.
458 - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors.
459 - Fonts: obsoleted ImFont::Scale which is not useful anymore.
460 - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things:
461 - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef.
462 - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef.
463 - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]
464 - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount.
465 - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size.
466 - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance().
467 - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels().
468 - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.)
469 - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags.
470 If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader().
471 - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()
472 - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader()
473 - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1]
474 - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV().
475 - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h.
476 - old:
477 const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id);
478 ImVec2 uv0, uv1;
479 atlas->GetCustomRectUV(r, &uv0, &uv1);
480 ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1);
481 - new;
482 ImFontAtlasRect r;
483 atlas->GetCustomRect(custom_rect_id, &r);
484 ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1);
485 - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple.
486 - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code.
487 - Prefer adding a font source (ImFontConfig) using a custom/procedural loader.
488 - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture().
489 - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more.
490 - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition()
491 - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....);
492 - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....);
493 The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function.
494 - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete).
495 - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092)
496 - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead.
497 - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name.
498 - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387)
499 - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238)
500 - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0));
501 - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1));
502 - new: void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1));
503 - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton().
504 - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize.
505 - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable.
506 - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified.
507 - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg().
508 - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount.
509 - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX.
510 - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior.
511 prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior.
512 the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls:
513 - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937)
514 - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions.
515 As a result, old .ini data may be partially lost (docking and tables information particularly).
516 Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data.
517 - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
518 - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
519 - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
520 - pre-1.87 backends are not supported:
521 - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
522 - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
523 - for more reference:
524 - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
525 - read https://github.com/ocornut/imgui/issues/4921
526 - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
527 - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
528 - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
529 - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
530 - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
531 moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
532 kept legacy names (will obsolete) + code that copies settings once the first time. Dynamically changing the old value won't work. Switch to using the new value!
533 - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
534 this removes the requirement to redefine it for backends which are e.g. storing descriptor sets or other 64-bits structures when building on 32-bits archs. It therefore simplify various building scripts/helpers.
535 you may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID' when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
536 in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
537 - May warn: ImGui::Image((void*)MyTextureData, ...);
538 - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...);
539 - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
540 - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
541 - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
542 - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
543 although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
544 - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
545 it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
546 - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
547 - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
548 - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
549 - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line.
550 - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660)
551 - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
552 - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278)
553 - access those via GetPlatformIO() instead of GetIO().
554 some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol.
555 - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder:
556 - old ImageButton() before 1.89 used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID)
557 - new ImageButton() since 1.89 requires an explicit 'const char* str_id'
558 - old ImageButton() before 1.89 had frame_padding' override argument.
559 - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar().
560 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
561 you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
562 - instead of: GetWindowContentRegionMax().x - GetCursorPos().x
563 - you can use: GetContentRegionAvail().x
564 - instead of: GetWindowContentRegionMax().x + GetWindowPos().x
565 - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
566 - instead of: GetContentRegionMax()
567 - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
568 - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
569 - you can use: GetContentRegionAvail() // when called from left edge of window
570 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
571 (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
572 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
573 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
574 - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
575 - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
576 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
577 - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
578 - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
579 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
580 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
581 - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
582 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
583 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
584 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
585 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
586 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
587 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
588 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
589 - old: CaptureKeyboardFromApp(bool)
590 - new: SetNextFrameWantCaptureKeyboard(bool)
591 - old: CaptureMouseFromApp(bool)
592 - new: SetNextFrameWantCaptureMouse(bool)
593 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
594 - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
595 - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
596 - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
597 - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
598 - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
599 - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
600 - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
601 - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
602 - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
603 for various reasons those changes makes sense. They are being made because making some of those API public.
604 only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
605 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
606 - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
607 - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
608 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
609 - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
610 - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
611 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
612 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
613 - old: TreeNode("##Hidden"); SameLine(); Text("Hello"); // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
614 - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
615 with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
616 You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
617 (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
618 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
619 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
620 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
621 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
622 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
623 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
624 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
625 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
626 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
627 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
628 those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
629 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
630 - old: BeginChild("Name", size, true)
631 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
632 - old: BeginChild("Name", size, false)
633 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
634 **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'**
635 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
636 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
637 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
638 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
639 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
640 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
641 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
642 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
643 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
644 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
645 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
646 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
647 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
648 - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
649 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
650 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
651 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
652 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
653 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
654 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
655 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
656 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
657 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
658 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
659 - ListBoxFooter() -> use EndListBox()
660 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
661 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
662 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
663 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
664 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
665 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
666 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
667 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
668 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
669 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
670 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
671 it has been frequently requested by people to use our own. We had an opt-in define which was
672 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
673 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
674 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
675 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
676 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
677 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
678 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
679 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
680 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
681 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
682 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
683 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
684 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
685 exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
686 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
687 this will require uses of legacy backend-dependent indices to be casted, e.g.
688 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
689 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
690 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
691 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
692 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
693 - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
694 - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
695 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
696 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
697 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
698 - previously this would make the window content size ~200x200:
699 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
700 - instead, please submit an item:
701 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
702 - alternative:
703 Begin(...) + Dummy(ImVec2(200,200)) + End();
704 - content size is now only extended when submitting an item!
705 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
706 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
707 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
708 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
709 - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
710 - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
711 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
712 - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
713 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
714 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
715 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
716 - Official backends from 1.87+ -> no issue.
717 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
718 - Custom backends not writing to io.NavInputs[] -> no issue.
719 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
720 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
721 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
722 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
723 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
724 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
725 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
726 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputting text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
727 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
728 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
729 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
730 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
731 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
732 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
733 read https://github.com/ocornut/imgui/issues/4921 for details.
734 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
735 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
736 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
737 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes).
738 - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
739 - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
740 - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
741 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
742 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
743 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
744 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
745 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
746 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
747 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
748 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
749 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
750 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
751 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
752 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
753 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
754 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
755 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
756 - if you are using official backends from the source tree: you have nothing to do.
757 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
758 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
759 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
760 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
761 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
762 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
763 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
764 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
765 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
766 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
767 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
768 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
769 the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
770 legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
771 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
772 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
773 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
774 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
775 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
776 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
777 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
778 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
779 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
780 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
781 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
782 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
783 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
784 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
785 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
786 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
787 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
788 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
789 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
790 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
791 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
792 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
793 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
794 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
795 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
796 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
797 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
798 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
799 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
800 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
801 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
802 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
803 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
804 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
805 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
806 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
807 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
808 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
809 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
810 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
811 - if you omitted the 'power' parameter (likely!), you are not affected.
812 - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
813 - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
814 see https://github.com/ocornut/imgui/issues/3361 for all details.
815 kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
816 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
817 - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
818 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
819 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
820 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
821 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
822 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
823 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
824 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
825 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
826 - ShowTestWindow() -> use ShowDemoWindow()
827 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
828 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
829 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
830 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
831 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
832 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
833 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
834 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
835 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
836 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
837 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
838 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
839 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
840 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
841 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
842 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
843 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
844 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
845 - ImFont::Glyph -> use ImFontGlyph
846 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
847 if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
848 The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
849 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
850 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
851 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
852 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
853 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
854 overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
855 This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
856 Please reach out if you are affected.
857 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
858 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
859 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
860 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
861 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
862 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
863 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
864 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
865 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
866 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
867 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
868 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
869 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
870 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
871 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
872 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
873 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
874 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
875 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
876 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
877 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
878 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
879 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
880 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
881 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
882 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
883 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
884 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
885 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
886 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
887 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
888 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
889 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
890 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
891 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
892 To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
893 If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
894 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
895 consistent with other functions. Kept redirection functions (will obsolete).
896 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
897 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
898 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
899 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
900 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
901 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
902 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
903 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
904 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
905 - removed Shutdown() function, as DestroyContext() serve this purpose.
906 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
907 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
908 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
909 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
910 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
911 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
912 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
913 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
914 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
915 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
916 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
917 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
918 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
919 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
920 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
921 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
922 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
923 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
924 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
925 Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
926 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
927 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
928 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
929 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
930 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
931 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
932 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
933 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
934 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
935 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
936 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
937 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
938 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
939 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
940 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
941 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
942 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
943 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
944 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
945 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
946 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix.
947 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
948 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
949 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
950 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
951 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
952 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
953 - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
954 - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
955 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
956 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
957 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
958 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
959 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
960 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
961 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
962 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
963 If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
964 This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
965 ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
966 If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
967 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
968 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
969 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
970 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
971 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
972 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
973 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
974 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
975 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
976 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
977 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
978 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
979 GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
980 GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
981 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
982 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
983 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
984 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
985 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
986 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
987 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
988 - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
989 - the signature of the io.RenderDrawListsFn handler has changed!
990 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
991 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
992 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
993 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
994 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
995 - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
996 - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
997 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
998 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
999 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
1000 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
1001 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
1002 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
1003 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
1004 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
1005 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
1006 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
1007 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
1008 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
1009 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
1010 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
1011 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
1012 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
1013 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
1014 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
1015 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
1016 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
1017 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
1018 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
1019 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
1020 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
1021 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
1022 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
1023 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
1024 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
1025 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
1026 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
1027 you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
1028 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
1029 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
1030 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
1031 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
1032 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
1033 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
1034 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
1035 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
1036 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
1037 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
1038 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
1039 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
1040 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
1041 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
1042
1043
1044 FREQUENTLY ASKED QUESTIONS (FAQ)
1045 ================================
1046
1047 Read all answers online:
1048 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
1049 Read all answers locally (with a text editor or ideally a Markdown viewer):
1050 docs/FAQ.md
1051 Some answers are copied down here to facilitate searching in code.
1052
1053 Q&A: Basics
1054 ===========
1055
1056 Q: Where is the documentation?
1057 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
1058 - Run the examples/ applications and explore them.
1059 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
1060 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
1061 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
1062 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
1063 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
1064 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
1065 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
1066 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
1067 - Your programming IDE is your friend, find the type or function declaration to find comments
1068 associated with it.
1069
1070 Q: What is this library called?
1071 Q: Which version should I get?
1072 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
1073 >> See https://www.dearimgui.com/faq for details.
1074
1075 Q&A: Integration
1076 ================
1077
1078 Q: How to get started?
1079 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
1080
1081 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
1082 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
1083 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
1084
1085 Q. How can I enable keyboard or gamepad controls?
1086 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
1087 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
1088 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
1089 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
1090 >> See https://www.dearimgui.com/faq
1091
1092 Q&A: Usage
1093 ----------
1094
1095 Q: About the ID Stack system..
1096 - Why is my widget not reacting when I click on it?
1097 - How can I have widgets with an empty label?
1098 - How can I have multiple widgets with the same label?
1099 - How can I have multiple windows with the same label?
1100 Q: How can I display an image? What is ImTextureID, how does it work?
1101 Q: How can I use my own math types instead of ImVec2?
1102 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
1103 Q: How can I display custom shapes? (using low-level ImDrawList API)
1104 >> See https://www.dearimgui.com/faq
1105
1106 Q&A: Fonts, Text
1107 ================
1108
1109 Q: How should I handle DPI in my application?
1110 Q: How can I load a different font than the default?
1111 Q: How can I easily use icons in my application?
1112 Q: How can I load multiple fonts?
1113 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
1114 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
1115
1116 Q&A: Concerns
1117 =============
1118
1119 Q: Who uses Dear ImGui?
1120 Q: Can you create elaborate/serious tools with Dear ImGui?
1121 Q: Can you reskin the look of Dear ImGui?
1122 Q: Why using C++ (as opposed to C)?
1123 >> See https://www.dearimgui.com/faq
1124
1125 Q&A: Community
1126 ==============
1127
1128 Q: How can I help?
1129 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1130 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1131 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1132 >>> See https://github.com/ocornut/imgui/wiki/Funding
1133 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1134 - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1135 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1136 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1137 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1138 - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1139
1140*/
1141
1142//-------------------------------------------------------------------------
1143// [SECTION] INCLUDES
1144//-------------------------------------------------------------------------
1145
1146#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1147#define _CRT_SECURE_NO_WARNINGS
1148#endif
1149
1150#ifndef IMGUI_DEFINE_MATH_OPERATORS
1151#define IMGUI_DEFINE_MATH_OPERATORS
1152#endif
1153
1154#include "imgui.h"
1155#ifndef IMGUI_DISABLE
1156#include "imgui_internal.h"
1157
1158// System includes
1159#include <stdio.h> // vsnprintf, sscanf, printf
1160#include <stdint.h> // intptr_t
1161
1162// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1163#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1164#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1165#endif
1166
1167// [Windows] OS specific includes (optional)
1168#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1169#define IMGUI_DISABLE_WIN32_FUNCTIONS
1170#endif
1171#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1172#ifndef WIN32_LEAN_AND_MEAN
1173#define WIN32_LEAN_AND_MEAN
1174#endif
1175#ifndef NOMINMAX
1176#define NOMINMAX
1177#endif
1178#ifndef __MINGW32__
1179#include <Windows.h> // _wfopen, OpenClipboard
1180#else
1181#include <windows.h>
1182#endif
1183#if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
1184// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1185#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1186#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1187#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1188#endif
1189#endif
1190
1191// [Apple] OS specific includes
1192#if defined(__APPLE__)
1193#include <TargetConditionals.h>
1194#endif
1195
1196// Visual Studio warnings
1197#ifdef _MSC_VER
1198#pragma warning (disable: 4127) // condition expression is constant
1199#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1200#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
1201#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1202#endif
1203#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1204#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1205#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1206#endif
1207
1208// Clang/GCC warnings with -Weverything
1209#if defined(__clang__)
1210#if __has_warning("-Wunknown-warning-option")
1211#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1212#endif
1213#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1214#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1215#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1216#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int'
1217#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1218#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1219#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1220#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1221#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1222#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1223#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1224#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1225#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1226#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
1227#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
1228#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
1229#elif defined(__GNUC__)
1230// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1231#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1232#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1233#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1234#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
1235#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
1236#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1237#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1238#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1239#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1240#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1241#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
1242#endif
1243
1244// Debug options
1245#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
1246#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1247
1248// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls.
1249static const float FONT_DEFAULT_SIZE = 20.0f;
1250
1251// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1252static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1253static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1254static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut.
1255static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1256static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1257
1258// Tooltip offset
1259static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1260static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale
1261static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale
1262
1263// Docking
1264static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1265
1266//-------------------------------------------------------------------------
1267// [SECTION] FORWARD DECLARATIONS
1268//-------------------------------------------------------------------------
1269
1270static void SetCurrentWindow(ImGuiWindow* window);
1271static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1272static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1273
1274static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1275
1276// Settings
1277static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1278static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1279static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1280static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1281static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1282
1283// Platform Dependents default implementation for ImGuiPlatformIO functions
1284static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx);
1285static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text);
1286static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1287static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1288
1289namespace ImGui
1290{
1291// Item
1292static void ItemHandleShortcut(ImGuiID id);
1293
1294// Window Focus
1295static int FindWindowFocusIndex(ImGuiWindow* window);
1296static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags);
1297
1298// Navigation
1299static void NavUpdate();
1300static void NavUpdateWindowing();
1301static void NavUpdateWindowingApplyFocus(ImGuiWindow* window);
1302static void NavUpdateWindowingOverlay();
1303static void NavUpdateCancelRequest();
1304static void NavUpdateCreateMoveRequest();
1305static void NavUpdateCreateTabbingRequest();
1306static float NavUpdatePageUpPageDown();
1307static inline void NavUpdateAnyRequestFlag();
1308static void NavUpdateCreateWrappingRequest();
1309static void NavEndFrame();
1310static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb);
1311static void NavApplyItemToResult(ImGuiNavItemData* result);
1312static void NavProcessItem();
1313static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1314static ImGuiInputSource NavCalcPreferredRefPosSource();
1315static ImVec2 NavCalcPreferredRefPos();
1316static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1317static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1318static void NavRestoreLayer(ImGuiNavLayer layer);
1319
1320// Error Checking and Debug Tools
1321static void ErrorCheckNewFrameSanityChecks();
1322static void ErrorCheckEndFrameSanityChecks();
1323#ifndef IMGUI_DISABLE_DEBUG_TOOLS
1324static void UpdateDebugToolItemPicker();
1325static void UpdateDebugToolStackQueries();
1326static void UpdateDebugToolFlashStyleColor();
1327#endif
1328
1329// Inputs
1330static void UpdateKeyboardInputs();
1331static void UpdateMouseInputs();
1332static void UpdateMouseWheel();
1333static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1334
1335// Misc
1336static void UpdateFontsNewFrame();
1337static void UpdateFontsEndFrame();
1338static void UpdateTexturesNewFrame();
1339static void UpdateTexturesEndFrame();
1340static void UpdateSettings();
1341static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1342static void RenderWindowOuterBorders(ImGuiWindow* window);
1343static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1344static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1345static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1346static void RenderDimmedBackgrounds();
1347static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1348static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect);
1349
1350// Viewports
1351const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1352static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1353static void DestroyViewport(ImGuiViewportP* viewport);
1354static void UpdateViewportsNewFrame();
1355static void UpdateViewportsEndFrame();
1356static void WindowSelectViewport(ImGuiWindow* window);
1357static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1358static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1359static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1360static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1361static int FindPlatformMonitorForPos(const ImVec2& pos);
1362static int FindPlatformMonitorForRect(const ImRect& r);
1363static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1364
1365}
1366
1367//-----------------------------------------------------------------------------
1368// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1369//-----------------------------------------------------------------------------
1370
1371// DLL users:
1372// - Heaps and globals are not shared across DLL boundaries!
1373// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1374// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1375// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1376// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1377
1378// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1379// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1380// Change to a different context by calling ImGui::SetCurrentContext().
1381// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1382// If you want thread-safety to allow N threads to access N different contexts:
1383// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1384// struct ImGuiContext;
1385// extern thread_local ImGuiContext* MyImGuiTLS;
1386// #define GImGui MyImGuiTLS
1387// And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1388// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1389// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1390// - DLL users: read comments above.
1391#ifndef GImGui
1392ImGuiContext* GImGui = NULL;
1393#endif
1394
1395// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1396// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1397// - DLL users: read comments above.
1398#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1399static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size: size); }
1400static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr: ptr); }
1401#else
1402static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1403static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1404#endif
1405static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1406static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1407static void* GImAllocatorUserData = NULL;
1408
1409//-----------------------------------------------------------------------------
1410// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO)
1411//-----------------------------------------------------------------------------
1412
1413ImGuiStyle::ImGuiStyle()
1414{
1415 FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame.
1416 FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user.
1417 FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI.
1418
1419 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1420 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1421 WindowPadding = ImVec2(8,8); // Padding within a window
1422 WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1423 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1424 WindowBorderHoverPadding = 4.0f; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders.
1425 WindowMinSize = ImVec2(32,32); // Minimum window size
1426 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1427 WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1428 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1429 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1430 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1431 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1432 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1433 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1434 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1435 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1436 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1437 CellPadding = ImVec2(4,2); // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1438 TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1439 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1440 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1441 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1442 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1443 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1444 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1445 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1446 ImageBorderSize = 0.0f; // Thickness of border around tabs.
1447 TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1448 TabBorderSize = 0.0f; // Thickness of border around tabs.
1449 TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected.
1450 TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy.
1451 TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width.
1452 TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected.
1453 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1454 TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar.
1455 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1456 TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1457 TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone;
1458 TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines.
1459 TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line.
1460 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1461 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1462 SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1463 SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText()
1464 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1465 SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1466 DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1467 DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1468 DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows
1469 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1470 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1471 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1472 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1473 CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1474 CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1475
1476 // Behaviors
1477 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1478 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1479 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1480 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1481 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1482
1483 // [Internal]
1484 _MainScale = 1.0f;
1485 _NextFrameFontSizeBase = 0.0f;
1486
1487 // Default theme
1488 ImGui::StyleColorsDark(dst: this);
1489}
1490
1491
1492// Scale all spacing/padding/thickness values. Do not scale fonts.
1493// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1494void ImGuiStyle::ScaleAllSizes(float scale_factor)
1495{
1496 _MainScale *= scale_factor;
1497 WindowPadding = ImTrunc(v: WindowPadding * scale_factor);
1498 WindowRounding = ImTrunc(f: WindowRounding * scale_factor);
1499 WindowMinSize = ImTrunc(v: WindowMinSize * scale_factor);
1500 WindowBorderHoverPadding = ImTrunc(f: WindowBorderHoverPadding * scale_factor);
1501 ChildRounding = ImTrunc(f: ChildRounding * scale_factor);
1502 PopupRounding = ImTrunc(f: PopupRounding * scale_factor);
1503 FramePadding = ImTrunc(v: FramePadding * scale_factor);
1504 FrameRounding = ImTrunc(f: FrameRounding * scale_factor);
1505 ItemSpacing = ImTrunc(v: ItemSpacing * scale_factor);
1506 ItemInnerSpacing = ImTrunc(v: ItemInnerSpacing * scale_factor);
1507 CellPadding = ImTrunc(v: CellPadding * scale_factor);
1508 TouchExtraPadding = ImTrunc(v: TouchExtraPadding * scale_factor);
1509 IndentSpacing = ImTrunc(f: IndentSpacing * scale_factor);
1510 ColumnsMinSpacing = ImTrunc(f: ColumnsMinSpacing * scale_factor);
1511 ScrollbarSize = ImTrunc(f: ScrollbarSize * scale_factor);
1512 ScrollbarRounding = ImTrunc(f: ScrollbarRounding * scale_factor);
1513 GrabMinSize = ImTrunc(f: GrabMinSize * scale_factor);
1514 GrabRounding = ImTrunc(f: GrabRounding * scale_factor);
1515 LogSliderDeadzone = ImTrunc(f: LogSliderDeadzone * scale_factor);
1516 ImageBorderSize = ImTrunc(f: ImageBorderSize * scale_factor);
1517 TabRounding = ImTrunc(f: TabRounding * scale_factor);
1518 TabMinWidthBase = ImTrunc(f: TabMinWidthBase * scale_factor);
1519 TabMinWidthShrink = ImTrunc(f: TabMinWidthShrink * scale_factor);
1520 TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(f: TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected;
1521 TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(f: TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected;
1522 TabBarOverlineSize = ImTrunc(f: TabBarOverlineSize * scale_factor);
1523 TreeLinesRounding = ImTrunc(f: TreeLinesRounding * scale_factor);
1524 SeparatorTextPadding = ImTrunc(v: SeparatorTextPadding * scale_factor);
1525 DockingSeparatorSize = ImTrunc(f: DockingSeparatorSize * scale_factor);
1526 DisplayWindowPadding = ImTrunc(v: DisplayWindowPadding * scale_factor);
1527 DisplaySafeAreaPadding = ImTrunc(v: DisplaySafeAreaPadding * scale_factor);
1528 MouseCursorScale = ImTrunc(f: MouseCursorScale * scale_factor);
1529}
1530
1531ImGuiIO::ImGuiIO()
1532{
1533 // Most fields are initialized with zero
1534 memset(s: this, c: 0, n: sizeof(*this));
1535 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1536
1537 // Settings
1538 ConfigFlags = ImGuiConfigFlags_None;
1539 BackendFlags = ImGuiBackendFlags_None;
1540 DisplaySize = ImVec2(-1.0f, -1.0f);
1541 DeltaTime = 1.0f / 60.0f;
1542 IniSavingRate = 5.0f;
1543 IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1544 LogFilename = "imgui_log.txt";
1545 UserData = NULL;
1546
1547 Fonts = NULL;
1548 FontDefault = NULL;
1549 FontAllowUserScaling = false;
1550#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1551 FontGlobalScale = 1.0f; // Use style.FontScaleMain instead!
1552#endif
1553 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1554
1555 // Keyboard/Gamepad Navigation options
1556 ConfigNavSwapGamepadButtons = false;
1557 ConfigNavMoveSetMousePos = false;
1558 ConfigNavCaptureKeyboard = true;
1559 ConfigNavEscapeClearFocusItem = true;
1560 ConfigNavEscapeClearFocusWindow = false;
1561 ConfigNavCursorVisibleAuto = true;
1562 ConfigNavCursorVisibleAlways = false;
1563
1564 // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1565 ConfigDockingNoSplit = false;
1566 ConfigDockingWithShift = false;
1567 ConfigDockingAlwaysTabBar = false;
1568 ConfigDockingTransparentPayload = false;
1569
1570 // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1571 ConfigViewportsNoAutoMerge = false;
1572 ConfigViewportsNoTaskBarIcon = false;
1573 ConfigViewportsNoDecoration = true;
1574 ConfigViewportsNoDefaultParent = false;
1575 ConfigViewportPlatformFocusSetsImGuiFocus = true;
1576
1577 // Miscellaneous options
1578 MouseDrawCursor = false;
1579#ifdef __APPLE__
1580 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1581#else
1582 ConfigMacOSXBehaviors = false;
1583#endif
1584 ConfigInputTrickleEventQueue = true;
1585 ConfigInputTextCursorBlink = true;
1586 ConfigInputTextEnterKeepActive = false;
1587 ConfigDragClickToInputText = false;
1588 ConfigWindowsResizeFromEdges = true;
1589 ConfigWindowsMoveFromTitleBarOnly = false;
1590 ConfigWindowsCopyContentsWithCtrlC = false;
1591 ConfigScrollbarScrollByPage = true;
1592 ConfigMemoryCompactTimer = 60.0f;
1593 ConfigDebugIsDebuggerPresent = false;
1594 ConfigDebugHighlightIdConflicts = true;
1595 ConfigDebugHighlightIdConflictsShowItemPicker = true;
1596 ConfigDebugBeginReturnValueOnce = false;
1597 ConfigDebugBeginReturnValueLoop = false;
1598
1599 ConfigErrorRecovery = true;
1600 ConfigErrorRecoveryEnableAssert = true;
1601 ConfigErrorRecoveryEnableDebugLog = true;
1602 ConfigErrorRecoveryEnableTooltip = true;
1603
1604 // Inputs Behaviors
1605 MouseDoubleClickTime = 0.30f;
1606 MouseDoubleClickMaxDist = 6.0f;
1607 MouseDragThreshold = 6.0f;
1608 KeyRepeatDelay = 0.275f;
1609 KeyRepeatRate = 0.050f;
1610
1611 // Platform Functions
1612 // Note: Initialize() will setup default clipboard/ime handlers.
1613 BackendPlatformName = BackendRendererName = NULL;
1614 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1615
1616 // Input (NB: we already have memset zero the entire structure!)
1617 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1618 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1619 MouseSource = ImGuiMouseSource_Mouse;
1620 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1621 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1622 AppAcceptingEvents = true;
1623}
1624
1625// Pass in translated ASCII characters for text input.
1626// - with glfw you can get those from the callback set in glfwSetCharCallback()
1627// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1628// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1629void ImGuiIO::AddInputCharacter(unsigned int c)
1630{
1631 IM_ASSERT(Ctx != NULL);
1632 ImGuiContext& g = *Ctx;
1633 if (c == 0 || !AppAcceptingEvents)
1634 return;
1635
1636 ImGuiInputEvent e;
1637 e.Type = ImGuiInputEventType_Text;
1638 e.Source = ImGuiInputSource_Keyboard;
1639 e.EventId = g.InputEventsNextEventId++;
1640 e.Text.Char = c;
1641 g.InputEventsQueue.push_back(v: e);
1642}
1643
1644// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1645// we should save the high surrogate.
1646void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1647{
1648 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1649 return;
1650
1651 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1652 {
1653 if (InputQueueSurrogate != 0)
1654 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1655 InputQueueSurrogate = c;
1656 return;
1657 }
1658
1659 ImWchar cp = c;
1660 if (InputQueueSurrogate != 0)
1661 {
1662 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1663 {
1664 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1665 }
1666 else
1667 {
1668#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1669 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1670#else
1671 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1672#endif
1673 }
1674
1675 InputQueueSurrogate = 0;
1676 }
1677 AddInputCharacter(c: (unsigned)cp);
1678}
1679
1680void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1681{
1682 if (!AppAcceptingEvents)
1683 return;
1684 while (*utf8_chars != 0)
1685 {
1686 unsigned int c = 0;
1687 utf8_chars += ImTextCharFromUtf8(out_char: &c, in_text: utf8_chars, NULL);
1688 AddInputCharacter(c);
1689 }
1690}
1691
1692// Clear all incoming events.
1693void ImGuiIO::ClearEventsQueue()
1694{
1695 IM_ASSERT(Ctx != NULL);
1696 ImGuiContext& g = *Ctx;
1697 g.InputEventsQueue.clear();
1698}
1699
1700// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1701void ImGuiIO::ClearInputKeys()
1702{
1703 ImGuiContext& g = *Ctx;
1704 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
1705 {
1706 if (ImGui::IsMouseKey(key: (ImGuiKey)key))
1707 continue;
1708 ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
1709 key_data->Down = false;
1710 key_data->DownDuration = -1.0f;
1711 key_data->DownDurationPrev = -1.0f;
1712 }
1713 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1714 KeyMods = ImGuiMod_None;
1715 InputQueueCharacters.resize(new_size: 0); // Behavior of old ClearInputCharacters().
1716}
1717
1718void ImGuiIO::ClearInputMouse()
1719{
1720 for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1721 {
1722 ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
1723 key_data->Down = false;
1724 key_data->DownDuration = -1.0f;
1725 key_data->DownDurationPrev = -1.0f;
1726 }
1727 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1728 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1729 {
1730 MouseDown[n] = false;
1731 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1732 }
1733 MouseWheel = MouseWheelH = 0.0f;
1734}
1735
1736// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1737// Current frame character buffer is now also cleared by ClearInputKeys().
1738#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1739void ImGuiIO::ClearInputCharacters()
1740{
1741 InputQueueCharacters.resize(new_size: 0);
1742}
1743#endif
1744
1745static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1746{
1747 ImGuiContext& g = *ctx;
1748 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1749 {
1750 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1751 if (e->Type != type)
1752 continue;
1753 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1754 continue;
1755 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1756 continue;
1757 return e;
1758 }
1759 return NULL;
1760}
1761
1762// Queue a new key down/up event.
1763// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1764// - bool down: Is the key down? use false to signify a key release.
1765// - float analog_value: 0.0f..1.0f
1766// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1767// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1768void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1769{
1770 //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1771 IM_ASSERT(Ctx != NULL);
1772 if (key == ImGuiKey_None || !AppAcceptingEvents)
1773 return;
1774 ImGuiContext& g = *Ctx;
1775 IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1776 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1777
1778 // MacOS: swap Cmd(Super) and Ctrl
1779 if (g.IO.ConfigMacOSXBehaviors)
1780 {
1781 if (key == ImGuiMod_Super) { key = ImGuiMod_Ctrl; }
1782 else if (key == ImGuiMod_Ctrl) { key = ImGuiMod_Super; }
1783 else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1784 else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1785 else if (key == ImGuiKey_LeftCtrl) { key = ImGuiKey_LeftSuper; }
1786 else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1787 }
1788
1789 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1790 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)key);
1791 const ImGuiKeyData* key_data = ImGui::GetKeyData(ctx: &g, key);
1792 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1793 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1794 if (latest_key_down == down && latest_key_analog == analog_value)
1795 return;
1796
1797 // Add event
1798 ImGuiInputEvent e;
1799 e.Type = ImGuiInputEventType_Key;
1800 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1801 e.EventId = g.InputEventsNextEventId++;
1802 e.Key.Key = key;
1803 e.Key.Down = down;
1804 e.Key.AnalogValue = analog_value;
1805 g.InputEventsQueue.push_back(v: e);
1806}
1807
1808void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1809{
1810 if (!AppAcceptingEvents)
1811 return;
1812 AddKeyAnalogEvent(key, down, analog_value: down ? 1.0f : 0.0f);
1813}
1814
1815// [Optional] Call after AddKeyEvent().
1816// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1817// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1818void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1819{
1820 if (key == ImGuiKey_None)
1821 return;
1822 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1823 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1824 IM_UNUSED(key); // Yet unused
1825 IM_UNUSED(native_keycode); // Yet unused
1826 IM_UNUSED(native_scancode); // Yet unused
1827 IM_UNUSED(native_legacy_index); // Yet unused
1828}
1829
1830// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1831void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1832{
1833 AppAcceptingEvents = accepting_events;
1834}
1835
1836// Queue a mouse move event
1837void ImGuiIO::AddMousePosEvent(float x, float y)
1838{
1839 IM_ASSERT(Ctx != NULL);
1840 ImGuiContext& g = *Ctx;
1841 if (!AppAcceptingEvents)
1842 return;
1843
1844 // Apply same flooring as UpdateMouseInputs()
1845 ImVec2 pos((x > -FLT_MAX) ? ImFloor(f: x) : x, (y > -FLT_MAX) ? ImFloor(f: y) : y);
1846
1847 // Filter duplicate
1848 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MousePos);
1849 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1850 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1851 return;
1852
1853 ImGuiInputEvent e;
1854 e.Type = ImGuiInputEventType_MousePos;
1855 e.Source = ImGuiInputSource_Mouse;
1856 e.EventId = g.InputEventsNextEventId++;
1857 e.MousePos.PosX = pos.x;
1858 e.MousePos.PosY = pos.y;
1859 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1860 g.InputEventsQueue.push_back(v: e);
1861}
1862
1863void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1864{
1865 IM_ASSERT(Ctx != NULL);
1866 ImGuiContext& g = *Ctx;
1867 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1868 if (!AppAcceptingEvents)
1869 return;
1870
1871 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1872 if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1873 {
1874 // Order of both statements matters: this event will still release mouse button 1
1875 mouse_button = 1;
1876 if (!down)
1877 MouseCtrlLeftAsRightClick = false;
1878 }
1879
1880 // Filter duplicate
1881 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseButton, arg: (int)mouse_button);
1882 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1883 if (latest_button_down == down)
1884 return;
1885
1886 // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1887 // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1888 // - At this point we want from !down to down, so this is handling the initial press.
1889 if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1890 {
1891 const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)ImGuiMod_Super);
1892 if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1893 {
1894 IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1895 MouseCtrlLeftAsRightClick = true;
1896 AddMouseButtonEvent(mouse_button: 1, down: true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1897 return;
1898 }
1899 }
1900
1901 ImGuiInputEvent e;
1902 e.Type = ImGuiInputEventType_MouseButton;
1903 e.Source = ImGuiInputSource_Mouse;
1904 e.EventId = g.InputEventsNextEventId++;
1905 e.MouseButton.Button = mouse_button;
1906 e.MouseButton.Down = down;
1907 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1908 g.InputEventsQueue.push_back(v: e);
1909}
1910
1911// Queue a mouse wheel event (some mouse/API may only have a Y component)
1912void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1913{
1914 IM_ASSERT(Ctx != NULL);
1915 ImGuiContext& g = *Ctx;
1916
1917 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1918 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1919 return;
1920
1921 ImGuiInputEvent e;
1922 e.Type = ImGuiInputEventType_MouseWheel;
1923 e.Source = ImGuiInputSource_Mouse;
1924 e.EventId = g.InputEventsNextEventId++;
1925 e.MouseWheel.WheelX = wheel_x;
1926 e.MouseWheel.WheelY = wheel_y;
1927 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1928 g.InputEventsQueue.push_back(v: e);
1929}
1930
1931// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1932// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1933void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1934{
1935 IM_ASSERT(Ctx != NULL);
1936 ImGuiContext& g = *Ctx;
1937 g.InputEventsNextMouseSource = source;
1938}
1939
1940void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1941{
1942 IM_ASSERT(Ctx != NULL);
1943 ImGuiContext& g = *Ctx;
1944 //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1945 if (!AppAcceptingEvents)
1946 return;
1947
1948 // Filter duplicate
1949 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseViewport);
1950 const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1951 if (latest_viewport_id == viewport_id)
1952 return;
1953
1954 ImGuiInputEvent e;
1955 e.Type = ImGuiInputEventType_MouseViewport;
1956 e.Source = ImGuiInputSource_Mouse;
1957 e.MouseViewport.HoveredViewportID = viewport_id;
1958 g.InputEventsQueue.push_back(v: e);
1959}
1960
1961void ImGuiIO::AddFocusEvent(bool focused)
1962{
1963 IM_ASSERT(Ctx != NULL);
1964 ImGuiContext& g = *Ctx;
1965
1966 // Filter duplicate
1967 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Focus);
1968 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1969 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1970 return;
1971
1972 ImGuiInputEvent e;
1973 e.Type = ImGuiInputEventType_Focus;
1974 e.EventId = g.InputEventsNextEventId++;
1975 e.AppFocused.Focused = focused;
1976 g.InputEventsQueue.push_back(v: e);
1977}
1978
1979ImGuiPlatformIO::ImGuiPlatformIO()
1980{
1981 // Most fields are initialized with zero
1982 memset(s: this, c: 0, n: sizeof(*this));
1983 Platform_LocaleDecimalPoint = '.';
1984}
1985
1986//-----------------------------------------------------------------------------
1987// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1988//-----------------------------------------------------------------------------
1989
1990ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1991{
1992 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1993 ImVec2 p_last = p1;
1994 ImVec2 p_closest;
1995 float p_closest_dist2 = FLT_MAX;
1996 float t_step = 1.0f / (float)num_segments;
1997 for (int i_step = 1; i_step <= num_segments; i_step++)
1998 {
1999 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t: t_step * i_step);
2000 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
2001 float dist2 = ImLengthSqr(lhs: p - p_line);
2002 if (dist2 < p_closest_dist2)
2003 {
2004 p_closest = p_line;
2005 p_closest_dist2 = dist2;
2006 }
2007 p_last = p_current;
2008 }
2009 return p_closest;
2010}
2011
2012// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
2013static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
2014{
2015 float dx = x4 - x1;
2016 float dy = y4 - y1;
2017 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
2018 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
2019 d2 = (d2 >= 0) ? d2 : -d2;
2020 d3 = (d3 >= 0) ? d3 : -d3;
2021 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
2022 {
2023 ImVec2 p_current(x4, y4);
2024 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
2025 float dist2 = ImLengthSqr(lhs: p - p_line);
2026 if (dist2 < p_closest_dist2)
2027 {
2028 p_closest = p_line;
2029 p_closest_dist2 = dist2;
2030 }
2031 p_last = p_current;
2032 }
2033 else if (level < 10)
2034 {
2035 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
2036 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
2037 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
2038 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
2039 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
2040 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
2041 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x2: x12, y2: y12, x3: x123, y3: y123, x4: x1234, y4: y1234, tess_tol, level: level + 1);
2042 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: x1234, y1: y1234, x2: x234, y2: y234, x3: x34, y3: y34, x4, y4, tess_tol, level: level + 1);
2043 }
2044}
2045
2046// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
2047// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
2048ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
2049{
2050 IM_ASSERT(tess_tol > 0.0f);
2051 ImVec2 p_last = p1;
2052 ImVec2 p_closest;
2053 float p_closest_dist2 = FLT_MAX;
2054 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y, x3: p3.x, y3: p3.y, x4: p4.x, y4: p4.y, tess_tol, level: 0);
2055 return p_closest;
2056}
2057
2058ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
2059{
2060 ImVec2 ap = p - a;
2061 ImVec2 ab_dir = b - a;
2062 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
2063 if (dot < 0.0f)
2064 return a;
2065 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
2066 if (dot > ab_len_sqr)
2067 return b;
2068 return a + ab_dir * dot / ab_len_sqr;
2069}
2070
2071bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2072{
2073 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
2074 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
2075 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
2076 return ((b1 == b2) && (b2 == b3));
2077}
2078
2079void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
2080{
2081 ImVec2 v0 = b - a;
2082 ImVec2 v1 = c - a;
2083 ImVec2 v2 = p - a;
2084 const float denom = v0.x * v1.y - v1.x * v0.y;
2085 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
2086 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
2087 out_u = 1.0f - out_v - out_w;
2088}
2089
2090ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
2091{
2092 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
2093 ImVec2 proj_bc = ImLineClosestPoint(a: b, b: c, p);
2094 ImVec2 proj_ca = ImLineClosestPoint(a: c, b: a, p);
2095 float dist2_ab = ImLengthSqr(lhs: p - proj_ab);
2096 float dist2_bc = ImLengthSqr(lhs: p - proj_bc);
2097 float dist2_ca = ImLengthSqr(lhs: p - proj_ca);
2098 float m = ImMin(lhs: dist2_ab, rhs: ImMin(lhs: dist2_bc, rhs: dist2_ca));
2099 if (m == dist2_ab)
2100 return proj_ab;
2101 if (m == dist2_bc)
2102 return proj_bc;
2103 return proj_ca;
2104}
2105
2106//-----------------------------------------------------------------------------
2107// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
2108//-----------------------------------------------------------------------------
2109
2110// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
2111int ImStricmp(const char* str1, const char* str2)
2112{
2113 int d;
2114 while ((d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; }
2115 return d;
2116}
2117
2118int ImStrnicmp(const char* str1, const char* str2, size_t count)
2119{
2120 int d = 0;
2121 while (count > 0 && (d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; count--; }
2122 return d;
2123}
2124
2125void ImStrncpy(char* dst, const char* src, size_t count)
2126{
2127 if (count < 1)
2128 return;
2129 if (count > 1)
2130 strncpy(dest: dst, src: src, n: count - 1);
2131 dst[count - 1] = 0;
2132}
2133
2134char* ImStrdup(const char* str)
2135{
2136 size_t len = ImStrlen(s: str);
2137 void* buf = IM_ALLOC(len + 1);
2138 return (char*)memcpy(dest: buf, src: (const void*)str, n: len + 1);
2139}
2140
2141void* ImMemdup(const void* src, size_t size)
2142{
2143 void* dst = IM_ALLOC(size);
2144 return memcpy(dest: dst, src: src, n: size);
2145}
2146
2147char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
2148{
2149 size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(s: dst) + 1;
2150 size_t src_size = ImStrlen(s: src) + 1;
2151 if (dst_buf_size < src_size)
2152 {
2153 IM_FREE(dst);
2154 dst = (char*)IM_ALLOC(src_size);
2155 if (p_dst_size)
2156 *p_dst_size = src_size;
2157 }
2158 return (char*)memcpy(dest: dst, src: (const void*)src, n: src_size);
2159}
2160
2161const char* ImStrchrRange(const char* str, const char* str_end, char c)
2162{
2163 const char* p = (const char*)ImMemchr(s: str, c: (int)c, n: str_end - str);
2164 return p;
2165}
2166
2167int ImStrlenW(const ImWchar* str)
2168{
2169 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
2170 int n = 0;
2171 while (*str++) n++;
2172 return n;
2173}
2174
2175// Find end-of-line. Return pointer will point to either first \n, either str_end.
2176const char* ImStreolRange(const char* str, const char* str_end)
2177{
2178 const char* p = (const char*)ImMemchr(s: str, c: '\n', n: str_end - str);
2179 return p ? p : str_end;
2180}
2181
2182const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
2183{
2184 IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin));
2185 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2186 buf_mid_line--;
2187 return buf_mid_line;
2188}
2189
2190const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2191{
2192 if (!needle_end)
2193 needle_end = needle + ImStrlen(s: needle);
2194
2195 const char un0 = (char)ImToUpper(c: *needle);
2196 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2197 {
2198 if (ImToUpper(c: *haystack) == un0)
2199 {
2200 const char* b = needle + 1;
2201 for (const char* a = haystack + 1; b < needle_end; a++, b++)
2202 if (ImToUpper(c: *a) != ImToUpper(c: *b))
2203 break;
2204 if (b == needle_end)
2205 return haystack;
2206 }
2207 haystack++;
2208 }
2209 return NULL;
2210}
2211
2212// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2213void ImStrTrimBlanks(char* buf)
2214{
2215 char* p = buf;
2216 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
2217 p++;
2218 char* p_start = p;
2219 while (*p != 0) // Find end of string
2220 p++;
2221 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
2222 p--;
2223 if (p_start != buf) // Copy memory if we had leading blanks
2224 memmove(dest: buf, src: p_start, n: p - p_start);
2225 buf[p - p_start] = 0; // Zero terminate
2226}
2227
2228const char* ImStrSkipBlank(const char* str)
2229{
2230 while (str[0] == ' ' || str[0] == '\t')
2231 str++;
2232 return str;
2233}
2234
2235// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2236// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2237// B) When buf==NULL vsnprintf() will return the output size.
2238#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2239
2240// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2241// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2242// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2243// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2244#ifdef IMGUI_USE_STB_SPRINTF
2245#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2246#define STB_SPRINTF_IMPLEMENTATION
2247#endif
2248#ifdef IMGUI_STB_SPRINTF_FILENAME
2249#include IMGUI_STB_SPRINTF_FILENAME
2250#else
2251#include "stb_sprintf.h"
2252#endif
2253#endif // #ifdef IMGUI_USE_STB_SPRINTF
2254
2255#if defined(_MSC_VER) && !defined(vsnprintf)
2256#define vsnprintf _vsnprintf
2257#endif
2258
2259int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2260{
2261 va_list args;
2262 va_start(args, fmt);
2263#ifdef IMGUI_USE_STB_SPRINTF
2264 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2265#else
2266 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
2267#endif
2268 va_end(args);
2269 if (buf == NULL)
2270 return w;
2271 if (w == -1 || w >= (int)buf_size)
2272 w = (int)buf_size - 1;
2273 buf[w] = 0;
2274 return w;
2275}
2276
2277int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2278{
2279#ifdef IMGUI_USE_STB_SPRINTF
2280 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2281#else
2282 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
2283#endif
2284 if (buf == NULL)
2285 return w;
2286 if (w == -1 || w >= (int)buf_size)
2287 w = (int)buf_size - 1;
2288 buf[w] = 0;
2289 return w;
2290}
2291#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2292
2293void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2294{
2295 va_list args;
2296 va_start(args, fmt);
2297 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2298 va_end(args);
2299}
2300
2301// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2302// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2303// ImGuiTempBufferToken token;
2304// ImFormatStringToTempBuffer(token, ...);
2305void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2306{
2307 ImGuiContext& g = *GImGui;
2308 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2309 {
2310 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2311 if (buf == NULL)
2312 buf = "(null)";
2313 *out_buf = buf;
2314 if (out_buf_end) { *out_buf_end = buf + ImStrlen(s: buf); }
2315 }
2316 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2317 {
2318 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2319 const char* buf = va_arg(args, const char*);
2320 if (buf == NULL)
2321 {
2322 buf = "(null)";
2323 buf_len = ImMin(lhs: buf_len, rhs: 6);
2324 }
2325 *out_buf = buf;
2326 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2327 }
2328 else
2329 {
2330 int buf_len = ImFormatStringV(buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size, fmt, args);
2331 *out_buf = g.TempBuffer.Data;
2332 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2333 }
2334}
2335
2336#ifndef IMGUI_ENABLE_SSE4_2_CRC
2337// CRC32 needs a 1KB lookup table (not cache friendly)
2338// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2339// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2340static const ImU32 GCrc32LookupTable[256] =
2341{
2342#ifdef IMGUI_USE_LEGACY_CRC32_ADLER
2343 // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
2344 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2345 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2346 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2347 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2348 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2349 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2350 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2351 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2352 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2353 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2354 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2355 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2356 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2357 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2358 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2359 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2360#else
2361 // CRC32c table compatible with SSE 4.2 instructions
2362 0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
2363 0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
2364 0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
2365 0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
2366 0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
2367 0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
2368 0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
2369 0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
2370 0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
2371 0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
2372 0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
2373 0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
2374 0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
2375 0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
2376 0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
2377 0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
2378#endif
2379};
2380#endif
2381
2382// Known size hash
2383// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2384// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2385ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2386{
2387 ImU32 crc = ~seed;
2388 const unsigned char* data = (const unsigned char*)data_p;
2389 const unsigned char *data_end = (const unsigned char*)data_p + data_size;
2390#ifndef IMGUI_ENABLE_SSE4_2_CRC
2391 const ImU32* crc32_lut = GCrc32LookupTable;
2392 while (data < data_end)
2393 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2394 return ~crc;
2395#else
2396 while (data + 4 <= data_end)
2397 {
2398 crc = _mm_crc32_u32(crc, *(ImU32*)data);
2399 data += 4;
2400 }
2401 while (data < data_end)
2402 crc = _mm_crc32_u8(crc, *data++);
2403 return ~crc;
2404#endif
2405}
2406
2407// Zero-terminated string hash, with support for ### to reset back to seed value
2408// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2409// Because this syntax is rarely used we are optimizing for the common case.
2410// - If we reach ### in the string we discard the hash so far and reset to the seed.
2411// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2412// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2413ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2414{
2415 seed = ~seed;
2416 ImU32 crc = seed;
2417 const unsigned char* data = (const unsigned char*)data_p;
2418#ifndef IMGUI_ENABLE_SSE4_2_CRC
2419 const ImU32* crc32_lut = GCrc32LookupTable;
2420#endif
2421 if (data_size != 0)
2422 {
2423 while (data_size-- != 0)
2424 {
2425 unsigned char c = *data++;
2426 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2427 crc = seed;
2428#ifndef IMGUI_ENABLE_SSE4_2_CRC
2429 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2430#else
2431 crc = _mm_crc32_u8(crc, c);
2432#endif
2433 }
2434 }
2435 else
2436 {
2437 while (unsigned char c = *data++)
2438 {
2439 if (c == '#' && data[0] == '#' && data[1] == '#')
2440 crc = seed;
2441#ifndef IMGUI_ENABLE_SSE4_2_CRC
2442 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2443#else
2444 crc = _mm_crc32_u8(crc, c);
2445#endif
2446 }
2447 }
2448 return ~crc;
2449}
2450
2451//-----------------------------------------------------------------------------
2452// [SECTION] MISC HELPERS/UTILITIES (File functions)
2453//-----------------------------------------------------------------------------
2454
2455// Default file functions
2456#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2457
2458ImFileHandle ImFileOpen(const char* filename, const char* mode)
2459{
2460#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__)))
2461 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2462 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2463 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2464 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2465
2466 // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2467 // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2468 wchar_t local_temp_stack[FILENAME_MAX];
2469 ImVector<wchar_t> local_temp_heap;
2470 if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2471 local_temp_heap.resize(filename_wsize + mode_wsize);
2472 wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2473 wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2474 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2475 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2476 return ::_wfopen(filename_wbuf, mode_wbuf);
2477#else
2478 return fopen(filename: filename, modes: mode);
2479#endif
2480}
2481
2482// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2483bool ImFileClose(ImFileHandle f) { return fclose(stream: f) == 0; }
2484ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(stream: f)) != -1 && !fseek(stream: f, off: 0, SEEK_END) && (sz = ftell(stream: f)) != -1 && !fseek(stream: f, off: off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2485ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(ptr: data, size: (size_t)sz, n: (size_t)count, stream: f); }
2486ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(ptr: data, size: (size_t)sz, n: (size_t)count, s: f); }
2487#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2488
2489// Helper: Load file content into memory
2490// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2491// This can't really be used with "rt" because fseek size won't match read size.
2492void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2493{
2494 IM_ASSERT(filename && mode);
2495 if (out_file_size)
2496 *out_file_size = 0;
2497
2498 ImFileHandle f;
2499 if ((f = ImFileOpen(filename, mode)) == NULL)
2500 return NULL;
2501
2502 size_t file_size = (size_t)ImFileGetSize(f);
2503 if (file_size == (size_t)-1)
2504 {
2505 ImFileClose(f);
2506 return NULL;
2507 }
2508
2509 void* file_data = IM_ALLOC(file_size + padding_bytes);
2510 if (file_data == NULL)
2511 {
2512 ImFileClose(f);
2513 return NULL;
2514 }
2515 if (ImFileRead(data: file_data, sz: 1, count: file_size, f) != file_size)
2516 {
2517 ImFileClose(f);
2518 IM_FREE(file_data);
2519 return NULL;
2520 }
2521 if (padding_bytes > 0)
2522 memset(s: (void*)(((char*)file_data) + file_size), c: 0, n: (size_t)padding_bytes);
2523
2524 ImFileClose(f);
2525 if (out_file_size)
2526 *out_file_size = file_size;
2527
2528 return file_data;
2529}
2530
2531//-----------------------------------------------------------------------------
2532// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2533//-----------------------------------------------------------------------------
2534
2535IM_MSVC_RUNTIME_CHECKS_OFF
2536
2537// Convert UTF-8 to 32-bit character, process single character input.
2538// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2539// We handle UTF-8 decoding error by skipping forward.
2540int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2541{
2542 static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2543 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2544 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2545 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2546 static const int shifte[] = { 0, 6, 4, 2, 0 };
2547 int len = lengths[*(const unsigned char*)in_text >> 3];
2548 int wanted = len + (len ? 0 : 1);
2549
2550 if (in_text_end == NULL)
2551 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2552
2553 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2554 // so it is fast even with excessive branching.
2555 unsigned char s[4];
2556 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2557 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2558 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2559 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2560
2561 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2562 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2563 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2564 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2565 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2566 *out_char >>= shiftc[len];
2567
2568 // Accumulate the various error conditions.
2569 int e = 0;
2570 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2571 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2572 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve)
2573 e |= (s[1] & 0xc0) >> 2;
2574 e |= (s[2] & 0xc0) >> 4;
2575 e |= (s[3] ) >> 6;
2576 e ^= 0x2a; // top two bits of each tail byte correct?
2577 e >>= shifte[len];
2578
2579 if (e)
2580 {
2581 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2582 // One byte is consumed in case of invalid first byte of in_text.
2583 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2584 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2585 wanted = ImMin(lhs: wanted, rhs: !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2586 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2587 }
2588
2589 return wanted;
2590}
2591
2592int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2593{
2594 ImWchar* buf_out = buf;
2595 ImWchar* buf_end = buf + buf_size;
2596 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2597 {
2598 unsigned int c;
2599 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2600 *buf_out++ = (ImWchar)c;
2601 }
2602 *buf_out = 0;
2603 if (in_text_remaining)
2604 *in_text_remaining = in_text;
2605 return (int)(buf_out - buf);
2606}
2607
2608int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2609{
2610 int char_count = 0;
2611 while ((!in_text_end || in_text < in_text_end) && *in_text)
2612 {
2613 unsigned int c;
2614 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2615 char_count++;
2616 }
2617 return char_count;
2618}
2619
2620// Based on stb_to_utf8() from github.com/nothings/stb/
2621static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2622{
2623 if (c < 0x80)
2624 {
2625 buf[0] = (char)c;
2626 return 1;
2627 }
2628 if (c < 0x800)
2629 {
2630 if (buf_size < 2) return 0;
2631 buf[0] = (char)(0xc0 + (c >> 6));
2632 buf[1] = (char)(0x80 + (c & 0x3f));
2633 return 2;
2634 }
2635 if (c < 0x10000)
2636 {
2637 if (buf_size < 3) return 0;
2638 buf[0] = (char)(0xe0 + (c >> 12));
2639 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2640 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2641 return 3;
2642 }
2643 if (c <= 0x10FFFF)
2644 {
2645 if (buf_size < 4) return 0;
2646 buf[0] = (char)(0xf0 + (c >> 18));
2647 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2648 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2649 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2650 return 4;
2651 }
2652 // Invalid code point, the max unicode is 0x10FFFF
2653 return 0;
2654}
2655
2656int ImTextCharToUtf8(char out_buf[5], unsigned int c)
2657{
2658 int count = ImTextCharToUtf8_inline(buf: out_buf, buf_size: 5, c);
2659 out_buf[count] = 0;
2660 return count;
2661}
2662
2663// Not optimal but we very rarely use this function.
2664int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2665{
2666 unsigned int unused = 0;
2667 return ImTextCharFromUtf8(out_char: &unused, in_text, in_text_end);
2668}
2669
2670static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2671{
2672 if (c < 0x80) return 1;
2673 if (c < 0x800) return 2;
2674 if (c < 0x10000) return 3;
2675 if (c <= 0x10FFFF) return 4;
2676 return 3;
2677}
2678
2679int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2680{
2681 char* buf_p = out_buf;
2682 const char* buf_end = out_buf + out_buf_size;
2683 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2684 {
2685 unsigned int c = (unsigned int)(*in_text++);
2686 if (c < 0x80)
2687 *buf_p++ = (char)c;
2688 else
2689 buf_p += ImTextCharToUtf8_inline(buf: buf_p, buf_size: (int)(buf_end - buf_p - 1), c);
2690 }
2691 *buf_p = 0;
2692 return (int)(buf_p - out_buf);
2693}
2694
2695int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2696{
2697 int bytes_count = 0;
2698 while ((!in_text_end || in_text < in_text_end) && *in_text)
2699 {
2700 unsigned int c = (unsigned int)(*in_text++);
2701 if (c < 0x80)
2702 bytes_count++;
2703 else
2704 bytes_count += ImTextCountUtf8BytesFromChar(c);
2705 }
2706 return bytes_count;
2707}
2708
2709const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2710{
2711 while (in_text_curr > in_text_start)
2712 {
2713 in_text_curr--;
2714 if ((*in_text_curr & 0xC0) != 0x80)
2715 return in_text_curr;
2716 }
2717 return in_text_start;
2718}
2719
2720int ImTextCountLines(const char* in_text, const char* in_text_end)
2721{
2722 if (in_text_end == NULL)
2723 in_text_end = in_text + ImStrlen(s: in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2724 int count = 0;
2725 while (in_text < in_text_end)
2726 {
2727 const char* line_end = (const char*)ImMemchr(s: in_text, c: '\n', n: in_text_end - in_text);
2728 in_text = line_end ? line_end + 1 : in_text_end;
2729 count++;
2730 }
2731 return count;
2732}
2733
2734IM_MSVC_RUNTIME_CHECKS_RESTORE
2735
2736//-----------------------------------------------------------------------------
2737// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2738// Note: The Convert functions are early design which are not consistent with other API.
2739//-----------------------------------------------------------------------------
2740
2741IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2742{
2743 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2744 int r = ImLerp(a: (int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2745 int g = ImLerp(a: (int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2746 int b = ImLerp(a: (int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2747 return IM_COL32(r, g, b, 0xFF);
2748}
2749
2750ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2751{
2752 float s = 1.0f / 255.0f;
2753 return ImVec4(
2754 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2755 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2756 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2757 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2758}
2759
2760ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2761{
2762 ImU32 out;
2763 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2764 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2765 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2766 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2767 return out;
2768}
2769
2770// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2771// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2772void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2773{
2774 float K = 0.f;
2775 if (g < b)
2776 {
2777 ImSwap(a&: g, b);
2778 K = -1.f;
2779 }
2780 if (r < g)
2781 {
2782 ImSwap(a&: r, b&: g);
2783 K = -2.f / 6.f - K;
2784 }
2785
2786 const float chroma = r - (g < b ? g : b);
2787 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2788 out_s = chroma / (r + 1e-20f);
2789 out_v = r;
2790}
2791
2792// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2793// also http://en.wikipedia.org/wiki/HSL_and_HSV
2794void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2795{
2796 if (s == 0.0f)
2797 {
2798 // gray
2799 out_r = out_g = out_b = v;
2800 return;
2801 }
2802
2803 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2804 int i = (int)h;
2805 float f = h - (float)i;
2806 float p = v * (1.0f - s);
2807 float q = v * (1.0f - s * f);
2808 float t = v * (1.0f - s * (1.0f - f));
2809
2810 switch (i)
2811 {
2812 case 0: out_r = v; out_g = t; out_b = p; break;
2813 case 1: out_r = q; out_g = v; out_b = p; break;
2814 case 2: out_r = p; out_g = v; out_b = t; break;
2815 case 3: out_r = p; out_g = q; out_b = v; break;
2816 case 4: out_r = t; out_g = p; out_b = v; break;
2817 case 5: default: out_r = v; out_g = p; out_b = q; break;
2818 }
2819}
2820
2821//-----------------------------------------------------------------------------
2822// [SECTION] ImGuiStorage
2823// Helper: Key->value storage
2824//-----------------------------------------------------------------------------
2825
2826// std::lower_bound but without the bullshit
2827ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2828{
2829 ImGuiStoragePair* in_p = in_begin;
2830 for (size_t count = (size_t)(in_end - in_p); count > 0; )
2831 {
2832 size_t count2 = count >> 1;
2833 ImGuiStoragePair* mid = in_p + count2;
2834 if (mid->key < key)
2835 {
2836 in_p = ++mid;
2837 count -= count2 + 1;
2838 }
2839 else
2840 {
2841 count = count2;
2842 }
2843 }
2844 return in_p;
2845}
2846
2847IM_MSVC_RUNTIME_CHECKS_OFF
2848static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2849{
2850 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2851 ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2852 ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2853 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2854}
2855
2856// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2857void ImGuiStorage::BuildSortByKey()
2858{
2859 ImQsort(base: Data.Data, count: (size_t)Data.Size, size_of_element: sizeof(ImGuiStoragePair), compare_func: PairComparerByID);
2860}
2861
2862int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2863{
2864 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2865 if (it == Data.Data + Data.Size || it->key != key)
2866 return default_val;
2867 return it->val_i;
2868}
2869
2870bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2871{
2872 return GetInt(key, default_val: default_val ? 1 : 0) != 0;
2873}
2874
2875float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2876{
2877 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2878 if (it == Data.Data + Data.Size || it->key != key)
2879 return default_val;
2880 return it->val_f;
2881}
2882
2883void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2884{
2885 ImGuiStoragePair* it = ImLowerBound(in_begin: const_cast<ImGuiStoragePair*>(Data.Data), in_end: const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2886 if (it == Data.Data + Data.Size || it->key != key)
2887 return NULL;
2888 return it->val_p;
2889}
2890
2891// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2892int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2893{
2894 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2895 if (it == Data.Data + Data.Size || it->key != key)
2896 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2897 return &it->val_i;
2898}
2899
2900bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2901{
2902 return (bool*)GetIntRef(key, default_val: default_val ? 1 : 0);
2903}
2904
2905float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2906{
2907 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2908 if (it == Data.Data + Data.Size || it->key != key)
2909 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2910 return &it->val_f;
2911}
2912
2913void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2914{
2915 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2916 if (it == Data.Data + Data.Size || it->key != key)
2917 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2918 return &it->val_p;
2919}
2920
2921// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2922void ImGuiStorage::SetInt(ImGuiID key, int val)
2923{
2924 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2925 if (it == Data.Data + Data.Size || it->key != key)
2926 Data.insert(it, v: ImGuiStoragePair(key, val));
2927 else
2928 it->val_i = val;
2929}
2930
2931void ImGuiStorage::SetBool(ImGuiID key, bool val)
2932{
2933 SetInt(key, val: val ? 1 : 0);
2934}
2935
2936void ImGuiStorage::SetFloat(ImGuiID key, float val)
2937{
2938 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2939 if (it == Data.Data + Data.Size || it->key != key)
2940 Data.insert(it, v: ImGuiStoragePair(key, val));
2941 else
2942 it->val_f = val;
2943}
2944
2945void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2946{
2947 ImGuiStoragePair* it = ImLowerBound(in_begin: Data.Data, in_end: Data.Data + Data.Size, key);
2948 if (it == Data.Data + Data.Size || it->key != key)
2949 Data.insert(it, v: ImGuiStoragePair(key, val));
2950 else
2951 it->val_p = val;
2952}
2953
2954void ImGuiStorage::SetAllInt(int v)
2955{
2956 for (int i = 0; i < Data.Size; i++)
2957 Data[i].val_i = v;
2958}
2959IM_MSVC_RUNTIME_CHECKS_RESTORE
2960
2961//-----------------------------------------------------------------------------
2962// [SECTION] ImGuiTextFilter
2963//-----------------------------------------------------------------------------
2964
2965// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2966ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2967{
2968 InputBuf[0] = 0;
2969 CountGrep = 0;
2970 if (default_filter)
2971 {
2972 ImStrncpy(dst: InputBuf, src: default_filter, IM_ARRAYSIZE(InputBuf));
2973 Build();
2974 }
2975}
2976
2977bool ImGuiTextFilter::Draw(const char* label, float width)
2978{
2979 if (width != 0.0f)
2980 ImGui::SetNextItemWidth(width);
2981 bool value_changed = ImGui::InputText(label, buf: InputBuf, IM_ARRAYSIZE(InputBuf));
2982 if (value_changed)
2983 Build();
2984 return value_changed;
2985}
2986
2987void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2988{
2989 out->resize(new_size: 0);
2990 const char* wb = b;
2991 const char* we = wb;
2992 while (we < e)
2993 {
2994 if (*we == separator)
2995 {
2996 out->push_back(v: ImGuiTextRange(wb, we));
2997 wb = we + 1;
2998 }
2999 we++;
3000 }
3001 if (wb != we)
3002 out->push_back(v: ImGuiTextRange(wb, we));
3003}
3004
3005void ImGuiTextFilter::Build()
3006{
3007 Filters.resize(new_size: 0);
3008 ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(s: InputBuf));
3009 input_range.split(separator: ',', out: &Filters);
3010
3011 CountGrep = 0;
3012 for (ImGuiTextRange& f : Filters)
3013 {
3014 while (f.b < f.e && ImCharIsBlankA(c: f.b[0]))
3015 f.b++;
3016 while (f.e > f.b && ImCharIsBlankA(c: f.e[-1]))
3017 f.e--;
3018 if (f.empty())
3019 continue;
3020 if (f.b[0] != '-')
3021 CountGrep += 1;
3022 }
3023}
3024
3025bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
3026{
3027 if (Filters.Size == 0)
3028 return true;
3029
3030 if (text == NULL)
3031 text = text_end = "";
3032
3033 for (const ImGuiTextRange& f : Filters)
3034 {
3035 if (f.b == f.e)
3036 continue;
3037 if (f.b[0] == '-')
3038 {
3039 // Subtract
3040 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b + 1, needle_end: f.e) != NULL)
3041 return false;
3042 }
3043 else
3044 {
3045 // Grep
3046 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b, needle_end: f.e) != NULL)
3047 return true;
3048 }
3049 }
3050
3051 // Implicit * grep
3052 if (CountGrep == 0)
3053 return true;
3054
3055 return false;
3056}
3057
3058//-----------------------------------------------------------------------------
3059// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
3060//-----------------------------------------------------------------------------
3061
3062// On some platform vsnprintf() takes va_list by reference and modifies it.
3063// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
3064#ifndef va_copy
3065#if defined(__GNUC__) || defined(__clang__)
3066#define va_copy(dest, src) __builtin_va_copy(dest, src)
3067#else
3068#define va_copy(dest, src) (dest = src)
3069#endif
3070#endif
3071
3072char ImGuiTextBuffer::EmptyString[1] = { 0 };
3073
3074void ImGuiTextBuffer::append(const char* str, const char* str_end)
3075{
3076 int len = str_end ? (int)(str_end - str) : (int)ImStrlen(s: str);
3077
3078 // Add zero-terminator the first time
3079 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3080 const int needed_sz = write_off + len;
3081 if (write_off + len >= Buf.Capacity)
3082 {
3083 int new_capacity = Buf.Capacity * 2;
3084 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
3085 }
3086
3087 Buf.resize(new_size: needed_sz);
3088 memcpy(dest: &Buf[write_off - 1], src: str, n: (size_t)len);
3089 Buf[write_off - 1 + len] = 0;
3090}
3091
3092void ImGuiTextBuffer::appendf(const char* fmt, ...)
3093{
3094 va_list args;
3095 va_start(args, fmt);
3096 appendfv(fmt, args);
3097 va_end(args);
3098}
3099
3100// Helper: Text buffer for logging/accumulating text
3101void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
3102{
3103 va_list args_copy;
3104 va_copy(args_copy, args);
3105
3106 int len = ImFormatStringV(NULL, buf_size: 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
3107 if (len <= 0)
3108 {
3109 va_end(args_copy);
3110 return;
3111 }
3112
3113 // Add zero-terminator the first time
3114 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
3115 const int needed_sz = write_off + len;
3116 if (write_off + len >= Buf.Capacity)
3117 {
3118 int new_capacity = Buf.Capacity * 2;
3119 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
3120 }
3121
3122 Buf.resize(new_size: needed_sz);
3123 ImFormatStringV(buf: &Buf[write_off - 1], buf_size: (size_t)len + 1, fmt, args: args_copy);
3124 va_end(args_copy);
3125}
3126
3127void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
3128{
3129 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
3130 if (old_size == new_size)
3131 return;
3132 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
3133 LineOffsets.push_back(v: EndOffset);
3134 const char* base_end = base + new_size;
3135 for (const char* p = base + old_size; (p = (const char*)ImMemchr(s: p, c: '\n', n: base_end - p)) != 0; )
3136 if (++p < base_end) // Don't push a trailing offset on last \n
3137 LineOffsets.push_back(v: (int)(intptr_t)(p - base));
3138 EndOffset = ImMax(lhs: EndOffset, rhs: new_size);
3139}
3140
3141//-----------------------------------------------------------------------------
3142// [SECTION] ImGuiListClipper
3143//-----------------------------------------------------------------------------
3144
3145// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
3146// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
3147static bool GetSkipItemForListClipping()
3148{
3149 ImGuiContext& g = *GImGui;
3150 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
3151}
3152
3153static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
3154{
3155 if (ranges.Size - offset <= 1)
3156 return;
3157
3158 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
3159 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
3160 for (int i = offset; i < sort_end + offset; ++i)
3161 if (ranges[i].Min > ranges[i + 1].Min)
3162 ImSwap(a&: ranges[i], b&: ranges[i + 1]);
3163
3164 // Now fuse ranges together as much as possible.
3165 for (int i = 1 + offset; i < ranges.Size; i++)
3166 {
3167 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
3168 if (ranges[i - 1].Max < ranges[i].Min)
3169 continue;
3170 ranges[i - 1].Min = ImMin(lhs: ranges[i - 1].Min, rhs: ranges[i].Min);
3171 ranges[i - 1].Max = ImMax(lhs: ranges[i - 1].Max, rhs: ranges[i].Max);
3172 ranges.erase(it: ranges.Data + i);
3173 i--;
3174 }
3175}
3176
3177static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
3178{
3179 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
3180 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
3181 // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
3182 ImGuiContext& g = *GImGui;
3183 ImGuiWindow* window = g.CurrentWindow;
3184 float off_y = pos_y - window->DC.CursorPos.y;
3185 window->DC.CursorPos.y = pos_y;
3186 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: pos_y - g.Style.ItemSpacing.y);
3187 window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
3188 window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
3189 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
3190 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
3191 if (ImGuiTable* table = g.CurrentTable)
3192 {
3193 if (table->IsInsideRow)
3194 ImGui::TableEndRow(table);
3195 table->RowPosY2 = window->DC.CursorPos.y;
3196 const int row_increase = (int)((off_y / line_height) + 0.5f);
3197 table->CurrentRow += row_increase;
3198 table->RowBgColorCounter += row_increase;
3199 }
3200}
3201
3202ImGuiListClipper::ImGuiListClipper()
3203{
3204 memset(s: this, c: 0, n: sizeof(*this));
3205}
3206
3207ImGuiListClipper::~ImGuiListClipper()
3208{
3209 End();
3210}
3211
3212void ImGuiListClipper::Begin(int items_count, float items_height)
3213{
3214 if (Ctx == NULL)
3215 Ctx = ImGui::GetCurrentContext();
3216
3217 ImGuiContext& g = *Ctx;
3218 ImGuiWindow* window = g.CurrentWindow;
3219 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3220
3221 if (ImGuiTable* table = g.CurrentTable)
3222 if (table->IsInsideRow)
3223 ImGui::TableEndRow(table);
3224
3225 StartPosY = window->DC.CursorPos.y;
3226 ItemsHeight = items_height;
3227 ItemsCount = items_count;
3228 DisplayStart = -1;
3229 DisplayEnd = 0;
3230
3231 // Acquire temporary buffer
3232 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3233 g.ClipperTempData.resize(new_size: g.ClipperTempDataStacked, v: ImGuiListClipperData());
3234 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3235 data->Reset(clipper: this);
3236 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3237 TempData = data;
3238 StartSeekOffsetY = data->LossynessOffset;
3239}
3240
3241void ImGuiListClipper::End()
3242{
3243 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3244 {
3245 // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3246 ImGuiContext& g = *Ctx;
3247 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3248 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3249 SeekCursorForItem(item_index: ItemsCount);
3250
3251 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3252 IM_ASSERT(data->ListClipper == this);
3253 data->StepNo = data->Ranges.Size;
3254 if (--g.ClipperTempDataStacked > 0)
3255 {
3256 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3257 data->ListClipper->TempData = data;
3258 }
3259 TempData = NULL;
3260 }
3261 ItemsCount = -1;
3262}
3263
3264void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3265{
3266 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3267 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3268 IM_ASSERT(item_begin <= item_end);
3269 if (item_begin < item_end)
3270 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: item_begin, max: item_end));
3271}
3272
3273// This is already called while stepping.
3274// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand.
3275void ImGuiListClipper::SeekCursorForItem(int item_n)
3276{
3277 // - Perform the add and multiply with double to allow seeking through larger ranges.
3278 // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3279 // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
3280 float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3281 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, line_height: ItemsHeight);
3282}
3283
3284static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3285{
3286 ImGuiContext& g = *clipper->Ctx;
3287 ImGuiWindow* window = g.CurrentWindow;
3288 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3289 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3290
3291 ImGuiTable* table = g.CurrentTable;
3292 if (table && table->IsInsideRow)
3293 ImGui::TableEndRow(table);
3294
3295 // No items
3296 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3297 return false;
3298
3299 // While we are in frozen row state, keep displaying items one by one, unclipped
3300 // FIXME: Could be stored as a table-agnostic state.
3301 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3302 {
3303 clipper->DisplayStart = data->ItemsFrozen;
3304 clipper->DisplayEnd = ImMin(lhs: data->ItemsFrozen + 1, rhs: clipper->ItemsCount);
3305 if (clipper->DisplayStart < clipper->DisplayEnd)
3306 data->ItemsFrozen++;
3307 return true;
3308 }
3309
3310 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3311 bool calc_clipping = false;
3312 if (data->StepNo == 0)
3313 {
3314 clipper->StartPosY = window->DC.CursorPos.y;
3315 if (clipper->ItemsHeight <= 0.0f)
3316 {
3317 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3318 data->Ranges.push_front(v: ImGuiListClipperRange::FromIndices(min: data->ItemsFrozen, max: data->ItemsFrozen + 1));
3319 clipper->DisplayStart = ImMax(lhs: data->Ranges[0].Min, rhs: data->ItemsFrozen);
3320 clipper->DisplayEnd = ImMin(lhs: data->Ranges[0].Max, rhs: clipper->ItemsCount);
3321 data->StepNo = 1;
3322 return true;
3323 }
3324 calc_clipping = true; // If on the first step with known item height, calculate clipping.
3325 }
3326
3327 // Step 1: Let the clipper infer height from first range
3328 if (clipper->ItemsHeight <= 0.0f)
3329 {
3330 IM_ASSERT(data->StepNo == 1);
3331 if (table)
3332 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3333
3334 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(f: (float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(f: window->DC.CursorPos.y);
3335 if (affected_by_floating_point_precision)
3336 {
3337 // Mitigation/hack for very large range: assume last time height constitute line height.
3338 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3339 window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight);
3340 }
3341 else
3342 {
3343 clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3344 }
3345 if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3346 return false;
3347 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3348 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
3349 }
3350
3351 // Step 0 or 1: Calculate the actual ranges of visible elements.
3352 const int already_submitted = clipper->DisplayEnd;
3353 if (calc_clipping)
3354 {
3355 // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3356 clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3357
3358 if (g.LogEnabled)
3359 {
3360 // If logging is active, do not perform any clipping
3361 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: 0, max: clipper->ItemsCount));
3362 }
3363 else
3364 {
3365 // Add range selected to be included for navigation
3366 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3367 if (is_nav_request)
3368 {
3369 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringRect.Min.y, y2: g.NavScoringRect.Max.y, off_min: 0, off_max: 0));
3370 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringNoClipRect.Min.y, y2: g.NavScoringNoClipRect.Max.y, off_min: 0, off_max: 0));
3371 }
3372 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3373 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: clipper->ItemsCount - 1, max: clipper->ItemsCount));
3374
3375 // Add focused/active item
3376 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, r: window->NavRectRel[0]);
3377 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3378 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: nav_rect_abs.Min.y, y2: nav_rect_abs.Max.y, off_min: 0, off_max: 0));
3379
3380 // Add visible range
3381 float min_y = window->ClipRect.Min.y;
3382 float max_y = window->ClipRect.Max.y;
3383
3384 // Add box selection range
3385 ImGuiBoxSelectState* bs = &g.BoxSelectState;
3386 if (bs->IsActive && bs->Window == window)
3387 {
3388 // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3389 // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3390 // As a workaround we currently half ItemSpacing worth on each side.
3391 min_y -= g.Style.ItemSpacing.y;
3392 max_y += g.Style.ItemSpacing.y;
3393
3394 // Box-select on 2D area requires different clipping.
3395 if (bs->UnclipMode)
3396 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: bs->UnclipRect.Min.y, y2: bs->UnclipRect.Max.y, off_min: 0, off_max: 0));
3397 }
3398
3399 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3400 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3401 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: min_y, y2: max_y, off_min, off_max));
3402 }
3403
3404 // Convert position ranges to item index ranges
3405 // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3406 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3407 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3408 for (ImGuiListClipperRange& range : data->Ranges)
3409 if (range.PosToIndexConvert)
3410 {
3411 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3412 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3413 range.Min = ImClamp(v: already_submitted + m1 + range.PosToIndexOffsetMin, mn: already_submitted, mx: clipper->ItemsCount - 1);
3414 range.Max = ImClamp(v: already_submitted + m2 + range.PosToIndexOffsetMax, mn: range.Min + 1, mx: clipper->ItemsCount);
3415 range.PosToIndexConvert = false;
3416 }
3417 ImGuiListClipper_SortAndFuseRanges(ranges&: data->Ranges, offset: data->StepNo);
3418 }
3419
3420 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3421 while (data->StepNo < data->Ranges.Size)
3422 {
3423 clipper->DisplayStart = ImMax(lhs: data->Ranges[data->StepNo].Min, rhs: already_submitted);
3424 clipper->DisplayEnd = ImMin(lhs: data->Ranges[data->StepNo].Max, rhs: clipper->ItemsCount);
3425 data->StepNo++;
3426 if (clipper->DisplayStart >= clipper->DisplayEnd)
3427 continue;
3428 if (clipper->DisplayStart > already_submitted)
3429 clipper->SeekCursorForItem(item_n: clipper->DisplayStart);
3430 return true;
3431 }
3432
3433 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3434 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3435 if (clipper->ItemsCount < INT_MAX)
3436 clipper->SeekCursorForItem(item_n: clipper->ItemsCount);
3437
3438 return false;
3439}
3440
3441bool ImGuiListClipper::Step()
3442{
3443 ImGuiContext& g = *Ctx;
3444 bool need_items_height = (ItemsHeight <= 0.0f);
3445 bool ret = ImGuiListClipper_StepInternal(clipper: this);
3446 if (ret && (DisplayStart >= DisplayEnd))
3447 ret = false;
3448 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3449 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3450 if (need_items_height && ItemsHeight > 0.0f)
3451 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3452 if (ret)
3453 {
3454 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3455 }
3456 else
3457 {
3458 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3459 End();
3460 }
3461 return ret;
3462}
3463
3464//-----------------------------------------------------------------------------
3465// [SECTION] STYLING
3466//-----------------------------------------------------------------------------
3467
3468ImGuiStyle& ImGui::GetStyle()
3469{
3470 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3471 return GImGui->Style;
3472}
3473
3474ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3475{
3476 ImGuiStyle& style = GImGui->Style;
3477 ImVec4 c = style.Colors[idx];
3478 c.w *= style.Alpha * alpha_mul;
3479 return ColorConvertFloat4ToU32(in: c);
3480}
3481
3482ImU32 ImGui::GetColorU32(const ImVec4& col)
3483{
3484 ImGuiStyle& style = GImGui->Style;
3485 ImVec4 c = col;
3486 c.w *= style.Alpha;
3487 return ColorConvertFloat4ToU32(in: c);
3488}
3489
3490const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3491{
3492 ImGuiStyle& style = GImGui->Style;
3493 return style.Colors[idx];
3494}
3495
3496ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3497{
3498 ImGuiStyle& style = GImGui->Style;
3499 alpha_mul *= style.Alpha;
3500 if (alpha_mul >= 1.0f)
3501 return col;
3502 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3503 a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3504 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3505}
3506
3507// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3508void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3509{
3510 ImGuiContext& g = *GImGui;
3511 ImGuiColorMod backup;
3512 backup.Col = idx;
3513 backup.BackupValue = g.Style.Colors[idx];
3514 g.ColorStack.push_back(v: backup);
3515 if (g.DebugFlashStyleColorIdx != idx)
3516 g.Style.Colors[idx] = ColorConvertU32ToFloat4(in: col);
3517}
3518
3519void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3520{
3521 ImGuiContext& g = *GImGui;
3522 ImGuiColorMod backup;
3523 backup.Col = idx;
3524 backup.BackupValue = g.Style.Colors[idx];
3525 g.ColorStack.push_back(v: backup);
3526 if (g.DebugFlashStyleColorIdx != idx)
3527 g.Style.Colors[idx] = col;
3528}
3529
3530void ImGui::PopStyleColor(int count)
3531{
3532 ImGuiContext& g = *GImGui;
3533 if (g.ColorStack.Size < count)
3534 {
3535 IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
3536 count = g.ColorStack.Size;
3537 }
3538 while (count > 0)
3539 {
3540 ImGuiColorMod& backup = g.ColorStack.back();
3541 g.Style.Colors[backup.Col] = backup.BackupValue;
3542 g.ColorStack.pop_back();
3543 count--;
3544 }
3545}
3546
3547static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3548{
3549 ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3550};
3551
3552static const ImGuiStyleVarInfo GStyleVarsInfo[] =
3553{
3554 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3555 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3556 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3557 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3558 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3559 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3560 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3561 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3562 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3563 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3564 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3565 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3566 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3567 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3568 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3569 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3570 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3571 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3572 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3573 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3574 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3575 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3576 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize
3577 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3578 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize
3579 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase
3580 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink
3581 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3582 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize
3583 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle
3584 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3585 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize
3586 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding
3587 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3588 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3589 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize
3590 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3591 { .Count: 2, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3592 { .Count: 1, .DataType: ImGuiDataType_Float, .Offset: (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize
3593};
3594
3595const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3596{
3597 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3598 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT);
3599 return &GStyleVarsInfo[idx];
3600}
3601
3602void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3603{
3604 ImGuiContext& g = *GImGui;
3605 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3606 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1)
3607 {
3608 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3609 return;
3610 }
3611 float* pvar = (float*)var_info->GetVarPtr(parent: &g.Style);
3612 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3613 *pvar = val;
3614}
3615
3616void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x)
3617{
3618 ImGuiContext& g = *GImGui;
3619 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3620 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3621 {
3622 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3623 return;
3624 }
3625 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3626 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3627 pvar->x = val_x;
3628}
3629
3630void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y)
3631{
3632 ImGuiContext& g = *GImGui;
3633 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3634 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3635 {
3636 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3637 return;
3638 }
3639 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3640 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3641 pvar->y = val_y;
3642}
3643
3644void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3645{
3646 ImGuiContext& g = *GImGui;
3647 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3648 if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2)
3649 {
3650 IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3651 return;
3652 }
3653 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3654 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3655 *pvar = val;
3656}
3657
3658void ImGui::PopStyleVar(int count)
3659{
3660 ImGuiContext& g = *GImGui;
3661 if (g.StyleVarStack.Size < count)
3662 {
3663 IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
3664 count = g.StyleVarStack.Size;
3665 }
3666 while (count > 0)
3667 {
3668 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3669 ImGuiStyleMod& backup = g.StyleVarStack.back();
3670 const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx: backup.VarIdx);
3671 void* data = var_info->GetVarPtr(parent: &g.Style);
3672 if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3673 else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3674 g.StyleVarStack.pop_back();
3675 count--;
3676 }
3677}
3678
3679const char* ImGui::GetStyleColorName(ImGuiCol idx)
3680{
3681 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3682 switch (idx)
3683 {
3684 case ImGuiCol_Text: return "Text";
3685 case ImGuiCol_TextDisabled: return "TextDisabled";
3686 case ImGuiCol_WindowBg: return "WindowBg";
3687 case ImGuiCol_ChildBg: return "ChildBg";
3688 case ImGuiCol_PopupBg: return "PopupBg";
3689 case ImGuiCol_Border: return "Border";
3690 case ImGuiCol_BorderShadow: return "BorderShadow";
3691 case ImGuiCol_FrameBg: return "FrameBg";
3692 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3693 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3694 case ImGuiCol_TitleBg: return "TitleBg";
3695 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3696 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3697 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3698 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3699 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3700 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3701 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3702 case ImGuiCol_CheckMark: return "CheckMark";
3703 case ImGuiCol_SliderGrab: return "SliderGrab";
3704 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3705 case ImGuiCol_Button: return "Button";
3706 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3707 case ImGuiCol_ButtonActive: return "ButtonActive";
3708 case ImGuiCol_Header: return "Header";
3709 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3710 case ImGuiCol_HeaderActive: return "HeaderActive";
3711 case ImGuiCol_Separator: return "Separator";
3712 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3713 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3714 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3715 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3716 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3717 case ImGuiCol_InputTextCursor: return "InputTextCursor";
3718 case ImGuiCol_TabHovered: return "TabHovered";
3719 case ImGuiCol_Tab: return "Tab";
3720 case ImGuiCol_TabSelected: return "TabSelected";
3721 case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3722 case ImGuiCol_TabDimmed: return "TabDimmed";
3723 case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3724 case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3725 case ImGuiCol_DockingPreview: return "DockingPreview";
3726 case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3727 case ImGuiCol_PlotLines: return "PlotLines";
3728 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3729 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3730 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3731 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3732 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3733 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3734 case ImGuiCol_TableRowBg: return "TableRowBg";
3735 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3736 case ImGuiCol_TextLink: return "TextLink";
3737 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3738 case ImGuiCol_TreeLines: return "TreeLines";
3739 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3740 case ImGuiCol_NavCursor: return "NavCursor";
3741 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3742 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3743 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3744 }
3745 IM_ASSERT(0);
3746 return "Unknown";
3747}
3748
3749//-----------------------------------------------------------------------------
3750// [SECTION] RENDER HELPERS
3751// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3752// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3753// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3754//-----------------------------------------------------------------------------
3755
3756const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3757{
3758 const char* text_display_end = text;
3759 if (!text_end)
3760 text_end = (const char*)-1;
3761
3762 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3763 text_display_end++;
3764 return text_display_end;
3765}
3766
3767// Internal ImGui functions to render text
3768// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3769void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3770{
3771 ImGuiContext& g = *GImGui;
3772 ImGuiWindow* window = g.CurrentWindow;
3773
3774 // Hide anything after a '##' string
3775 const char* text_display_end;
3776 if (hide_text_after_hash)
3777 {
3778 text_display_end = FindRenderedTextEnd(text, text_end);
3779 }
3780 else
3781 {
3782 if (!text_end)
3783 text_end = text + ImStrlen(s: text); // FIXME-OPT
3784 text_display_end = text_end;
3785 }
3786
3787 if (text != text_display_end)
3788 {
3789 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end);
3790 if (g.LogEnabled)
3791 LogRenderedText(ref_pos: &pos, text, text_end: text_display_end);
3792 }
3793}
3794
3795void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3796{
3797 ImGuiContext& g = *GImGui;
3798 ImGuiWindow* window = g.CurrentWindow;
3799
3800 if (!text_end)
3801 text_end = text + ImStrlen(s: text); // FIXME-OPT
3802
3803 if (text != text_end)
3804 {
3805 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end, wrap_width);
3806 if (g.LogEnabled)
3807 LogRenderedText(ref_pos: &pos, text, text_end);
3808 }
3809}
3810
3811// Default clip_rect uses (pos_min,pos_max)
3812// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3813// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList.
3814// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3815// better advantage of the render function taking size into account for coarse clipping.
3816void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3817{
3818 // Perform CPU side clipping for single clipped element to avoid using scissor state
3819 ImVec2 pos = pos_min;
3820 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_display_end, hide_text_after_double_hash: false, wrap_width: 0.0f);
3821
3822 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3823 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3824 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3825 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3826 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3827
3828 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3829 if (align.x > 0.0f) pos.x = ImMax(lhs: pos.x, rhs: pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3830 if (align.y > 0.0f) pos.y = ImMax(lhs: pos.y, rhs: pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3831
3832 // Render
3833 if (need_clipping)
3834 {
3835 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3836 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, cpu_fine_clip_rect: &fine_clip_rect);
3837 }
3838 else
3839 {
3840 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, NULL);
3841 }
3842}
3843
3844void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3845{
3846 // Hide anything after a '##' string
3847 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3848 const int text_len = (int)(text_display_end - text);
3849 if (text_len == 0)
3850 return;
3851
3852 ImGuiContext& g = *GImGui;
3853 ImGuiWindow* window = g.CurrentWindow;
3854 RenderTextClippedEx(draw_list: window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3855 if (g.LogEnabled)
3856 LogRenderedText(ref_pos: &pos_min, text, text_end: text_display_end);
3857}
3858
3859// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3860// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) from 'ellipsis_max_x' which may be beyond it.
3861// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3862// (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceeding 'float ellipsis_max' and was the same value for 99% of users.
3863void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3864{
3865 ImGuiContext& g = *GImGui;
3866 if (text_end_full == NULL)
3867 text_end_full = FindRenderedTextEnd(text);
3868 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_end_full, hide_text_after_double_hash: false, wrap_width: 0.0f);
3869
3870 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255));
3871 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255));
3872
3873 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3874 if (text_size.x > pos_max.x - pos_min.x)
3875 {
3876 // Hello wo...
3877 // | | |
3878 // min max ellipsis_max
3879 // <-> this is generally some padding value
3880
3881 ImFont* font = draw_list->_Data->Font;
3882 const float font_size = draw_list->_Data->FontSize;
3883 const float font_scale = draw_list->_Data->FontScale;
3884 const char* text_end_ellipsis = NULL;
3885 ImFontBaked* baked = font->GetFontBaked(font_size);
3886 const float ellipsis_width = baked->GetCharAdvance(c: font->EllipsisChar) * font_scale;
3887
3888 // We can now claim the space between pos_max.x and ellipsis_max.x
3889 const float text_avail_width = ImMax(lhs: (ImMax(lhs: pos_max.x, rhs: ellipsis_max_x) - ellipsis_width) - pos_min.x, rhs: 1.0f);
3890 float text_size_clipped_x = font->CalcTextSizeA(size: font_size, max_width: text_avail_width, wrap_width: 0.0f, text_begin: text, text_end: text_end_full, remaining: &text_end_ellipsis).x;
3891 while (text_end_ellipsis > text && ImCharIsBlankA(c: text_end_ellipsis[-1]))
3892 {
3893 // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3894 text_end_ellipsis--;
3895 text_size_clipped_x -= font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text_end_ellipsis, text_end: text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3896 }
3897
3898 // Render text, render ellipsis
3899 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_display_end: text_end_ellipsis, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3900 ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y);
3901 ImVec2 ellipsis_pos = ImTrunc(v: ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3902 font->RenderChar(draw_list, size: font_size, pos: ellipsis_pos, col: GetColorU32(idx: ImGuiCol_Text), c: font->EllipsisChar, cpu_fine_clip: &cpu_fine_clip_rect);
3903 }
3904 else
3905 {
3906 RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_display_end: text_end_full, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3907 }
3908
3909 if (g.LogEnabled)
3910 LogRenderedText(ref_pos: &pos_min, text, text_end: text_end_full);
3911}
3912
3913// Render a rectangle shaped with optional rounding and borders
3914void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding)
3915{
3916 ImGuiContext& g = *GImGui;
3917 ImGuiWindow* window = g.CurrentWindow;
3918 window->DrawList->AddRectFilled(p_min, p_max, col: fill_col, rounding);
3919 const float border_size = g.Style.FrameBorderSize;
3920 if (borders && border_size > 0.0f)
3921 {
3922 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3923 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3924 }
3925}
3926
3927void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3928{
3929 ImGuiContext& g = *GImGui;
3930 ImGuiWindow* window = g.CurrentWindow;
3931 const float border_size = g.Style.FrameBorderSize;
3932 if (border_size > 0.0f)
3933 {
3934 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3935 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3936 }
3937}
3938
3939void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags)
3940{
3941 ImGuiContext& g = *GImGui;
3942 if (id != g.NavId)
3943 return;
3944 if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
3945 return;
3946 if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
3947 return;
3948 ImGuiWindow* window = g.CurrentWindow;
3949 if (window->DC.NavHideHighlightOneFrame)
3950 return;
3951
3952 float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3953 ImRect display_rect = bb;
3954 display_rect.ClipWith(r: window->ClipRect);
3955 const float thickness = 2.0f;
3956 if (flags & ImGuiNavRenderCursorFlags_Compact)
3957 {
3958 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavCursor), rounding, flags: 0, thickness);
3959 }
3960 else
3961 {
3962 const float distance = 3.0f + thickness * 0.5f;
3963 display_rect.Expand(amount: ImVec2(distance, distance));
3964 bool fully_visible = window->ClipRect.Contains(r: display_rect);
3965 if (!fully_visible)
3966 window->DrawList->PushClipRect(clip_rect_min: display_rect.Min, clip_rect_max: display_rect.Max);
3967 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavCursor), rounding, flags: 0, thickness);
3968 if (!fully_visible)
3969 window->DrawList->PopClipRect();
3970 }
3971}
3972
3973void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3974{
3975 ImGuiContext& g = *GImGui;
3976 if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
3977 mouse_cursor = ImGuiMouseCursor_Arrow;
3978 ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas;
3979 for (ImGuiViewportP* viewport : g.Viewports)
3980 {
3981 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3982 ImVec2 offset, size, uv[4];
3983 if (!ImFontAtlasGetMouseCursorTexData(atlas: font_atlas, cursor_type: mouse_cursor, out_offset: &offset, out_size: &size, out_uv_border: &uv[0], out_uv_fill: &uv[2]))
3984 continue;
3985 const ImVec2 pos = base_pos - offset;
3986 const float scale = base_scale * viewport->DpiScale;
3987 if (!viewport->GetMainRect().Overlaps(r: ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3988 continue;
3989 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3990 ImTextureRef tex_ref = font_atlas->TexRef;
3991 draw_list->PushTexture(tex_ref);
3992 draw_list->AddImage(tex_ref, p_min: pos + ImVec2(1, 0) * scale, p_max: pos + (ImVec2(1, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3993 draw_list->AddImage(tex_ref, p_min: pos + ImVec2(2, 0) * scale, p_max: pos + (ImVec2(2, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3994 draw_list->AddImage(tex_ref, p_min: pos, p_max: pos + size * scale, uv_min: uv[2], uv_max: uv[3], col: col_border);
3995 draw_list->AddImage(tex_ref, p_min: pos, p_max: pos + size * scale, uv_min: uv[0], uv_max: uv[1], col: col_fill);
3996 if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress)
3997 {
3998 float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI);
3999 float a_max = a_min + IM_PI * 1.65f;
4000 draw_list->PathArcTo(center: pos + ImVec2(14, -1) * scale, radius: 6.0f * scale, a_min, a_max);
4001 draw_list->PathStroke(col: col_fill, flags: ImDrawFlags_None, thickness: 3.0f * scale);
4002 }
4003 draw_list->PopTexture();
4004 }
4005}
4006
4007//-----------------------------------------------------------------------------
4008// [SECTION] INITIALIZATION, SHUTDOWN
4009//-----------------------------------------------------------------------------
4010
4011// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
4012// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
4013ImGuiContext* ImGui::GetCurrentContext()
4014{
4015 return GImGui;
4016}
4017
4018void ImGui::SetCurrentContext(ImGuiContext* ctx)
4019{
4020#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
4021 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
4022#else
4023 GImGui = ctx;
4024#endif
4025}
4026
4027void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
4028{
4029 GImAllocatorAllocFunc = alloc_func;
4030 GImAllocatorFreeFunc = free_func;
4031 GImAllocatorUserData = user_data;
4032}
4033
4034// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
4035void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
4036{
4037 *p_alloc_func = GImAllocatorAllocFunc;
4038 *p_free_func = GImAllocatorFreeFunc;
4039 *p_user_data = GImAllocatorUserData;
4040}
4041
4042ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
4043{
4044 ImGuiContext* prev_ctx = GetCurrentContext();
4045 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
4046 SetCurrentContext(ctx);
4047 Initialize();
4048 if (prev_ctx != NULL)
4049 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
4050 return ctx;
4051}
4052
4053void ImGui::DestroyContext(ImGuiContext* ctx)
4054{
4055 ImGuiContext* prev_ctx = GetCurrentContext();
4056 if (ctx == NULL) //-V1051
4057 ctx = prev_ctx;
4058 SetCurrentContext(ctx);
4059 Shutdown();
4060 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
4061 IM_DELETE(p: ctx);
4062}
4063
4064// IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation.
4065static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
4066{
4067 { .Key: ImGuiLocKey_VersionStr, .Text: "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
4068 { .Key: ImGuiLocKey_TableSizeOne, .Text: "Size column to fit###SizeOne" },
4069 { .Key: ImGuiLocKey_TableSizeAllFit, .Text: "Size all columns to fit###SizeAll" },
4070 { .Key: ImGuiLocKey_TableSizeAllDefault, .Text: "Size all columns to default###SizeAll" },
4071 { .Key: ImGuiLocKey_TableResetOrder, .Text: "Reset order###ResetOrder" },
4072 { .Key: ImGuiLocKey_WindowingMainMenuBar, .Text: "(Main menu bar)" },
4073 { .Key: ImGuiLocKey_WindowingPopup, .Text: "(Popup)" },
4074 { .Key: ImGuiLocKey_WindowingUntitled, .Text: "(Untitled)" },
4075 { .Key: ImGuiLocKey_OpenLink_s, .Text: "Open '%s'" },
4076 { .Key: ImGuiLocKey_CopyLink, .Text: "Copy Link###CopyLink" },
4077 { .Key: ImGuiLocKey_DockingHideTabBar, .Text: "Hide tab bar###HideTabBar" },
4078 { .Key: ImGuiLocKey_DockingHoldShiftToDock, .Text: "Hold SHIFT to enable Docking window." },
4079 { .Key: ImGuiLocKey_DockingDragToUndockOrMoveNode,.Text: "Click and drag to move or undock whole node." },
4080};
4081
4082ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
4083{
4084 IO.Ctx = this;
4085 InputTextState.Ctx = this;
4086
4087 Initialized = false;
4088 ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None;
4089
4090 Font = NULL;
4091 FontBaked = NULL;
4092 FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f;
4093 FontRasterizerDensity = 1.0f;
4094 IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
4095 if (shared_font_atlas == NULL)
4096 IO.Fonts->OwnerContext = this;
4097 Time = 0.0f;
4098 FrameCount = 0;
4099 FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1;
4100 WithinEndChildID = 0;
4101 WithinFrameScope = WithinFrameScopeWithImplicitWindow = false;
4102 GcCompactAll = false;
4103 TestEngineHookItems = false;
4104 TestEngine = NULL;
4105 memset(s: ContextName, c: 0, n: sizeof(ContextName));
4106
4107 InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
4108 InputEventsNextEventId = 1;
4109
4110 WindowsActiveCount = 0;
4111 WindowsBorderHoverPadding = 0.0f;
4112 CurrentWindow = NULL;
4113 HoveredWindow = NULL;
4114 HoveredWindowUnderMovingWindow = NULL;
4115 HoveredWindowBeforeClear = NULL;
4116 MovingWindow = NULL;
4117 WheelingWindow = NULL;
4118 WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
4119 WheelingWindowReleaseTimer = 0.0f;
4120
4121 DebugDrawIdConflictsId = 0;
4122 DebugHookIdInfo = 0;
4123 HoveredId = HoveredIdPreviousFrame = 0;
4124 HoveredIdPreviousFrameItemCount = 0;
4125 HoveredIdAllowOverlap = false;
4126 HoveredIdIsDisabled = false;
4127 HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
4128 ItemUnclipByLog = false;
4129 ActiveId = 0;
4130 ActiveIdIsAlive = 0;
4131 ActiveIdTimer = 0.0f;
4132 ActiveIdIsJustActivated = false;
4133 ActiveIdAllowOverlap = false;
4134 ActiveIdNoClearOnFocusLoss = false;
4135 ActiveIdHasBeenPressedBefore = false;
4136 ActiveIdHasBeenEditedBefore = false;
4137 ActiveIdHasBeenEditedThisFrame = false;
4138 ActiveIdFromShortcut = false;
4139 ActiveIdClickOffset = ImVec2(-1, -1);
4140 ActiveIdWindow = NULL;
4141 ActiveIdSource = ImGuiInputSource_None;
4142 ActiveIdDisabledId = 0;
4143 ActiveIdMouseButton = -1;
4144 ActiveIdPreviousFrame = 0;
4145 memset(s: &DeactivatedItemData, c: 0, n: sizeof(DeactivatedItemData));
4146 memset(s: &ActiveIdValueOnActivation, c: 0, n: sizeof(ActiveIdValueOnActivation));
4147 LastActiveId = 0;
4148 LastActiveIdTimer = 0.0f;
4149
4150 LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
4151
4152 ActiveIdUsingNavDirMask = 0x00;
4153 ActiveIdUsingAllKeyboardKeys = false;
4154
4155 CurrentFocusScopeId = 0;
4156 CurrentItemFlags = ImGuiItemFlags_None;
4157 DebugShowGroupRects = false;
4158
4159 CurrentViewport = NULL;
4160 MouseViewport = MouseLastHoveredViewport = NULL;
4161 PlatformLastFocusedViewportId = 0;
4162 ViewportCreatedCount = PlatformWindowsCreatedCount = 0;
4163 ViewportFocusedStampCount = 0;
4164
4165 NavCursorVisible = false;
4166 NavHighlightItemUnderNav = false;
4167 NavMousePosDirty = false;
4168 NavIdIsAlive = false;
4169 NavId = 0;
4170 NavWindow = NULL;
4171 NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
4172 NavLayer = ImGuiNavLayer_Main;
4173 NavNextActivateId = 0;
4174 NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
4175 NavHighlightActivatedId = 0;
4176 NavHighlightActivatedTimer = 0.0f;
4177 NavInputSource = ImGuiInputSource_Keyboard;
4178 NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
4179 NavCursorHideFrames = 0;
4180
4181 NavAnyRequest = false;
4182 NavInitRequest = false;
4183 NavInitRequestFromMove = false;
4184 NavMoveSubmitted = false;
4185 NavMoveScoringItems = false;
4186 NavMoveForwardToNextFrame = false;
4187 NavMoveFlags = ImGuiNavMoveFlags_None;
4188 NavMoveScrollFlags = ImGuiScrollFlags_None;
4189 NavMoveKeyMods = ImGuiMod_None;
4190 NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
4191 NavScoringDebugCount = 0;
4192 NavTabbingDir = 0;
4193 NavTabbingCounter = 0;
4194
4195 NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
4196 NavJustMovedToKeyMods = ImGuiMod_None;
4197 NavJustMovedToIsTabbing = false;
4198 NavJustMovedToHasSelectionData = false;
4199
4200 // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
4201 // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
4202 ConfigNavWindowingWithGamepad = true;
4203 ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
4204 ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
4205 NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
4206 NavWindowingInputSource = ImGuiInputSource_None;
4207 NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
4208 NavWindowingToggleLayer = false;
4209 NavWindowingToggleKey = ImGuiKey_None;
4210
4211 DimBgRatio = 0.0f;
4212
4213 DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
4214 DragDropSourceFlags = ImGuiDragDropFlags_None;
4215 DragDropSourceFrameCount = -1;
4216 DragDropMouseButton = -1;
4217 DragDropTargetId = 0;
4218 DragDropAcceptFlags = ImGuiDragDropFlags_None;
4219 DragDropAcceptIdCurrRectSurface = 0.0f;
4220 DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
4221 DragDropAcceptFrameCount = -1;
4222 DragDropHoldJustPressedId = 0;
4223 memset(s: DragDropPayloadBufLocal, c: 0, n: sizeof(DragDropPayloadBufLocal));
4224
4225 ClipperTempDataStacked = 0;
4226
4227 CurrentTable = NULL;
4228 TablesTempDataStacked = 0;
4229 CurrentTabBar = NULL;
4230 CurrentMultiSelect = NULL;
4231 MultiSelectTempDataStacked = 0;
4232
4233 HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
4234 HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
4235
4236 MouseCursor = ImGuiMouseCursor_Arrow;
4237 MouseStationaryTimer = 0.0f;
4238
4239 InputTextPasswordFontBackupFlags = ImFontFlags_None;
4240 TempInputId = 0;
4241 memset(s: &DataTypeZeroValue, c: 0, n: sizeof(DataTypeZeroValue));
4242 BeginMenuDepth = BeginComboDepth = 0;
4243 ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
4244 ColorEditCurrentID = ColorEditSavedID = 0;
4245 ColorEditSavedHue = ColorEditSavedSat = 0.0f;
4246 ColorEditSavedColor = 0;
4247 WindowResizeRelativeMode = false;
4248 ScrollbarSeekMode = 0;
4249 ScrollbarClickDeltaToGrabCenter = 0.0f;
4250 SliderGrabClickOffset = 0.0f;
4251 SliderCurrentAccum = 0.0f;
4252 SliderCurrentAccumDirty = false;
4253 DragCurrentAccumDirty = false;
4254 DragCurrentAccum = 0.0f;
4255 DragSpeedDefaultRatio = 1.0f / 100.0f;
4256 DisabledAlphaBackup = 0.0f;
4257 DisabledStackSize = 0;
4258 TooltipOverrideCount = 0;
4259 TooltipPreviousWindow = NULL;
4260
4261 PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
4262 PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
4263
4264 DockNodeWindowMenuHandler = NULL;
4265
4266 SettingsLoaded = false;
4267 SettingsDirtyTimer = 0.0f;
4268 HookIdNext = 0;
4269
4270 memset(s: LocalizationTable, c: 0, n: sizeof(LocalizationTable));
4271
4272 LogEnabled = false;
4273 LogFlags = ImGuiLogFlags_None;
4274 LogWindow = NULL;
4275 LogNextPrefix = LogNextSuffix = NULL;
4276 LogFile = NULL;
4277 LogLinePosY = FLT_MAX;
4278 LogLineFirstItem = false;
4279 LogDepthRef = 0;
4280 LogDepthToExpand = LogDepthToExpandDefault = 2;
4281
4282 ErrorCallback = NULL;
4283 ErrorCallbackUserData = NULL;
4284 ErrorFirst = true;
4285 ErrorCountCurrentFrame = 0;
4286 StackSizesInBeginForCurrentWindow = NULL;
4287
4288 DebugDrawIdConflictsCount = 0;
4289 DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
4290 DebugLocateId = 0;
4291 DebugLogSkippedErrors = 0;
4292 DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4293 DebugLogAutoDisableFrames = 0;
4294 DebugLocateFrames = 0;
4295 DebugBeginReturnValueCullDepth = -1;
4296 DebugItemPickerActive = false;
4297 DebugItemPickerMouseButton = ImGuiMouseButton_Left;
4298 DebugItemPickerBreakId = 0;
4299 DebugFlashStyleColorTime = 0.0f;
4300 DebugFlashStyleColorIdx = ImGuiCol_COUNT;
4301 DebugHoveredDockNode = NULL;
4302
4303 // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
4304 DebugBreakInWindow = 0;
4305 DebugBreakInTable = 0;
4306 DebugBreakInLocateId = false;
4307 DebugBreakKeyChord = ImGuiKey_Pause;
4308 DebugBreakInShortcutRouting = ImGuiKey_None;
4309
4310 memset(s: FramerateSecPerFrame, c: 0, n: sizeof(FramerateSecPerFrame));
4311 FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
4312 FramerateSecPerFrameAccum = 0.0f;
4313 WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
4314 memset(s: TempKeychordName, c: 0, n: sizeof(TempKeychordName));
4315}
4316
4317void ImGui::Initialize()
4318{
4319 ImGuiContext& g = *GImGui;
4320 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4321
4322 // Add .ini handle for ImGuiWindow and ImGuiTable types
4323 {
4324 ImGuiSettingsHandler ini_handler;
4325 ini_handler.TypeName = "Window";
4326 ini_handler.TypeHash = ImHashStr(data_p: "Window");
4327 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4328 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4329 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4330 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4331 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4332 AddSettingsHandler(handler: &ini_handler);
4333 }
4334 TableSettingsAddSettingsHandler();
4335
4336 // Setup default localization table
4337 LocalizeRegisterEntries(entries: GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
4338
4339 // Setup default ImGuiPlatformIO clipboard/IME handlers.
4340 g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
4341 g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl;
4342 g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl;
4343 g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl;
4344
4345 // Create default viewport
4346 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4347 viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4348 viewport->Idx = 0;
4349 viewport->PlatformWindowCreated = true;
4350 viewport->Flags = ImGuiViewportFlags_OwnedByApp;
4351 g.Viewports.push_back(v: viewport);
4352 g.TempBuffer.resize(new_size: 1024 * 3 + 1, v: 0);
4353 g.ViewportCreatedCount++;
4354 g.PlatformIO.Viewports.push_back(v: g.Viewports[0]);
4355
4356 // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
4357 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4358 if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
4359 || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
4360 || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
4361 || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
4362 g.KeysMayBeCharInput.SetBit(key);
4363
4364#ifdef IMGUI_HAS_DOCK
4365 // Initialize Docking
4366 DockContextInitialize(ctx: &g);
4367#endif
4368
4369 // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow.
4370 // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED.
4371#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
4372 DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n");
4373#endif
4374
4375 // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context.
4376 // But this link allows us to facilitate/handle a few edge cases better.
4377 ImFontAtlas* atlas = g.IO.Fonts;
4378 g.DrawListSharedData.Context = &g;
4379 RegisterFontAtlas(atlas);
4380
4381 g.Initialized = true;
4382}
4383
4384// This function is merely here to free heap allocations.
4385void ImGui::Shutdown()
4386{
4387 ImGuiContext& g = *GImGui;
4388 IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
4389 IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
4390
4391 // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
4392 for (ImFontAtlas* atlas : g.FontAtlases)
4393 {
4394 UnregisterFontAtlas(atlas);
4395 if (atlas->OwnerContext == &g)
4396 {
4397 atlas->Locked = false;
4398 IM_DELETE(p: atlas);
4399 }
4400 }
4401 g.DrawListSharedData.TempBuffer.clear();
4402
4403 // Cleanup of other data are conditional on actually having initialized Dear ImGui.
4404 if (!g.Initialized)
4405 return;
4406
4407 // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
4408 if (g.SettingsLoaded && g.IO.IniFilename != NULL)
4409 SaveIniSettingsToDisk(ini_filename: g.IO.IniFilename);
4410
4411 // Destroy platform windows
4412 DestroyPlatformWindows();
4413
4414 // Shutdown extensions
4415 DockContextShutdown(ctx: &g);
4416
4417 CallContextHooks(context: &g, type: ImGuiContextHookType_Shutdown);
4418
4419 // Clear everything else
4420 g.Windows.clear_delete();
4421 g.WindowsFocusOrder.clear();
4422 g.WindowsTempSortBuffer.clear();
4423 g.CurrentWindow = NULL;
4424 g.CurrentWindowStack.clear();
4425 g.WindowsById.Clear();
4426 g.NavWindow = NULL;
4427 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4428 g.ActiveIdWindow = NULL;
4429 g.MovingWindow = NULL;
4430
4431 g.KeysRoutingTable.Clear();
4432
4433 g.ColorStack.clear();
4434 g.StyleVarStack.clear();
4435 g.FontStack.clear();
4436 g.OpenPopupStack.clear();
4437 g.BeginPopupStack.clear();
4438 g.TreeNodeStack.clear();
4439
4440 g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
4441 g.Viewports.clear_delete();
4442
4443 g.TabBars.Clear();
4444 g.CurrentTabBarStack.clear();
4445 g.ShrinkWidthBuffer.clear();
4446
4447 g.ClipperTempData.clear_destruct();
4448
4449 g.Tables.Clear();
4450 g.TablesTempData.clear_destruct();
4451 g.DrawChannelsTempMergeBuffer.clear();
4452
4453 g.MultiSelectStorage.Clear();
4454 g.MultiSelectTempData.clear_destruct();
4455
4456 g.ClipboardHandlerData.clear();
4457 g.MenusIdSubmittedThisFrame.clear();
4458 g.InputTextState.ClearFreeMemory();
4459 g.InputTextDeactivatedState.ClearFreeMemory();
4460
4461 g.SettingsWindows.clear();
4462 g.SettingsHandlers.clear();
4463
4464 if (g.LogFile)
4465 {
4466#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
4467 if (g.LogFile != stdout)
4468#endif
4469 ImFileClose(f: g.LogFile);
4470 g.LogFile = NULL;
4471 }
4472 g.LogBuffer.clear();
4473 g.DebugLogBuf.clear();
4474 g.DebugLogIndex.clear();
4475
4476 g.Initialized = false;
4477}
4478
4479// No specific ordering/dependency support, will see as needed
4480ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
4481{
4482 ImGuiContext& g = *ctx;
4483 IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
4484 g.Hooks.push_back(v: *hook);
4485 g.Hooks.back().HookId = ++g.HookIdNext;
4486 return g.HookIdNext;
4487}
4488
4489// Deferred removal, avoiding issue with changing vector while iterating it
4490void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
4491{
4492 ImGuiContext& g = *ctx;
4493 IM_ASSERT(hook_id != 0);
4494 for (ImGuiContextHook& hook : g.Hooks)
4495 if (hook.HookId == hook_id)
4496 hook.Type = ImGuiContextHookType_PendingRemoval_;
4497}
4498
4499// Call context hooks (used by e.g. test engine)
4500// We assume a small number of hooks so all stored in same array
4501void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
4502{
4503 ImGuiContext& g = *ctx;
4504 for (ImGuiContextHook& hook : g.Hooks)
4505 if (hook.Type == hook_type)
4506 hook.Callback(&g, &hook);
4507}
4508
4509//-----------------------------------------------------------------------------
4510// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4511//-----------------------------------------------------------------------------
4512
4513// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4514ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4515{
4516 memset(s: this, c: 0, n: sizeof(*this));
4517 Ctx = ctx;
4518 Name = ImStrdup(str: name);
4519 NameBufLen = (int)ImStrlen(s: name) + 1;
4520 ID = ImHashStr(data_p: name);
4521 IDStack.push_back(v: ID);
4522 ViewportAllowPlatformMonitorExtend = -1;
4523 ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
4524 MoveId = GetID(str: "#MOVE");
4525 TabId = GetID(str: "#TAB");
4526 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4527 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4528 AutoFitFramesX = AutoFitFramesY = -1;
4529 AutoPosLastDirection = ImGuiDir_None;
4530 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4531 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4532 LastFrameActive = -1;
4533 LastFrameJustFocused = -1;
4534 LastTimeActive = -1.0f;
4535 FontRefSize = 0.0f;
4536 FontWindowScale = FontWindowScaleParents = 1.0f;
4537 SettingsOffset = -1;
4538 DockOrder = -1;
4539 DrawList = &DrawListInst;
4540 DrawList->_OwnerName = Name;
4541 DrawList->_SetDrawListSharedData(data: &Ctx->DrawListSharedData);
4542 NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4543 IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4544}
4545
4546ImGuiWindow::~ImGuiWindow()
4547{
4548 IM_ASSERT(DrawList == &DrawListInst);
4549 IM_DELETE(p: Name);
4550 ColumnsStorage.clear_destruct();
4551}
4552
4553static void SetCurrentWindow(ImGuiWindow* window)
4554{
4555 ImGuiContext& g = *GImGui;
4556 g.CurrentWindow = window;
4557 g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
4558 g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(n: window->DC.CurrentTableIdx) : NULL;
4559 if (window)
4560 {
4561 bool backup_skip_items = window->SkipItems;
4562 window->SkipItems = false;
4563 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
4564 {
4565 ImGuiViewport* viewport = window->Viewport;
4566 g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity()
4567 }
4568 ImGui::UpdateCurrentFontSize(restore_font_size_after_scaling: 0.0f);
4569 window->SkipItems = backup_skip_items;
4570 ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4571 }
4572}
4573
4574void ImGui::GcCompactTransientMiscBuffers()
4575{
4576 ImGuiContext& g = *GImGui;
4577 g.ItemFlagsStack.clear();
4578 g.GroupStack.clear();
4579 g.MultiSelectTempDataStacked = 0;
4580 g.MultiSelectTempData.clear_destruct();
4581 TableGcCompactSettings();
4582 for (ImFontAtlas* atlas : g.FontAtlases)
4583 atlas->CompactCache();
4584}
4585
4586// Free up/compact internal window buffers, we can use this when a window becomes unused.
4587// Not freed:
4588// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4589// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4590void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4591{
4592 window->MemoryCompacted = true;
4593 window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4594 window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4595 window->IDStack.clear();
4596 window->DrawList->_ClearFreeMemory();
4597 window->DC.ChildWindows.clear();
4598 window->DC.ItemWidthStack.clear();
4599 window->DC.TextWrapPosStack.clear();
4600}
4601
4602void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4603{
4604 // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4605 // The other buffers tends to amortize much faster.
4606 window->MemoryCompacted = false;
4607 window->DrawList->IdxBuffer.reserve(new_capacity: window->MemoryDrawListIdxCapacity);
4608 window->DrawList->VtxBuffer.reserve(new_capacity: window->MemoryDrawListVtxCapacity);
4609 window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4610}
4611
4612void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4613{
4614 ImGuiContext& g = *GImGui;
4615
4616 // Clear previous active id
4617 if (g.ActiveId != 0)
4618 {
4619 // Store deactivate data
4620 ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData;
4621 deactivated_data->ID = g.ActiveId;
4622 deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData?
4623 deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4624 deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId);
4625
4626 // This could be written in a more general way (e.g associate a hook to ActiveId),
4627 // but since this is currently quite an exception we'll leave it as is.
4628 // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
4629 if (g.InputTextState.ID == g.ActiveId)
4630 InputTextDeactivateHook(id: g.ActiveId);
4631
4632 // While most behaved code would make an effort to not steal active id during window move/drag operations,
4633 // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4634 // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4635 if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4636 {
4637 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4638 StopMouseMovingWindow();
4639 }
4640 }
4641
4642 // Set active id
4643 g.ActiveIdIsJustActivated = (g.ActiveId != id);
4644 if (g.ActiveIdIsJustActivated)
4645 {
4646 IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4647 g.ActiveIdTimer = 0.0f;
4648 g.ActiveIdHasBeenPressedBefore = false;
4649 g.ActiveIdHasBeenEditedBefore = false;
4650 g.ActiveIdMouseButton = -1;
4651 if (id != 0)
4652 {
4653 g.LastActiveId = id;
4654 g.LastActiveIdTimer = 0.0f;
4655 }
4656 }
4657 g.ActiveId = id;
4658 g.ActiveIdAllowOverlap = false;
4659 g.ActiveIdNoClearOnFocusLoss = false;
4660 g.ActiveIdWindow = window;
4661 g.ActiveIdHasBeenEditedThisFrame = false;
4662 g.ActiveIdFromShortcut = false;
4663 g.ActiveIdDisabledId = 0;
4664 if (id)
4665 {
4666 g.ActiveIdIsAlive = id;
4667 g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4668 IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4669 }
4670
4671 // Clear declaration of inputs claimed by the widget
4672 // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4673 g.ActiveIdUsingNavDirMask = 0x00;
4674 g.ActiveIdUsingAllKeyboardKeys = false;
4675}
4676
4677void ImGui::ClearActiveID()
4678{
4679 SetActiveID(id: 0, NULL); // g.ActiveId = 0;
4680}
4681
4682void ImGui::SetHoveredID(ImGuiID id)
4683{
4684 ImGuiContext& g = *GImGui;
4685 g.HoveredId = id;
4686 g.HoveredIdAllowOverlap = false;
4687 if (id != 0 && g.HoveredIdPreviousFrame != id)
4688 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4689}
4690
4691ImGuiID ImGui::GetHoveredID()
4692{
4693 ImGuiContext& g = *GImGui;
4694 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4695}
4696
4697void ImGui::MarkItemEdited(ImGuiID id)
4698{
4699 // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
4700 // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4701 ImGuiContext& g = *GImGui;
4702 if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
4703 return;
4704 if (g.ActiveId == id || g.ActiveId == 0)
4705 {
4706 // FIXME: Can't we fully rely on LastItemData yet?
4707 g.ActiveIdHasBeenEditedThisFrame = true;
4708 g.ActiveIdHasBeenEditedBefore = true;
4709 if (g.DeactivatedItemData.ID == id)
4710 g.DeactivatedItemData.HasBeenEditedBefore = true;
4711 }
4712
4713 // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4714 // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4715 IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4716
4717 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4718 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4719}
4720
4721bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4722{
4723 // An active popup disable hovering on other windows (apart from its own children)
4724 // FIXME-OPT: This could be cached/stored within the window.
4725 ImGuiContext& g = *GImGui;
4726 if (g.NavWindow)
4727 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4728 if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4729 {
4730 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4731 // NB: The 'else' is important because Modal windows are also Popups.
4732 bool want_inhibit = false;
4733 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4734 want_inhibit = true;
4735 else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4736 want_inhibit = true;
4737
4738 // Inhibit hover unless the window is within the stack of our modal/popup
4739 if (want_inhibit)
4740 if (!IsWindowWithinBeginStackOf(window: window->RootWindow, potential_parent: focused_root_window))
4741 return false;
4742 }
4743
4744 // Filter by viewport
4745 if (window->Viewport != g.MouseViewport)
4746 if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4747 return false;
4748
4749 return true;
4750}
4751
4752static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4753{
4754 ImGuiContext& g = *GImGui;
4755 if (flags & ImGuiHoveredFlags_DelayNormal)
4756 return g.Style.HoverDelayNormal;
4757 if (flags & ImGuiHoveredFlags_DelayShort)
4758 return g.Style.HoverDelayShort;
4759 return 0.0f;
4760}
4761
4762static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4763{
4764 // Allow instance flags to override shared flags
4765 if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4766 shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4767 return user_flags | shared_flags;
4768}
4769
4770// This is roughly matching the behavior of internal-facing ItemHoverable()
4771// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4772// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4773bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4774{
4775 ImGuiContext& g = *GImGui;
4776 ImGuiWindow* window = g.CurrentWindow;
4777 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
4778
4779 if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
4780 {
4781 if (!IsItemFocused())
4782 return false;
4783 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4784 return false;
4785
4786 if (flags & ImGuiHoveredFlags_ForTooltip)
4787 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipNav);
4788 }
4789 else
4790 {
4791 // Test for bounding box overlap, as updated as ItemAdd()
4792 ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4793 if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4794 return false;
4795
4796 if (flags & ImGuiHoveredFlags_ForTooltip)
4797 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
4798
4799 // Done with rectangle culling so we can perform heavier checks now
4800 // Test if we are hovering the right window (our window could be behind another window)
4801 // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4802 // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4803 // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4804 // the test that has been running for a long while.
4805 if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4806 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4807 return false;
4808
4809 // Test if another item is active (e.g. being dragged)
4810 const ImGuiID id = g.LastItemData.ID;
4811 if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4812 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4813 {
4814 // When ActiveId == MoveId it means that either:
4815 // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag)
4816 // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed.
4817 // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId.
4818 bool cancel_is_hovered = true;
4819 if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id))
4820 cancel_is_hovered = false;
4821 // When ActiveId == TabId it means user clicked docking tab for the window.
4822 if (g.ActiveId == window->TabId)
4823 cancel_is_hovered = false;
4824 if (cancel_is_hovered)
4825 return false;
4826 }
4827
4828 // Test if interactions on this window are blocked by an active popup or modal.
4829 // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4830 if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4831 return false;
4832
4833 // Test if the item is disabled
4834 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4835 return false;
4836
4837 // Special handling for calling after Begin() which represent the title bar or tab.
4838 // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4839 // will never be overwritten so we need to detect the case.
4840 if (id == window->MoveId && window->WriteAccessed)
4841 return false;
4842
4843 // Test if using AllowOverlap and overlapped
4844 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4845 if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4846 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4847 return false;
4848 }
4849
4850 // Handle hover delay
4851 // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4852 const float delay = CalcDelayFromHoveredFlags(flags);
4853 if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4854 {
4855 ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(p_abs: g.LastItemData.Rect.Min);
4856 if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4857 g.HoverItemDelayTimer = 0.0f;
4858 g.HoverItemDelayId = hover_delay_id;
4859
4860 // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4861 // but once unlocked on a given item we also moving.
4862 //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4863 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4864 return false;
4865
4866 if (g.HoverItemDelayTimer < delay)
4867 return false;
4868 }
4869
4870 return true;
4871}
4872
4873// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK.
4874// Returns whether the item was hovered, logic differs slightly from IsItemHovered().
4875// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4876// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4877// If you used this in your legacy/custom widgets code:
4878// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
4879// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4880bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4881{
4882 ImGuiContext& g = *GImGui;
4883 ImGuiWindow* window = g.CurrentWindow;
4884
4885 // Detect ID conflicts
4886 // (this is specifically done here by comparing on hover because it allows us a detection of duplicates that is algorithmically extra cheap, 1 u32 compare per item. No O(log N) lookup whatsoever)
4887#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4888 if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
4889 {
4890 g.HoveredIdPreviousFrameItemCount++;
4891 if (g.DebugDrawIdConflictsId == id)
4892 window->DrawList->AddRect(p_min: bb.Min - ImVec2(1,1), p_max: bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), rounding: 0.0f, flags: ImDrawFlags_None, thickness: 2.0f);
4893 }
4894#endif
4895
4896 if (g.HoveredWindow != window)
4897 return false;
4898 if (!IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
4899 return false;
4900
4901 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4902 return false;
4903 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4904 if (!g.ActiveIdFromShortcut)
4905 return false;
4906
4907 // We are done with rectangle culling so we can perform heavier checks now.
4908 if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, flags: ImGuiHoveredFlags_None))
4909 {
4910 g.HoveredIdIsDisabled = true;
4911 return false;
4912 }
4913
4914 // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4915 // hover test in widgets code. We could also decide to split this function is two.
4916 if (id != 0)
4917 {
4918 // Drag source doesn't report as hovered
4919 if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4920 return false;
4921
4922 SetHoveredID(id);
4923
4924 // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4925 // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4926 if (item_flags & ImGuiItemFlags_AllowOverlap)
4927 {
4928 g.HoveredIdAllowOverlap = true;
4929 if (g.HoveredIdPreviousFrame != id)
4930 return false;
4931 }
4932
4933 // Display shortcut (only works with mouse)
4934 // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4935 if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
4936 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4937 SetTooltip("%s", GetKeyChordName(key_chord: g.LastItemData.Shortcut));
4938 }
4939
4940 // When disabled we'll return false but still set HoveredId
4941 if (item_flags & ImGuiItemFlags_Disabled)
4942 {
4943 // Release active id if turning disabled
4944 if (g.ActiveId == id && id != 0)
4945 ClearActiveID();
4946 g.HoveredIdIsDisabled = true;
4947 return false;
4948 }
4949
4950#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4951 if (id != 0)
4952 {
4953 // [DEBUG] Item Picker tool!
4954 // We perform the check here because reaching is path is rare (1~ time a frame),
4955 // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4956 // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4957 if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4958 GetForegroundDrawList()->AddRect(p_min: bb.Min, p_max: bb.Max, IM_COL32(255, 255, 0, 255));
4959 if (g.DebugItemPickerBreakId == id)
4960 IM_DEBUG_BREAK();
4961 }
4962#endif
4963
4964 if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
4965 return false;
4966
4967 return true;
4968}
4969
4970// FIXME: This is inlined/duplicated in ItemAdd()
4971// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4972bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4973{
4974 ImGuiContext& g = *GImGui;
4975 ImGuiWindow* window = g.CurrentWindow;
4976 if (!bb.Overlaps(r: window->ClipRect))
4977 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4978 if (!g.ItemUnclipByLog)
4979 return true;
4980 return false;
4981}
4982
4983// This is also inlined in ItemAdd()
4984// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4985void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect)
4986{
4987 ImGuiContext& g = *GImGui;
4988 g.LastItemData.ID = item_id;
4989 g.LastItemData.ItemFlags = item_flags;
4990 g.LastItemData.StatusFlags = status_flags;
4991 g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4992}
4993
4994static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
4995{
4996 ImGuiContext& g = *GImGui;
4997 if (window->DockIsActive)
4998 SetLastItemData(item_id: window->MoveId, item_flags: g.CurrentItemFlags, status_flags: window->DC.DockTabItemStatusFlags, item_rect: window->DC.DockTabItemRect);
4999 else
5000 SetLastItemData(item_id: window->MoveId, item_flags: g.CurrentItemFlags, status_flags: window->DC.WindowItemStatusFlags, item_rect: rect);
5001}
5002
5003static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect)
5004{
5005 ImGuiContext& g = *GImGui;
5006 SetLastItemData(item_id: window->ChildId, item_flags: g.CurrentItemFlags, status_flags: window->DC.ChildItemStatusFlags, item_rect: rect);
5007}
5008
5009float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
5010{
5011 if (wrap_pos_x < 0.0f)
5012 return 0.0f;
5013
5014 ImGuiContext& g = *GImGui;
5015 ImGuiWindow* window = g.CurrentWindow;
5016 if (wrap_pos_x == 0.0f)
5017 {
5018 // We could decide to setup a default wrapping max point for auto-resizing windows,
5019 // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
5020 //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
5021 // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
5022 //else
5023 wrap_pos_x = window->WorkRect.Max.x;
5024 }
5025 else if (wrap_pos_x > 0.0f)
5026 {
5027 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
5028 }
5029
5030 return ImMax(lhs: wrap_pos_x - pos.x, rhs: 1.0f);
5031}
5032
5033// IM_ALLOC() == ImGui::MemAlloc()
5034void* ImGui::MemAlloc(size_t size)
5035{
5036 void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
5037#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5038 if (ImGuiContext* ctx = GImGui)
5039 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size);
5040#endif
5041 return ptr;
5042}
5043
5044// IM_FREE() == ImGui::MemFree()
5045void ImGui::MemFree(void* ptr)
5046{
5047#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5048 if (ptr != NULL)
5049 if (ImGuiContext* ctx = GImGui)
5050 DebugAllocHook(info: &ctx->DebugAllocInfo, frame_count: ctx->FrameCount, ptr, size: (size_t)-1);
5051#endif
5052 return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
5053}
5054
5055// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
5056void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
5057{
5058 ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5059 IM_UNUSED(ptr);
5060 if (entry->FrameCount != frame_count)
5061 {
5062 info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
5063 entry = &info->LastEntriesBuf[info->LastEntriesIdx];
5064 entry->FrameCount = frame_count;
5065 entry->AllocCount = entry->FreeCount = 0;
5066 }
5067 if (size != (size_t)-1)
5068 {
5069 //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
5070 entry->AllocCount++;
5071 info->TotalAllocCount++;
5072 }
5073 else
5074 {
5075 //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
5076 entry->FreeCount++;
5077 info->TotalFreeCount++;
5078 }
5079}
5080
5081const char* ImGui::GetClipboardText()
5082{
5083 ImGuiContext& g = *GImGui;
5084 return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : "";
5085}
5086
5087void ImGui::SetClipboardText(const char* text)
5088{
5089 ImGuiContext& g = *GImGui;
5090 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5091 g.PlatformIO.Platform_SetClipboardTextFn(&g, text);
5092}
5093
5094const char* ImGui::GetVersion()
5095{
5096 return IMGUI_VERSION;
5097}
5098
5099ImGuiIO& ImGui::GetIO()
5100{
5101 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5102 return GImGui->IO;
5103}
5104
5105// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5106ImGuiIO& ImGui::GetIO(ImGuiContext* ctx)
5107{
5108 IM_ASSERT(ctx != NULL);
5109 return ctx->IO;
5110}
5111
5112ImGuiPlatformIO& ImGui::GetPlatformIO()
5113{
5114 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
5115 return GImGui->PlatformIO;
5116}
5117
5118// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
5119ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx)
5120{
5121 IM_ASSERT(ctx != NULL);
5122 return ctx->PlatformIO;
5123}
5124
5125// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
5126ImDrawData* ImGui::GetDrawData()
5127{
5128 ImGuiContext& g = *GImGui;
5129 ImGuiViewportP* viewport = g.Viewports[0];
5130 return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
5131}
5132
5133double ImGui::GetTime()
5134{
5135 return GImGui->Time;
5136}
5137
5138int ImGui::GetFrameCount()
5139{
5140 return GImGui->FrameCount;
5141}
5142
5143static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
5144{
5145 // Create the draw list on demand, because they are not frequently used for all viewports
5146 ImGuiContext& g = *GImGui;
5147 IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
5148 ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
5149 if (draw_list == NULL)
5150 {
5151 draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
5152 draw_list->_OwnerName = drawlist_name;
5153 viewport->BgFgDrawLists[drawlist_no] = draw_list;
5154 }
5155
5156 // Our ImDrawList system requires that there is always a command
5157 if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
5158 {
5159 draw_list->_ResetForNewFrame();
5160 draw_list->PushTexture(tex_ref: g.IO.Fonts->TexRef);
5161 draw_list->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size, intersect_with_current_clip_rect: false);
5162 viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
5163 }
5164 return draw_list;
5165}
5166
5167ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
5168{
5169 if (viewport == NULL)
5170 viewport = GImGui->CurrentWindow->Viewport;
5171 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 0, drawlist_name: "##Background");
5172}
5173
5174ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
5175{
5176 if (viewport == NULL)
5177 viewport = GImGui->CurrentWindow->Viewport;
5178 return GetViewportBgFgDrawList(viewport: (ImGuiViewportP*)viewport, drawlist_no: 1, drawlist_name: "##Foreground");
5179}
5180
5181ImDrawListSharedData* ImGui::GetDrawListSharedData()
5182{
5183 return &GImGui->DrawListSharedData;
5184}
5185
5186void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
5187{
5188 // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
5189 // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
5190 // This is because we want ActiveId to be set even when the window is not permitted to move.
5191 ImGuiContext& g = *GImGui;
5192 FocusWindow(window);
5193 SetActiveID(id: window->MoveId, window);
5194 if (g.IO.ConfigNavCursorVisibleAuto)
5195 g.NavCursorVisible = false;
5196 g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
5197 g.ActiveIdNoClearOnFocusLoss = true;
5198 SetActiveIdUsingAllKeyboardKeys();
5199
5200 bool can_move_window = true;
5201 if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
5202 can_move_window = false;
5203 if (ImGuiDockNode* node = window->DockNodeAsHost)
5204 if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
5205 can_move_window = false;
5206 if (can_move_window)
5207 g.MovingWindow = window;
5208}
5209
5210// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
5211void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
5212{
5213 ImGuiContext& g = *GImGui;
5214 bool can_undock_node = false;
5215 if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
5216 {
5217 // Can undock if:
5218 // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
5219 // - part of a dockspace node hierarchy: so we can undock the last single visible node too. Undocking from a fixed/central node will create a new node and copy windows.
5220 ImGuiDockNode* root_node = DockNodeGetRootNode(node);
5221 if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
5222 can_undock_node = true;
5223 }
5224
5225 const bool clicked = IsMouseClicked(button: 0);
5226 const bool dragging = IsMouseDragging(button: 0);
5227 if (can_undock_node && dragging)
5228 DockContextQueueUndockNode(ctx: &g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
5229 else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
5230 StartMouseMovingWindow(window);
5231}
5232
5233// This is not 100% symetric with StartMouseMovingWindow().
5234// We do NOT clear ActiveID, because:
5235// - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired.
5236// - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item).
5237void ImGui::StopMouseMovingWindow()
5238{
5239 ImGuiContext& g = *GImGui;
5240 ImGuiWindow* window = g.MovingWindow;
5241
5242 // Ref commits 6b7766817, 36055213c for some partial history on checking if viewport != NULL.
5243 if (window && window->Viewport)
5244 {
5245 // Try to merge the window back into the main viewport.
5246 // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
5247 if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
5248 UpdateTryMergeWindowIntoHostViewport(window, host_viewport: g.MouseViewport);
5249
5250 // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
5251 if (!IsDragDropPayloadBeingAccepted())
5252 g.MouseViewport = window->Viewport;
5253
5254 // Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport()
5255 const bool window_can_use_inputs = ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) == false;
5256 if (window_can_use_inputs)
5257 window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
5258 }
5259 g.MovingWindow = NULL;
5260}
5261
5262// Handle mouse moving window
5263// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
5264// FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId.
5265// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
5266// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
5267void ImGui::UpdateMouseMovingWindowNewFrame()
5268{
5269 ImGuiContext& g = *GImGui;
5270 if (g.MovingWindow != NULL)
5271 {
5272 // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
5273 // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
5274 KeepAliveID(id: g.ActiveId);
5275 IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
5276 ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
5277
5278 // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
5279 const bool window_disappeared = (!moving_window->WasActive && !moving_window->Active);
5280 if (g.IO.MouseDown[0] && IsMousePosValid(mouse_pos: &g.IO.MousePos) && !window_disappeared)
5281 {
5282 ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
5283 if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
5284 {
5285 SetWindowPos(window: moving_window, pos, cond: ImGuiCond_Always);
5286 if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
5287 {
5288 moving_window->Viewport->Pos = pos;
5289 moving_window->Viewport->UpdateWorkRect();
5290 }
5291 }
5292 FocusWindow(window: g.MovingWindow);
5293 }
5294 else
5295 {
5296 StopMouseMovingWindow();
5297 ClearActiveID();
5298 }
5299 }
5300 else
5301 {
5302 // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
5303 if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
5304 {
5305 KeepAliveID(id: g.ActiveId);
5306 if (!g.IO.MouseDown[0])
5307 ClearActiveID();
5308 }
5309 }
5310}
5311
5312// Initiate focusing and moving window when clicking on empty space or title bar.
5313// Initiate focusing window when clicking on a disabled item.
5314// Handle left-click and right-click focus.
5315void ImGui::UpdateMouseMovingWindowEndFrame()
5316{
5317 ImGuiContext& g = *GImGui;
5318 if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
5319 return;
5320
5321 // Unless we just made a window/popup appear
5322 if (g.NavWindow && g.NavWindow->Appearing)
5323 return;
5324
5325 // Click on empty space to focus window and start moving
5326 // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
5327 if (g.IO.MouseClicked[0])
5328 {
5329 // Handle the edge case of a popup being closed while clicking in its empty space.
5330 // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
5331 ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
5332 const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(id: root_window->PopupId, popup_flags: ImGuiPopupFlags_AnyPopupLevel);
5333
5334 if (root_window != NULL && !is_closed_popup)
5335 {
5336 StartMouseMovingWindow(window: g.HoveredWindow); //-V595
5337
5338 // FIXME: In principal we might be able to call StopMouseMovingWindow() below.
5339 // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId.
5340
5341 // Cancel moving if clicked outside of title bar
5342 if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
5343 if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
5344 if (!root_window->TitleBarRect().Contains(p: g.IO.MouseClickedPos[0]))
5345 g.MovingWindow = NULL;
5346
5347 // Cancel moving if clicked over an item which was disabled or inhibited by popups
5348 // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)
5349 if (g.HoveredIdIsDisabled)
5350 {
5351 g.MovingWindow = NULL;
5352 g.ActiveIdDisabledId = g.HoveredId;
5353 }
5354 }
5355 else if (root_window == NULL && g.NavWindow != NULL)
5356 {
5357 // Clicking on void disable focus
5358 FocusWindow(NULL, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
5359 }
5360 }
5361
5362 // With right mouse button we close popups without changing focus based on where the mouse is aimed
5363 // Instead, focus will be restored to the window under the bottom-most closed popup.
5364 // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
5365 if (g.IO.MouseClicked[1] && g.HoveredId == 0)
5366 {
5367 // Find the top-most window between HoveredWindow and the top-most Modal Window.
5368 // This is where we can trim the popup stack.
5369 ImGuiWindow* modal = GetTopMostPopupModal();
5370 bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(potential_above: g.HoveredWindow, potential_below: modal));
5371 ClosePopupsOverWindow(ref_window: hovered_window_above_modal ? g.HoveredWindow : modal, restore_focus_to_window_under_popup: true);
5372 }
5373}
5374
5375// This is called during NewFrame()->UpdateViewportsNewFrame() only.
5376// Need to keep in sync with SetWindowPos()
5377static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
5378{
5379 window->Pos += delta;
5380 window->ClipRect.Translate(d: delta);
5381 window->OuterRectClipped.Translate(d: delta);
5382 window->InnerRect.Translate(d: delta);
5383 window->DC.CursorPos += delta;
5384 window->DC.CursorStartPos += delta;
5385 window->DC.CursorMaxPos += delta;
5386 window->DC.IdealMaxPos += delta;
5387}
5388
5389static void ScaleWindow(ImGuiWindow* window, float scale)
5390{
5391 ImVec2 origin = window->Viewport->Pos;
5392 window->Pos = ImFloor(v: (window->Pos - origin) * scale + origin);
5393 window->Size = ImTrunc(v: window->Size * scale);
5394 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
5395 window->ContentSize = ImTrunc(v: window->ContentSize * scale);
5396}
5397
5398static bool IsWindowActiveAndVisible(ImGuiWindow* window)
5399{
5400 return (window->Active) && (!window->Hidden);
5401}
5402
5403// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
5404void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos)
5405{
5406 ImGuiContext& g = *GImGui;
5407 ImGuiIO& io = g.IO;
5408
5409 // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
5410 // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
5411 g.WindowsBorderHoverPadding = ImMax(lhs: ImMax(lhs: g.Style.TouchExtraPadding.x, rhs: g.Style.TouchExtraPadding.y), rhs: g.Style.WindowBorderHoverPadding);
5412
5413 // Find the window hovered by mouse:
5414 // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
5415 // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
5416 // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
5417 bool clear_hovered_windows = false;
5418 FindHoveredWindowEx(pos: mouse_pos, find_first_and_in_any_viewport: false, out_hovered_window: &g.HoveredWindow, out_hovered_window_under_moving_window: &g.HoveredWindowUnderMovingWindow);
5419 IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
5420 g.HoveredWindowBeforeClear = g.HoveredWindow;
5421
5422 // Modal windows prevents mouse from hovering behind them.
5423 ImGuiWindow* modal_window = GetTopMostPopupModal();
5424 if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(window: g.HoveredWindow->RootWindow, potential_parent: modal_window)) // FIXME-MERGE: RootWindowDockTree ?
5425 clear_hovered_windows = true;
5426
5427 // Disabled mouse hovering (we don't currently clear MousePos, we could)
5428 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
5429 clear_hovered_windows = true;
5430
5431 // We track click ownership. When clicked outside of a window the click is owned by the application and
5432 // won't report hovering nor request capture even while dragging over our windows afterward.
5433 const bool has_open_popup = (g.OpenPopupStack.Size > 0);
5434 const bool has_open_modal = (modal_window != NULL);
5435 int mouse_earliest_down = -1;
5436 bool mouse_any_down = false;
5437 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
5438 {
5439 if (io.MouseClicked[i])
5440 {
5441 io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
5442 io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
5443 }
5444 mouse_any_down |= io.MouseDown[i];
5445 if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
5446 if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
5447 mouse_earliest_down = i;
5448 }
5449 const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
5450 const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
5451
5452 // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
5453 // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
5454 const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
5455 if (!mouse_avail && !mouse_dragging_extern_payload)
5456 clear_hovered_windows = true;
5457
5458 if (clear_hovered_windows)
5459 g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5460
5461 // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
5462 // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
5463 if (g.WantCaptureMouseNextFrame != -1)
5464 {
5465 io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
5466 }
5467 else
5468 {
5469 io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
5470 io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
5471 }
5472
5473 // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
5474 io.WantCaptureKeyboard = false;
5475 if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
5476 {
5477 if ((g.ActiveId != 0) || (modal_window != NULL))
5478 io.WantCaptureKeyboard = true;
5479 else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
5480 io.WantCaptureKeyboard = true;
5481 }
5482 if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
5483 io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
5484
5485 // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
5486 io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
5487}
5488
5489// Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
5490// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
5491static void SetupDrawListSharedData()
5492{
5493 ImGuiContext& g = *GImGui;
5494 ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
5495 for (ImGuiViewportP* viewport : g.Viewports)
5496 virtual_space.Add(r: viewport->GetMainRect());
5497 g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
5498 g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
5499 g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
5500 g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
5501 if (g.Style.AntiAliasedLines)
5502 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
5503 if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
5504 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
5505 if (g.Style.AntiAliasedFill)
5506 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
5507 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
5508 g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
5509 g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments.
5510}
5511
5512void ImGui::NewFrame()
5513{
5514 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
5515 ImGuiContext& g = *GImGui;
5516
5517 // Remove pending delete hooks before frame start.
5518 // This deferred removal avoid issues of removal while iterating the hook vector
5519 for (int n = g.Hooks.Size - 1; n >= 0; n--)
5520 if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
5521 g.Hooks.erase(it: &g.Hooks[n]);
5522
5523 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePre);
5524
5525 // Check and assert for various common IO and Configuration mistakes
5526 g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
5527 ErrorCheckNewFrameSanityChecks();
5528 g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
5529
5530 // Load settings on first frame, save settings when modified (after a delay)
5531 UpdateSettings();
5532
5533 g.Time += g.IO.DeltaTime;
5534 g.FrameCount += 1;
5535 g.TooltipOverrideCount = 0;
5536 g.WindowsActiveCount = 0;
5537 g.MenusIdSubmittedThisFrame.resize(new_size: 0);
5538
5539 // Calculate frame-rate for the user, as a purely luxurious feature
5540 g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
5541 g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
5542 g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
5543 g.FramerateSecPerFrameCount = ImMin(lhs: g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
5544 g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
5545
5546 // Process input queue (trickle as many events as possible), turn events into writes to IO structure
5547 g.InputEventsTrail.resize(new_size: 0);
5548 UpdateInputEvents(trickle_fast_inputs: g.IO.ConfigInputTrickleEventQueue);
5549
5550 // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
5551 UpdateViewportsNewFrame();
5552
5553 // Update texture list (collect destroyed textures, etc.)
5554 UpdateTexturesNewFrame();
5555
5556 // Setup current font and draw list shared data
5557 SetupDrawListSharedData();
5558 UpdateFontsNewFrame();
5559
5560 g.WithinFrameScope = true;
5561
5562 // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
5563 for (ImGuiViewportP* viewport : g.Viewports)
5564 {
5565 viewport->DrawData = NULL;
5566 viewport->DrawDataP.Valid = false;
5567 }
5568
5569 // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
5570 if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
5571 KeepAliveID(id: g.DragDropPayload.SourceId);
5572
5573 // [DEBUG]
5574 if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
5575 g.DebugDrawIdConflictsId = 0;
5576 if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
5577 g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame;
5578
5579 // Update HoveredId data
5580 if (!g.HoveredIdPreviousFrame)
5581 g.HoveredIdTimer = 0.0f;
5582 if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
5583 g.HoveredIdNotActiveTimer = 0.0f;
5584 if (g.HoveredId)
5585 g.HoveredIdTimer += g.IO.DeltaTime;
5586 if (g.HoveredId && g.ActiveId != g.HoveredId)
5587 g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
5588 g.HoveredIdPreviousFrame = g.HoveredId;
5589 g.HoveredIdPreviousFrameItemCount = 0;
5590 g.HoveredId = 0;
5591 g.HoveredIdAllowOverlap = false;
5592 g.HoveredIdIsDisabled = false;
5593
5594 // Clear ActiveID if the item is not alive anymore.
5595 // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
5596 // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
5597 if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
5598 {
5599 IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
5600 ClearActiveID();
5601 }
5602
5603 // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
5604 if (g.ActiveId)
5605 g.ActiveIdTimer += g.IO.DeltaTime;
5606 g.LastActiveIdTimer += g.IO.DeltaTime;
5607 g.ActiveIdPreviousFrame = g.ActiveId;
5608 g.ActiveIdIsAlive = 0;
5609 g.ActiveIdHasBeenEditedThisFrame = false;
5610 g.ActiveIdIsJustActivated = false;
5611 if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
5612 g.TempInputId = 0;
5613 if (g.ActiveId == 0)
5614 {
5615 g.ActiveIdUsingNavDirMask = 0x00;
5616 g.ActiveIdUsingAllKeyboardKeys = false;
5617 }
5618 if (g.DeactivatedItemData.ElapseFrame < g.FrameCount)
5619 g.DeactivatedItemData.ID = 0;
5620 g.DeactivatedItemData.IsAlive = false;
5621
5622 // Record when we have been stationary as this state is preserved while over same item.
5623 // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5624 // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5625 if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5626 g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5627 else if (g.HoverItemDelayId == 0)
5628 g.HoverItemUnlockedStationaryId = 0;
5629 if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5630 g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5631 else if (g.HoveredWindow == NULL)
5632 g.HoverWindowUnlockedStationaryId = 0;
5633
5634 // Update hover delay for IsItemHovered() with delays and tooltips
5635 g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5636 if (g.HoverItemDelayId != 0)
5637 {
5638 g.HoverItemDelayTimer += g.IO.DeltaTime;
5639 g.HoverItemDelayClearTimer = 0.0f;
5640 g.HoverItemDelayId = 0;
5641 }
5642 else if (g.HoverItemDelayTimer > 0.0f)
5643 {
5644 // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5645 // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5646 g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5647 if (g.HoverItemDelayClearTimer >= ImMax(lhs: 0.25f, rhs: g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5648 g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
5649 }
5650
5651 // Drag and drop
5652 g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5653 g.DragDropAcceptIdCurr = 0;
5654 g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5655 g.DragDropWithinSource = false;
5656 g.DragDropWithinTarget = false;
5657 g.DragDropHoldJustPressedId = 0;
5658 g.TooltipPreviousWindow = NULL;
5659
5660 // Close popups on focus lost (currently wip/opt-in)
5661 //if (g.IO.AppFocusLost)
5662 // ClosePopupsExceptModals();
5663
5664 // Update keyboard input state
5665 UpdateKeyboardInputs();
5666
5667 //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5668 //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5669 //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5670 //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5671
5672 // Update keyboard/gamepad navigation
5673 NavUpdate();
5674
5675 // Update mouse input state
5676 UpdateMouseInputs();
5677
5678 // Undocking
5679 // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5680 DockContextNewFrameUpdateUndocking(ctx: &g);
5681
5682 // Mark all windows as not visible and compact unused memory.
5683 IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5684 const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5685 for (ImGuiWindow* window : g.Windows)
5686 {
5687 window->WasActive = window->Active;
5688 window->Active = false;
5689 window->WriteAccessed = false;
5690 window->BeginCountPreviousFrame = window->BeginCount;
5691 window->BeginCount = 0;
5692
5693 // Garbage collect transient buffers of recently unused windows
5694 if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5695 GcCompactTransientWindowBuffers(window);
5696 }
5697
5698 // Find hovered window
5699 // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5700 // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
5701 UpdateHoveredWindowAndCaptureFlags(mouse_pos: g.IO.MousePos);
5702
5703 // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5704 UpdateMouseMovingWindowNewFrame();
5705
5706 // Background darkening/whitening
5707 if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5708 g.DimBgRatio = ImMin(lhs: g.DimBgRatio + g.IO.DeltaTime * 6.0f, rhs: 1.0f);
5709 else
5710 g.DimBgRatio = ImMax(lhs: g.DimBgRatio - g.IO.DeltaTime * 10.0f, rhs: 0.0f);
5711
5712 g.MouseCursor = ImGuiMouseCursor_Arrow;
5713 g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5714
5715 // Platform IME data: reset for the frame
5716 g.PlatformImeDataPrev = g.PlatformImeData;
5717 g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false;
5718
5719 // Mouse wheel scrolling, scale
5720 UpdateMouseWheel();
5721
5722 // Garbage collect transient buffers of recently unused tables
5723 for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5724 if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5725 TableGcCompactTransientBuffers(table: g.Tables.GetByIndex(n: i));
5726 for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5727 if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5728 TableGcCompactTransientBuffers(table: &table_temp_data);
5729 if (g.GcCompactAll)
5730 GcCompactTransientMiscBuffers();
5731 g.GcCompactAll = false;
5732
5733 // Closing the focused window restore focus to the first active root window in descending z-order
5734 if (g.NavWindow && !g.NavWindow->WasActive)
5735 FocusTopMostWindowUnderOne(NULL, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
5736
5737 // No window should be open at the beginning of the frame.
5738 // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5739 g.CurrentWindowStack.resize(new_size: 0);
5740 g.BeginPopupStack.resize(new_size: 0);
5741 g.ItemFlagsStack.resize(new_size: 0);
5742 g.ItemFlagsStack.push_back(v: ImGuiItemFlags_AutoClosePopups); // Default flags
5743 g.CurrentItemFlags = g.ItemFlagsStack.back();
5744 g.GroupStack.resize(new_size: 0);
5745
5746 // Docking
5747 DockContextNewFrameUpdateDocking(ctx: &g);
5748
5749 // [DEBUG] Update debug features
5750#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5751 UpdateDebugToolItemPicker();
5752 UpdateDebugToolStackQueries();
5753 UpdateDebugToolFlashStyleColor();
5754 if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5755 {
5756 g.DebugLocateId = 0;
5757 g.DebugBreakInLocateId = false;
5758 }
5759 if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5760 {
5761 DebugLog(fmt: "(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5762 g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5763 g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5764 }
5765#endif
5766
5767 // Create implicit/fallback window - which we will only render it if the user has added something to it.
5768 // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5769 // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5770 g.WithinFrameScopeWithImplicitWindow = true;
5771 SetNextWindowSize(size: ImVec2(400, 400), cond: ImGuiCond_FirstUseEver);
5772 Begin(name: "Debug##Default");
5773 IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5774
5775 // Store stack sizes
5776 g.ErrorCountCurrentFrame = 0;
5777 ErrorRecoveryStoreState(state_out: &g.StackSizesInNewFrame);
5778
5779 // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5780 // allowing to validate correct Begin/End behavior in user code.
5781#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5782 if (g.IO.ConfigDebugBeginReturnValueLoop)
5783 g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5784 else
5785 g.DebugBeginReturnValueCullDepth = -1;
5786#endif
5787
5788 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_NewFramePost);
5789}
5790
5791// FIXME: Add a more explicit sort order in the window structure.
5792static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5793{
5794 const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5795 const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5796 if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5797 return d;
5798 if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5799 return d;
5800 return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5801}
5802
5803static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5804{
5805 out_sorted_windows->push_back(v: window);
5806 if (window->Active)
5807 {
5808 int count = window->DC.ChildWindows.Size;
5809 ImQsort(base: window->DC.ChildWindows.Data, count: (size_t)count, size_of_element: sizeof(ImGuiWindow*), compare_func: ChildWindowComparer);
5810 for (int i = 0; i < count; i++)
5811 {
5812 ImGuiWindow* child = window->DC.ChildWindows[i];
5813 if (child->Active)
5814 AddWindowToSortBuffer(out_sorted_windows, window: child);
5815 }
5816 }
5817}
5818
5819static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5820{
5821 ImGuiContext& g = *GImGui;
5822 ImGuiViewportP* viewport = window->Viewport;
5823 IM_ASSERT(viewport != NULL);
5824 g.IO.MetricsRenderWindows++;
5825 if (window->DrawList->_Splitter._Count > 1)
5826 window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5827 ImGui::AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[layer], draw_list: window->DrawList);
5828 for (ImGuiWindow* child : window->DC.ChildWindows)
5829 if (IsWindowActiveAndVisible(window: child)) // Clipped children may have been marked not active
5830 AddWindowToDrawData(window: child, layer);
5831}
5832
5833static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5834{
5835 return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5836}
5837
5838// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5839static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5840{
5841 AddWindowToDrawData(window, layer: GetWindowDisplayLayer(window));
5842}
5843
5844static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5845{
5846 int n = builder->Layers[0]->Size;
5847 int full_size = n;
5848 for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5849 full_size += builder->Layers[i]->Size;
5850 builder->Layers[0]->resize(new_size: full_size);
5851 for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5852 {
5853 ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5854 if (layer->empty())
5855 continue;
5856 memcpy(dest: builder->Layers[0]->Data + n, src: layer->Data, n: layer->Size * sizeof(ImDrawList*));
5857 n += layer->Size;
5858 layer->resize(new_size: 0);
5859 }
5860}
5861
5862static void InitViewportDrawData(ImGuiViewportP* viewport)
5863{
5864 ImGuiIO& io = ImGui::GetIO();
5865 ImDrawData* draw_data = &viewport->DrawDataP;
5866
5867 viewport->DrawData = draw_data; // Make publicly accessible
5868 viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5869 viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5870 viewport->DrawDataBuilder.Layers[0]->resize(new_size: 0);
5871 viewport->DrawDataBuilder.Layers[1]->resize(new_size: 0);
5872
5873 // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5874 // and to allow applications/backends to easily skip rendering.
5875 // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5876 // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5877 // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5878 const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5879
5880 draw_data->Valid = true;
5881 draw_data->CmdListsCount = 0;
5882 draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5883 draw_data->DisplayPos = viewport->Pos;
5884 draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5885 draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale;
5886 draw_data->OwnerViewport = viewport;
5887 draw_data->Textures = &ImGui::GetPlatformIO().Textures;
5888}
5889
5890// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5891// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5892// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5893// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5894// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5895// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5896// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack,
5897// which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts.
5898void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5899{
5900 ImGuiWindow* window = GetCurrentWindow();
5901 window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5902 window->ClipRect = window->DrawList->_ClipRectStack.back();
5903}
5904
5905void ImGui::PopClipRect()
5906{
5907 ImGuiWindow* window = GetCurrentWindow();
5908 window->DrawList->PopClipRect();
5909 window->ClipRect = window->DrawList->_ClipRectStack.back();
5910}
5911
5912static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5913{
5914 for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5915 if (IsWindowActiveAndVisible(window: window->DC.ChildWindows[n]))
5916 return FindFrontMostVisibleChildWindow(window: window->DC.ChildWindows[n]);
5917 return window;
5918}
5919
5920static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5921{
5922 if ((col & IM_COL32_A_MASK) == 0)
5923 return;
5924
5925 ImGuiViewportP* viewport = window->Viewport;
5926 ImRect viewport_rect = viewport->GetMainRect();
5927
5928 // Draw behind window by moving the draw command at the FRONT of the draw list
5929 {
5930 // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5931 // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5932 ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5933 draw_list->ChannelsMerge();
5934 if (draw_list->CmdBuffer.Size == 0)
5935 draw_list->AddDrawCmd();
5936 draw_list->PushClipRect(clip_rect_min: viewport_rect.Min - ImVec2(1, 1), clip_rect_max: viewport_rect.Max + ImVec2(1, 1), intersect_with_current_clip_rect: false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5937 draw_list->AddRectFilled(p_min: viewport_rect.Min, p_max: viewport_rect.Max, col);
5938 ImDrawCmd cmd = draw_list->CmdBuffer.back();
5939 IM_ASSERT(cmd.ElemCount == 6);
5940 draw_list->CmdBuffer.pop_back();
5941 draw_list->CmdBuffer.push_front(v: cmd);
5942 draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5943 draw_list->PopClipRect();
5944 }
5945
5946 // Draw over sibling docking nodes in a same docking tree
5947 if (window->RootWindow->DockIsActive)
5948 {
5949 ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window: window->RootWindowDockTree)->DrawList;
5950 draw_list->ChannelsMerge();
5951 if (draw_list->CmdBuffer.Size == 0)
5952 draw_list->AddDrawCmd();
5953 draw_list->PushClipRect(clip_rect_min: viewport_rect.Min, clip_rect_max: viewport_rect.Max, intersect_with_current_clip_rect: false);
5954 RenderRectFilledWithHole(draw_list, outer: window->RootWindowDockTree->Rect(), inner: window->RootWindow->Rect(), col, rounding: 0.0f);// window->RootWindowDockTree->WindowRounding);
5955 draw_list->PopClipRect();
5956 }
5957}
5958
5959ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5960{
5961 ImGuiContext& g = *GImGui;
5962 ImGuiWindow* bottom_most_visible_window = parent_window;
5963 for (int i = FindWindowDisplayIndex(window: parent_window); i >= 0; i--)
5964 {
5965 ImGuiWindow* window = g.Windows[i];
5966 if (window->Flags & ImGuiWindowFlags_ChildWindow)
5967 continue;
5968 if (!IsWindowWithinBeginStackOf(window, potential_parent: parent_window))
5969 break;
5970 if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(window: parent_window))
5971 bottom_most_visible_window = window;
5972 }
5973 return bottom_most_visible_window;
5974}
5975
5976// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5977// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5978static void ImGui::RenderDimmedBackgrounds()
5979{
5980 ImGuiContext& g = *GImGui;
5981 ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5982 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5983 return;
5984 const bool dim_bg_for_modal = (modal_window != NULL);
5985 const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5986 if (!dim_bg_for_modal && !dim_bg_for_window_list)
5987 return;
5988
5989 ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5990 if (dim_bg_for_modal)
5991 {
5992 // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5993 ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(parent_window: modal_window);
5994 RenderDimmedBackgroundBehindWindow(window: dim_behind_window, col: GetColorU32(col: modal_window->DC.ModalDimBgColor, alpha_mul: g.DimBgRatio));
5995 viewports_already_dimmed[0] = modal_window->Viewport;
5996 }
5997 else if (dim_bg_for_window_list)
5998 {
5999 // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
6000 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingTargetAnim, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
6001 if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
6002 RenderDimmedBackgroundBehindWindow(window: g.NavWindowingListWindow, col: GetColorU32(idx: ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio));
6003 viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
6004 viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
6005
6006 // Draw border around CTRL+Tab target window
6007 ImGuiWindow* window = g.NavWindowingTargetAnim;
6008 ImGuiViewport* viewport = window->Viewport;
6009 float distance = g.FontSize;
6010 ImRect bb = window->Rect();
6011 bb.Expand(amount: distance);
6012 if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
6013 bb.Expand(amount: -distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
6014 window->DrawList->ChannelsMerge();
6015 if (window->DrawList->CmdBuffer.Size == 0)
6016 window->DrawList->AddDrawCmd();
6017 window->DrawList->PushClipRect(clip_rect_min: viewport->Pos, clip_rect_max: viewport->Pos + viewport->Size);
6018 window->DrawList->AddRect(p_min: bb.Min, p_max: bb.Max, col: GetColorU32(idx: ImGuiCol_NavWindowingHighlight, alpha_mul: g.NavWindowingHighlightAlpha), rounding: window->WindowRounding, flags: 0, thickness: 3.0f); // FIXME-DPI
6019 window->DrawList->PopClipRect();
6020 }
6021
6022 // Draw dimming background on _other_ viewports than the ones our windows are in
6023 for (ImGuiViewportP* viewport : g.Viewports)
6024 {
6025 if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
6026 continue;
6027 if (modal_window && viewport->Window && IsWindowAbove(potential_above: viewport->Window, potential_below: modal_window))
6028 continue;
6029 ImDrawList* draw_list = GetForegroundDrawList(viewport);
6030 const ImU32 dim_bg_col = GetColorU32(idx: dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, alpha_mul: g.DimBgRatio);
6031 draw_list->AddRectFilled(p_min: viewport->Pos, p_max: viewport->Pos + viewport->Size, col: dim_bg_col);
6032 }
6033}
6034
6035// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
6036void ImGui::EndFrame()
6037{
6038 ImGuiContext& g = *GImGui;
6039 IM_ASSERT(g.Initialized);
6040
6041 // Don't process EndFrame() multiple times.
6042 if (g.FrameCountEnded == g.FrameCount)
6043 return;
6044 if (!g.WithinFrameScope)
6045 {
6046 IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?");
6047 return;
6048 }
6049
6050 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePre);
6051
6052 // [EXPERIMENTAL] Recover from errors
6053 if (g.IO.ConfigErrorRecovery)
6054 ErrorRecoveryTryToRecoverState(state_in: &g.StackSizesInNewFrame);
6055 ErrorCheckEndFrameSanityChecks();
6056 ErrorCheckEndFrameFinalizeErrorTooltip();
6057
6058 // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
6059 ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
6060 if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(s1: ime_data, s2: &g.PlatformImeDataPrev, n: sizeof(ImGuiPlatformImeData)) != 0)
6061 {
6062 ImGuiViewport* viewport = FindViewportByID(id: ime_data->ViewportId);
6063 IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
6064 if (viewport == NULL)
6065 viewport = GetMainViewport();
6066 g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data);
6067 }
6068 g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0;
6069
6070 // Hide implicit/fallback "Debug" window if it hasn't been used
6071 g.WithinFrameScopeWithImplicitWindow = false;
6072 if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
6073 g.CurrentWindow->Active = false;
6074 End();
6075
6076 // Update navigation: CTRL+Tab, wrap-around requests
6077 NavEndFrame();
6078
6079 // Update docking
6080 DockContextEndFrame(ctx: &g);
6081
6082 SetCurrentViewport(NULL, NULL);
6083
6084 // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
6085 if (g.DragDropActive)
6086 {
6087 bool is_delivered = g.DragDropPayload.Delivery;
6088 bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(button: g.DragDropMouseButton));
6089 if (is_delivered || is_elapsed)
6090 ClearDragDrop();
6091 }
6092
6093 // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
6094 // If you want to handle source item disappearing: instead of submitting your description tooltip
6095 // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
6096 // (e.g. end of your item loop, or before EndFrame) by reading payload data.
6097 // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
6098 if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
6099 {
6100 g.DragDropWithinSource = true;
6101 SetTooltip("...");
6102 g.DragDropWithinSource = false;
6103 }
6104
6105 // End frame
6106 g.WithinFrameScope = false;
6107 g.FrameCountEnded = g.FrameCount;
6108 UpdateFontsEndFrame();
6109
6110 // Initiate moving window + handle left-click and right-click focus
6111 UpdateMouseMovingWindowEndFrame();
6112
6113 // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
6114 UpdateViewportsEndFrame();
6115
6116 // Sort the window list so that all child windows are after their parent
6117 // We cannot do that on FocusWindow() because children may not exist yet
6118 g.WindowsTempSortBuffer.resize(new_size: 0);
6119 g.WindowsTempSortBuffer.reserve(new_capacity: g.Windows.Size);
6120 for (ImGuiWindow* window : g.Windows)
6121 {
6122 if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
6123 continue;
6124 AddWindowToSortBuffer(out_sorted_windows: &g.WindowsTempSortBuffer, window);
6125 }
6126
6127 // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
6128 IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
6129 g.Windows.swap(rhs&: g.WindowsTempSortBuffer);
6130 g.IO.MetricsActiveWindows = g.WindowsActiveCount;
6131
6132 UpdateTexturesEndFrame();
6133
6134 // Unlock font atlas
6135 for (ImFontAtlas* atlas : g.FontAtlases)
6136 atlas->Locked = false;
6137
6138 // Clear Input data for next frame
6139 g.IO.MousePosPrev = g.IO.MousePos;
6140 g.IO.AppFocusLost = false;
6141 g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
6142 g.IO.InputQueueCharacters.resize(new_size: 0);
6143
6144 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_EndFramePost);
6145}
6146
6147// Prepare the data for rendering so you can call GetDrawData()
6148// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all:
6149// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
6150void ImGui::Render()
6151{
6152 ImGuiContext& g = *GImGui;
6153 IM_ASSERT(g.Initialized);
6154
6155 if (g.FrameCountEnded != g.FrameCount)
6156 EndFrame();
6157 if (g.FrameCountRendered == g.FrameCount)
6158 return;
6159 g.FrameCountRendered = g.FrameCount;
6160
6161 g.IO.MetricsRenderWindows = 0;
6162 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPre);
6163
6164 // Add background ImDrawList (for each active viewport)
6165 for (ImGuiViewportP* viewport : g.Viewports)
6166 {
6167 InitViewportDrawData(viewport);
6168 if (viewport->BgFgDrawLists[0] != NULL)
6169 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetBackgroundDrawList(viewport));
6170 }
6171
6172 // Draw modal/window whitening backgrounds
6173 RenderDimmedBackgrounds();
6174
6175 // Add ImDrawList to render
6176 ImGuiWindow* windows_to_render_top_most[2];
6177 windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
6178 windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
6179 for (ImGuiWindow* window : g.Windows)
6180 {
6181 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
6182 if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
6183 AddRootWindowToDrawData(window);
6184 }
6185 for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
6186 if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(window: windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
6187 AddRootWindowToDrawData(window: windows_to_render_top_most[n]);
6188
6189 // Draw software mouse cursor if requested by io.MouseDrawCursor flag
6190 if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
6191 RenderMouseCursor(base_pos: g.IO.MousePos, base_scale: g.Style.MouseCursorScale, mouse_cursor: g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
6192
6193 // Setup ImDrawData structures for end-user
6194 g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
6195 for (ImGuiViewportP* viewport : g.Viewports)
6196 {
6197 FlattenDrawDataIntoSingleLayer(builder: &viewport->DrawDataBuilder);
6198
6199 // Add foreground ImDrawList (for each active viewport)
6200 if (viewport->BgFgDrawLists[1] != NULL)
6201 AddDrawListToDrawDataEx(draw_data: &viewport->DrawDataP, out_list: viewport->DrawDataBuilder.Layers[0], draw_list: GetForegroundDrawList(viewport));
6202
6203 // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
6204 ImDrawData* draw_data = &viewport->DrawDataP;
6205 IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
6206 for (ImDrawList* draw_list : draw_data->CmdLists)
6207 draw_list->_PopUnusedDrawCmd();
6208
6209 g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
6210 g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
6211 }
6212
6213#ifndef IMGUI_DISABLE_DEBUG_TOOLS
6214 if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)
6215 for (ImFontAtlas* atlas : g.FontAtlases)
6216 ImFontAtlasDebugLogTextureRequests(atlas);
6217#endif
6218
6219 CallContextHooks(ctx: &g, hook_type: ImGuiContextHookType_RenderPost);
6220}
6221
6222// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
6223// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
6224ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
6225{
6226 ImGuiContext& g = *GImGui;
6227
6228 const char* text_display_end;
6229 if (hide_text_after_double_hash)
6230 text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
6231 else
6232 text_display_end = text_end;
6233
6234 ImFont* font = g.Font;
6235 const float font_size = g.FontSize;
6236 if (text == text_display_end)
6237 return ImVec2(0.0f, font_size);
6238 ImVec2 text_size = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width, text_begin: text, text_end: text_display_end, NULL);
6239
6240 // Round
6241 // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
6242 // FIXME: Investigate using ceilf or e.g.
6243 // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
6244 // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
6245 text_size.x = IM_TRUNC(text_size.x + 0.99999f);
6246
6247 return text_size;
6248}
6249
6250// Find window given position, search front-to-back
6251// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
6252// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
6253// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
6254// called, aka before the next Begin(). Moving window isn't affected.
6255// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
6256void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
6257{
6258 ImGuiContext& g = *GImGui;
6259 ImGuiWindow* hovered_window = NULL;
6260 ImGuiWindow* hovered_window_under_moving_window = NULL;
6261
6262 // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
6263 ImGuiViewportP* backup_moving_window_viewport = NULL;
6264 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6265 {
6266 backup_moving_window_viewport = g.MovingWindow->Viewport;
6267 g.MovingWindow->Viewport = g.MouseViewport;
6268 if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
6269 hovered_window = g.MovingWindow;
6270 }
6271
6272 ImVec2 padding_regular = g.Style.TouchExtraPadding;
6273 ImVec2 padding_for_resize = ImMax(lhs: g.Style.TouchExtraPadding, rhs: ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding));
6274 for (int i = g.Windows.Size - 1; i >= 0; i--)
6275 {
6276 ImGuiWindow* window = g.Windows[i];
6277 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6278 if (!window->WasActive || window->Hidden)
6279 continue;
6280 if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
6281 continue;
6282 IM_ASSERT(window->Viewport);
6283 if (window->Viewport != g.MouseViewport)
6284 continue;
6285
6286 // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
6287 ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
6288 if (!window->OuterRectClipped.ContainsWithPad(p: pos, pad: hit_padding))
6289 continue;
6290
6291 // Support for one rectangular hole in any given window
6292 // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
6293 if (window->HitTestHoleSize.x != 0)
6294 {
6295 ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
6296 ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
6297 if (ImRect(hole_pos, hole_pos + hole_size).Contains(p: pos))
6298 continue;
6299 }
6300
6301 if (find_first_and_in_any_viewport)
6302 {
6303 hovered_window = window;
6304 break;
6305 }
6306 else
6307 {
6308 if (hovered_window == NULL)
6309 hovered_window = window;
6310 IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
6311 if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
6312 hovered_window_under_moving_window = window;
6313 if (hovered_window && hovered_window_under_moving_window)
6314 break;
6315 }
6316 }
6317
6318 *out_hovered_window = hovered_window;
6319 if (out_hovered_window_under_moving_window != NULL)
6320 *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
6321 if (find_first_and_in_any_viewport == false && g.MovingWindow)
6322 g.MovingWindow->Viewport = backup_moving_window_viewport;
6323}
6324
6325bool ImGui::IsItemActive()
6326{
6327 ImGuiContext& g = *GImGui;
6328 if (g.ActiveId)
6329 return g.ActiveId == g.LastItemData.ID;
6330 return false;
6331}
6332
6333bool ImGui::IsItemActivated()
6334{
6335 ImGuiContext& g = *GImGui;
6336 if (g.ActiveId)
6337 if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
6338 return true;
6339 return false;
6340}
6341
6342bool ImGui::IsItemDeactivated()
6343{
6344 ImGuiContext& g = *GImGui;
6345 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
6346 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
6347 return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount);
6348}
6349
6350bool ImGui::IsItemDeactivatedAfterEdit()
6351{
6352 ImGuiContext& g = *GImGui;
6353 return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore;
6354}
6355
6356// == (GetItemID() == GetFocusID() && GetFocusID() != 0)
6357bool ImGui::IsItemFocused()
6358{
6359 ImGuiContext& g = *GImGui;
6360 if (g.NavId != g.LastItemData.ID || g.NavId == 0)
6361 return false;
6362
6363 // Special handling for the dummy item after Begin() which represent the title bar or tab.
6364 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
6365 ImGuiWindow* window = g.CurrentWindow;
6366 if (g.LastItemData.ID == window->ID && window->WriteAccessed)
6367 return false;
6368
6369 return true;
6370}
6371
6372// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
6373// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
6374bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
6375{
6376 return IsMouseClicked(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_None);
6377}
6378
6379bool ImGui::IsItemToggledOpen()
6380{
6381 ImGuiContext& g = *GImGui;
6382 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
6383}
6384
6385// Call after a Selectable() or TreeNode() involved in multi-selection.
6386// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
6387// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
6388// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
6389// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
6390bool ImGui::IsItemToggledSelection()
6391{
6392 ImGuiContext& g = *GImGui;
6393 IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
6394 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
6395}
6396
6397// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
6398// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
6399// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
6400bool ImGui::IsAnyItemHovered()
6401{
6402 ImGuiContext& g = *GImGui;
6403 return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
6404}
6405
6406bool ImGui::IsAnyItemActive()
6407{
6408 ImGuiContext& g = *GImGui;
6409 return g.ActiveId != 0;
6410}
6411
6412bool ImGui::IsAnyItemFocused()
6413{
6414 ImGuiContext& g = *GImGui;
6415 return g.NavId != 0 && g.NavCursorVisible;
6416}
6417
6418bool ImGui::IsItemVisible()
6419{
6420 ImGuiContext& g = *GImGui;
6421 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
6422}
6423
6424bool ImGui::IsItemEdited()
6425{
6426 ImGuiContext& g = *GImGui;
6427 return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
6428}
6429
6430// Allow next item to be overlapped by subsequent items.
6431// This works by requiring HoveredId to match for two subsequent frames,
6432// so if a following items overwrite it our interactions will naturally be disabled.
6433void ImGui::SetNextItemAllowOverlap()
6434{
6435 ImGuiContext& g = *GImGui;
6436 g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
6437}
6438
6439#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6440// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
6441// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
6442void ImGui::SetItemAllowOverlap()
6443{
6444 ImGuiContext& g = *GImGui;
6445 ImGuiID id = g.LastItemData.ID;
6446 if (g.HoveredId == id)
6447 g.HoveredIdAllowOverlap = true;
6448 if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
6449 g.ActiveIdAllowOverlap = true;
6450}
6451#endif
6452
6453// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
6454// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
6455void ImGui::SetActiveIdUsingAllKeyboardKeys()
6456{
6457 ImGuiContext& g = *GImGui;
6458 IM_ASSERT(g.ActiveId != 0);
6459 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
6460 g.ActiveIdUsingAllKeyboardKeys = true;
6461 NavMoveRequestCancel();
6462}
6463
6464ImGuiID ImGui::GetItemID()
6465{
6466 ImGuiContext& g = *GImGui;
6467 return g.LastItemData.ID;
6468}
6469
6470ImVec2 ImGui::GetItemRectMin()
6471{
6472 ImGuiContext& g = *GImGui;
6473 return g.LastItemData.Rect.Min;
6474}
6475
6476ImVec2 ImGui::GetItemRectMax()
6477{
6478 ImGuiContext& g = *GImGui;
6479 return g.LastItemData.Rect.Max;
6480}
6481
6482ImVec2 ImGui::GetItemRectSize()
6483{
6484 ImGuiContext& g = *GImGui;
6485 return g.LastItemData.Rect.GetSize();
6486}
6487
6488// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
6489// ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
6490bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6491{
6492 ImGuiID id = GetCurrentWindow()->GetID(str: str_id);
6493 return BeginChildEx(name: str_id, id, size_arg, child_flags, window_flags);
6494}
6495
6496bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6497{
6498 return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
6499}
6500
6501bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
6502{
6503 ImGuiContext& g = *GImGui;
6504 ImGuiWindow* parent_window = g.CurrentWindow;
6505 IM_ASSERT(id != 0);
6506
6507 // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
6508 const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
6509 IM_UNUSED(ImGuiChildFlags_SupportedMask_);
6510 IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
6511 IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
6512 if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
6513 {
6514 IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6515 IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
6516 }
6517#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
6518 if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
6519 child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
6520 if (window_flags & ImGuiWindowFlags_NavFlattened)
6521 child_flags |= ImGuiChildFlags_NavFlattened;
6522#endif
6523 if (child_flags & ImGuiChildFlags_AutoResizeX)
6524 child_flags &= ~ImGuiChildFlags_ResizeX;
6525 if (child_flags & ImGuiChildFlags_AutoResizeY)
6526 child_flags &= ~ImGuiChildFlags_ResizeY;
6527
6528 // Set window flags
6529 window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
6530 window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
6531 if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
6532 window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
6533 if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
6534 window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
6535
6536 // Special framed style
6537 if (child_flags & ImGuiChildFlags_FrameStyle)
6538 {
6539 PushStyleColor(idx: ImGuiCol_ChildBg, col: g.Style.Colors[ImGuiCol_FrameBg]);
6540 PushStyleVar(idx: ImGuiStyleVar_ChildRounding, val: g.Style.FrameRounding);
6541 PushStyleVar(idx: ImGuiStyleVar_ChildBorderSize, val: g.Style.FrameBorderSize);
6542 PushStyleVar(idx: ImGuiStyleVar_WindowPadding, val: g.Style.FramePadding);
6543 child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding;
6544 window_flags |= ImGuiWindowFlags_NoMove;
6545 }
6546
6547 // Forward size
6548 // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
6549 // (the alternative would to store conditional flags per axis, which is possible but more code)
6550 const ImVec2 size_avail = GetContentRegionAvail();
6551 const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
6552 ImVec2 size = CalcItemSize(size: size_arg, default_w: size_default.x, default_h: size_default.y);
6553
6554 // A SetNextWindowSize() call always has priority (#8020)
6555 // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
6556 // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
6557 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
6558 {
6559 if (g.NextWindowData.SizeVal.x > 0.0f)
6560 {
6561 size.x = g.NextWindowData.SizeVal.x;
6562 child_flags &= ~ImGuiChildFlags_ResizeX;
6563 }
6564 if (g.NextWindowData.SizeVal.y > 0.0f)
6565 {
6566 size.y = g.NextWindowData.SizeVal.y;
6567 child_flags &= ~ImGuiChildFlags_ResizeY;
6568 }
6569 }
6570 SetNextWindowSize(size);
6571
6572 // Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
6573 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags)
6574 g.NextWindowData.ChildFlags |= child_flags;
6575 else
6576 g.NextWindowData.ChildFlags = child_flags;
6577 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags;
6578
6579 // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
6580 // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
6581 // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
6582 const char* temp_window_name;
6583 /*if (name && parent_window->IDStack.back() == parent_window->ID)
6584 ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
6585 else*/
6586 if (name)
6587 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%s_%08X", parent_window->Name, name, id);
6588 else
6589 ImFormatStringToTempBuffer(out_buf: &temp_window_name, NULL, fmt: "%s/%08X", parent_window->Name, id);
6590
6591 // Set style
6592 const float backup_border_size = g.Style.ChildBorderSize;
6593 if ((child_flags & ImGuiChildFlags_Borders) == 0)
6594 g.Style.ChildBorderSize = 0.0f;
6595
6596 // Begin into window
6597 const bool ret = Begin(name: temp_window_name, NULL, flags: window_flags);
6598
6599 // Restore style
6600 g.Style.ChildBorderSize = backup_border_size;
6601 if (child_flags & ImGuiChildFlags_FrameStyle)
6602 {
6603 PopStyleVar(count: 3);
6604 PopStyleColor();
6605 }
6606
6607 ImGuiWindow* child_window = g.CurrentWindow;
6608 child_window->ChildId = id;
6609
6610 // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
6611 // While this is not really documented/defined, it seems that the expected thing to do.
6612 if (child_window->BeginCount == 1)
6613 parent_window->DC.CursorPos = child_window->Pos;
6614
6615 // Process navigation-in immediately so NavInit can run on first frame
6616 // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
6617 const ImGuiID temp_id_for_activation = ImHashStr(data_p: "##Child", data_size: 0, seed: id);
6618 if (g.ActiveId == temp_id_for_activation)
6619 ClearActiveID();
6620 if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
6621 {
6622 FocusWindow(window: child_window);
6623 NavInitWindow(window: child_window, force_reinit: false);
6624 SetActiveID(id: temp_id_for_activation, window: child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
6625 g.ActiveIdSource = g.NavInputSource;
6626 }
6627 return ret;
6628}
6629
6630void ImGui::EndChild()
6631{
6632 ImGuiContext& g = *GImGui;
6633 ImGuiWindow* child_window = g.CurrentWindow;
6634
6635 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
6636 IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
6637
6638 g.WithinEndChildID = child_window->ID;
6639 ImVec2 child_size = child_window->Size;
6640 End();
6641 if (child_window->BeginCount == 1)
6642 {
6643 ImGuiWindow* parent_window = g.CurrentWindow;
6644 ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
6645 ItemSize(size: child_size);
6646 const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
6647 if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
6648 {
6649 ItemAdd(bb, id: child_window->ChildId);
6650 RenderNavCursor(bb, id: child_window->ChildId);
6651
6652 // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
6653 if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
6654 RenderNavCursor(bb: ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), id: g.NavId, flags: ImGuiNavRenderCursorFlags_Compact);
6655 }
6656 else
6657 {
6658 // Not navigable into
6659 // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
6660 // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
6661 ItemAdd(bb, id: child_window->ChildId, NULL, extra_flags: ImGuiItemFlags_NoNav);
6662
6663 // But when flattened we directly reach items, adjust active layer mask accordingly
6664 if (nav_flattened)
6665 parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6666 }
6667 if (g.HoveredWindow == child_window)
6668 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6669 child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags;
6670 //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd()
6671 }
6672 else
6673 {
6674 SetLastItemDataForChildWindowItem(window: child_window, rect: child_window->Rect());
6675 }
6676
6677 g.WithinEndChildID = backup_within_end_child_id;
6678 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6679}
6680
6681static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6682{
6683 window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
6684 window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
6685 window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6686 window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
6687}
6688
6689ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6690{
6691 ImGuiContext& g = *GImGui;
6692 return (ImGuiWindow*)g.WindowsById.GetVoidPtr(key: id);
6693}
6694
6695ImGuiWindow* ImGui::FindWindowByName(const char* name)
6696{
6697 ImGuiID id = ImHashStr(data_p: name);
6698 return FindWindowByID(id);
6699}
6700
6701static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6702{
6703 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6704 window->ViewportPos = main_viewport->Pos;
6705 if (settings->ViewportId)
6706 {
6707 window->ViewportId = settings->ViewportId;
6708 window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6709 }
6710 window->Pos = ImTrunc(v: ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6711 if (settings->Size.x > 0 && settings->Size.y > 0)
6712 window->Size = window->SizeFull = ImTrunc(v: ImVec2(settings->Size.x, settings->Size.y));
6713 window->Collapsed = settings->Collapsed;
6714 window->DockId = settings->DockId;
6715 window->DockOrder = settings->DockOrder;
6716}
6717
6718static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6719{
6720 // Initial window state with e.g. default/arbitrary window position
6721 // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6722 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6723 window->Pos = main_viewport->Pos + ImVec2(60, 60);
6724 window->Size = window->SizeFull = ImVec2(0, 0);
6725 window->ViewportPos = main_viewport->Pos;
6726 window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6727
6728 if (settings != NULL)
6729 {
6730 SetWindowConditionAllowFlags(window, flags: ImGuiCond_FirstUseEver, enabled: false);
6731 ApplyWindowSettings(window, settings);
6732 }
6733 window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6734
6735 if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6736 {
6737 window->AutoFitFramesX = window->AutoFitFramesY = 2;
6738 window->AutoFitOnlyGrows = false;
6739 }
6740 else
6741 {
6742 if (window->Size.x <= 0.0f)
6743 window->AutoFitFramesX = 2;
6744 if (window->Size.y <= 0.0f)
6745 window->AutoFitFramesY = 2;
6746 window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6747 }
6748}
6749
6750static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6751{
6752 // Create window the first time
6753 //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6754 ImGuiContext& g = *GImGui;
6755 ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6756 window->Flags = flags;
6757 g.WindowsById.SetVoidPtr(key: window->ID, val: window);
6758
6759 ImGuiWindowSettings* settings = NULL;
6760 if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6761 if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6762 window->SettingsOffset = g.SettingsWindows.offset_from_ptr(p: settings);
6763
6764 InitOrLoadWindowSettings(window, settings);
6765
6766 if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6767 g.Windows.push_front(v: window); // Quite slow but rare and only once
6768 else
6769 g.Windows.push_back(v: window);
6770
6771 return window;
6772}
6773
6774static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6775{
6776 return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6777}
6778
6779static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6780{
6781 return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6782}
6783
6784static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6785{
6786 // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6787 // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6788 // Perhaps should tend further a neater test for this.
6789 ImGuiContext& g = *GImGui;
6790 ImVec2 size_min;
6791 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6792 {
6793 size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6794 size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6795 }
6796 else
6797 {
6798 size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6799 size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6800 }
6801
6802 // Reduce artifacts with very small windows
6803 ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6804 size_min.y = ImMax(lhs: size_min.y, rhs: window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(lhs: 0.0f, rhs: g.Style.WindowRounding - 1.0f));
6805 return size_min;
6806}
6807
6808static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6809{
6810 ImGuiContext& g = *GImGui;
6811 ImVec2 new_size = size_desired;
6812 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6813 {
6814 // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6815 ImRect cr = g.NextWindowData.SizeConstraintRect;
6816 new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(v: new_size.x, mn: cr.Min.x, mx: cr.Max.x) : window->SizeFull.x;
6817 new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(v: new_size.y, mn: cr.Min.y, mx: cr.Max.y) : window->SizeFull.y;
6818 if (g.NextWindowData.SizeCallback)
6819 {
6820 ImGuiSizeCallbackData data;
6821 data.UserData = g.NextWindowData.SizeCallbackUserData;
6822 data.Pos = window->Pos;
6823 data.CurrentSize = window->SizeFull;
6824 data.DesiredSize = new_size;
6825 g.NextWindowData.SizeCallback(&data);
6826 new_size = data.DesiredSize;
6827 }
6828 new_size.x = IM_TRUNC(new_size.x);
6829 new_size.y = IM_TRUNC(new_size.y);
6830 }
6831
6832 // Minimum size
6833 ImVec2 size_min = CalcWindowMinSize(window);
6834 return ImMax(lhs: new_size, rhs: size_min);
6835}
6836
6837static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6838{
6839 bool preserve_old_content_sizes = false;
6840 if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6841 preserve_old_content_sizes = true;
6842 else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6843 preserve_old_content_sizes = true;
6844 if (preserve_old_content_sizes)
6845 {
6846 *content_size_current = window->ContentSize;
6847 *content_size_ideal = window->ContentSizeIdeal;
6848 return;
6849 }
6850
6851 content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(f: window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6852 content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(f: window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6853 content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(f: ImMax(lhs: window->DC.CursorMaxPos.x, rhs: window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6854 content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(f: ImMax(lhs: window->DC.CursorMaxPos.y, rhs: window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6855}
6856
6857static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6858{
6859 ImGuiContext& g = *GImGui;
6860 ImGuiStyle& style = g.Style;
6861 const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6862 const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6863 ImVec2 size_pad = window->WindowPadding * 2.0f;
6864 ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6865
6866 // Determine maximum window size
6867 // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6868 ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6869 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6870 {
6871 if (!window->ViewportOwned)
6872 size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6873 const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6874 if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6875 size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6876 }
6877
6878 if (window->Flags & ImGuiWindowFlags_Tooltip)
6879 {
6880 // Tooltip always resize (up to maximum size)
6881 return ImMin(lhs: size_desired, rhs: size_max);
6882 }
6883 else
6884 {
6885 ImVec2 size_min = CalcWindowMinSize(window);
6886 ImVec2 size_auto_fit = ImClamp(v: size_desired, mn: ImMin(lhs: size_min, rhs: size_max), mx: size_max);
6887
6888 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6889 // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6890 // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6891 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY)))
6892 size_auto_fit.y = window->SizeFull.y;
6893 else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX)))
6894 size_auto_fit.x = window->SizeFull.x;
6895
6896 // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6897 // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6898 ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6899 bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6900 bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6901 if (will_have_scrollbar_x)
6902 size_auto_fit.y += style.ScrollbarSize;
6903 if (will_have_scrollbar_y)
6904 size_auto_fit.x += style.ScrollbarSize;
6905 return size_auto_fit;
6906 }
6907}
6908
6909ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6910{
6911 ImVec2 size_contents_current;
6912 ImVec2 size_contents_ideal;
6913 CalcWindowContentSizes(window, content_size_current: &size_contents_current, content_size_ideal: &size_contents_ideal);
6914 ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: size_contents_ideal);
6915 ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
6916 return size_final;
6917}
6918
6919static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6920{
6921 if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6922 return ImGuiCol_PopupBg;
6923 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6924 return ImGuiCol_ChildBg;
6925 return ImGuiCol_WindowBg;
6926}
6927
6928static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6929{
6930 ImVec2 pos_min = ImLerp(a: corner_target, b: window->Pos, t: corner_norm); // Expected window upper-left
6931 ImVec2 pos_max = ImLerp(a: window->Pos + window->Size, b: corner_target, t: corner_norm); // Expected window lower-right
6932 ImVec2 size_expected = pos_max - pos_min;
6933 ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_desired: size_expected);
6934 *out_pos = pos_min;
6935 if (corner_norm.x == 0.0f)
6936 out_pos->x -= (size_constrained.x - size_expected.x);
6937 if (corner_norm.y == 0.0f)
6938 out_pos->y -= (size_constrained.y - size_expected.y);
6939 *out_size = size_constrained;
6940}
6941
6942// Data for resizing from resize grip / corner
6943struct ImGuiResizeGripDef
6944{
6945 ImVec2 CornerPosN;
6946 ImVec2 InnerDir;
6947 int AngleMin12, AngleMax12;
6948};
6949static const ImGuiResizeGripDef resize_grip_def[4] =
6950{
6951 { .CornerPosN: ImVec2(1, 1), .InnerDir: ImVec2(-1, -1), .AngleMin12: 0, .AngleMax12: 3 }, // Lower-right
6952 { .CornerPosN: ImVec2(0, 1), .InnerDir: ImVec2(+1, -1), .AngleMin12: 3, .AngleMax12: 6 }, // Lower-left
6953 { .CornerPosN: ImVec2(0, 0), .InnerDir: ImVec2(+1, +1), .AngleMin12: 6, .AngleMax12: 9 }, // Upper-left (Unused)
6954 { .CornerPosN: ImVec2(1, 0), .InnerDir: ImVec2(-1, +1), .AngleMin12: 9, .AngleMax12: 12 } // Upper-right (Unused)
6955};
6956
6957// Data for resizing from borders
6958struct ImGuiResizeBorderDef
6959{
6960 ImVec2 InnerDir; // Normal toward inside
6961 ImVec2 SegmentN1, SegmentN2; // End positions, normalized (0,0: upper left)
6962 float OuterAngle; // Angle toward outside
6963};
6964static const ImGuiResizeBorderDef resize_border_def[4] =
6965{
6966 { .InnerDir: ImVec2(+1, 0), .SegmentN1: ImVec2(0, 1), .SegmentN2: ImVec2(0, 0), IM_PI * 1.00f }, // Left
6967 { .InnerDir: ImVec2(-1, 0), .SegmentN1: ImVec2(1, 0), .SegmentN2: ImVec2(1, 1), IM_PI * 0.00f }, // Right
6968 { .InnerDir: ImVec2(0, +1), .SegmentN1: ImVec2(0, 0), .SegmentN2: ImVec2(1, 0), IM_PI * 1.50f }, // Up
6969 { .InnerDir: ImVec2(0, -1), .SegmentN1: ImVec2(1, 1), .SegmentN2: ImVec2(0, 1), IM_PI * 0.50f } // Down
6970};
6971
6972static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6973{
6974 ImRect rect = window->Rect();
6975 if (thickness == 0.0f)
6976 rect.Max -= ImVec2(1, 1);
6977 if (border_n == ImGuiDir_Left) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); }
6978 if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); }
6979 if (border_n == ImGuiDir_Up) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); }
6980 if (border_n == ImGuiDir_Down) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); }
6981 IM_ASSERT(0);
6982 return ImRect();
6983}
6984
6985// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6986ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6987{
6988 IM_ASSERT(n >= 0 && n < 4);
6989 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6990 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
6991 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
6992 return id;
6993}
6994
6995// Borders (Left, Right, Up, Down)
6996ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6997{
6998 IM_ASSERT(dir >= 0 && dir < 4);
6999 int n = (int)dir + 4;
7000 ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
7001 id = ImHashStr(data_p: "#RESIZE", data_size: 0, seed: id);
7002 id = ImHashData(data_p: &n, data_size: sizeof(int), seed: id);
7003 return id;
7004}
7005
7006// Handle resize for: Resize Grips, Borders, Gamepad
7007// Return true when using auto-fit (double-click on resize grip)
7008static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
7009{
7010 ImGuiContext& g = *GImGui;
7011 ImGuiWindowFlags flags = window->Flags;
7012
7013 if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7014 return false;
7015 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
7016 return false;
7017 if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
7018 return false;
7019
7020 int ret_auto_fit_mask = 0x00;
7021 const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7022 const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
7023 const float grip_hover_outer_size = g.WindowsBorderHoverPadding;
7024
7025 ImRect clamp_rect = visibility_rect;
7026 const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
7027 if (window_move_from_title_bar)
7028 clamp_rect.Min.y -= window->TitleBarHeight;
7029
7030 ImVec2 pos_target(FLT_MAX, FLT_MAX);
7031 ImVec2 size_target(FLT_MAX, FLT_MAX);
7032
7033 // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
7034 // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
7035 // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
7036 // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
7037 // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
7038 // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
7039 const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
7040 if (clip_with_viewport_rect)
7041 window->ClipRect = window->Viewport->GetMainRect();
7042
7043 // Resize grips and borders are on layer 1
7044 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7045
7046 // Manual resize grips
7047 PushID(str_id: "#RESIZE");
7048 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7049 {
7050 const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
7051 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: def.CornerPosN);
7052
7053 // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
7054 bool hovered, held;
7055 ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
7056 if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(a&: resize_rect.Min.x, b&: resize_rect.Max.x);
7057 if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(a&: resize_rect.Min.y, b&: resize_rect.Max.y);
7058 ImGuiID resize_grip_id = window->GetID(n: resize_grip_n); // == GetWindowResizeCornerID()
7059 ItemAdd(bb: resize_rect, id: resize_grip_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
7060 ButtonBehavior(bb: resize_rect, id: resize_grip_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7061 //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
7062 if (hovered || held)
7063 SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
7064
7065 if (held && g.IO.MouseDoubleClicked[0])
7066 {
7067 // Auto-fit when double-clicking
7068 size_target = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit);
7069 ret_auto_fit_mask = 0x03; // Both axes
7070 ClearActiveID();
7071 }
7072 else if (held)
7073 {
7074 // Resize from any of the four corners
7075 // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
7076 ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
7077 ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
7078 ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(a: def.InnerDir * grip_hover_outer_size, b: def.InnerDir * -grip_hover_inner_size, t: def.CornerPosN); // Corner of the window corresponding to our corner grip
7079 corner_target = ImClamp(v: corner_target, mn: clamp_min, mx: clamp_max);
7080 CalcResizePosSizeFromAnyCorner(window, corner_target, corner_norm: def.CornerPosN, out_pos: &pos_target, out_size: &size_target);
7081 }
7082
7083 // Only lower-left grip is visible before hovering/activating
7084 if (resize_grip_n == 0 || held || hovered)
7085 resize_grip_col[resize_grip_n] = GetColorU32(idx: held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
7086 }
7087
7088 int resize_border_mask = 0x00;
7089 if (window->Flags & ImGuiWindowFlags_ChildWindow)
7090 resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
7091 else
7092 resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
7093 for (int border_n = 0; border_n < 4; border_n++)
7094 {
7095 if ((resize_border_mask & (1 << border_n)) == 0)
7096 continue;
7097 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7098 const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
7099
7100 bool hovered, held;
7101 ImRect border_rect = GetResizeBorderRect(window, border_n, perp_padding: grip_hover_inner_size, thickness: g.WindowsBorderHoverPadding);
7102 ImGuiID border_id = window->GetID(n: border_n + 4); // == GetWindowResizeBorderID()
7103 ItemAdd(bb: border_rect, id: border_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
7104 ButtonBehavior(bb: border_rect, id: border_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
7105 //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
7106 if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
7107 hovered = false;
7108 if (hovered || held)
7109 SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
7110 if (held && g.IO.MouseDoubleClicked[0])
7111 {
7112 // Double-clicking bottom or right border auto-fit on this axis
7113 // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
7114 // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
7115 if (border_n == 1 || border_n == 3) // Right and bottom border
7116 {
7117 size_target[axis] = CalcWindowSizeAfterConstraint(window, size_desired: size_auto_fit)[axis];
7118 ret_auto_fit_mask |= (1 << axis);
7119 hovered = held = false; // So border doesn't show highlighted at new position
7120 }
7121 ClearActiveID();
7122 }
7123 else if (held)
7124 {
7125 // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
7126 // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
7127 // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
7128 const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, potential_parent: g.WheelingWindow, popup_hierarchy: false, dock_hierarchy: true));
7129 if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
7130 {
7131 g.WindowResizeBorderExpectedRect = border_rect;
7132 g.WindowResizeRelativeMode = false;
7133 }
7134 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(s1: &g.WindowResizeBorderExpectedRect, s2: &border_rect, n: sizeof(ImRect)) != 0)
7135 g.WindowResizeRelativeMode = true;
7136
7137 const ImVec2 border_curr = (window->Pos + ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2) * window->Size);
7138 const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
7139 const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above.
7140
7141 // Use absolute mode position
7142 ImVec2 border_target = window->Pos;
7143 border_target[axis] = border_target_abs_mode_for_axis;
7144
7145 // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
7146 bool ignore_resize = false;
7147 if (g.WindowResizeRelativeMode)
7148 {
7149 //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
7150 border_target[axis] = border_target_rel_mode_for_axis;
7151 if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
7152 ignore_resize = true;
7153 }
7154
7155 // Clamp, apply
7156 ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
7157 ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
7158 border_target = ImClamp(v: border_target, mn: clamp_min, mx: clamp_max);
7159 if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
7160 {
7161 ImGuiWindow* parent_window = window->ParentWindow;
7162 ImGuiWindowFlags parent_flags = parent_window->Flags;
7163 ImRect border_limit_rect = parent_window->InnerRect;
7164 border_limit_rect.Expand(amount: ImVec2(-ImMax(lhs: parent_window->WindowPadding.x, rhs: parent_window->WindowBorderSize), -ImMax(lhs: parent_window->WindowPadding.y, rhs: parent_window->WindowBorderSize)));
7165 if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
7166 border_target.x = ImClamp(v: border_target.x, mn: border_limit_rect.Min.x, mx: border_limit_rect.Max.x);
7167 if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
7168 border_target.y = ImClamp(v: border_target.y, mn: border_limit_rect.Min.y, mx: border_limit_rect.Max.y);
7169 }
7170 if (!ignore_resize)
7171 CalcResizePosSizeFromAnyCorner(window, corner_target: border_target, corner_norm: ImMin(lhs: def.SegmentN1, rhs: def.SegmentN2), out_pos: &pos_target, out_size: &size_target);
7172 }
7173 if (hovered)
7174 *border_hovered = border_n;
7175 if (held)
7176 *border_held = border_n;
7177 }
7178 PopID();
7179
7180 // Restore nav layer
7181 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7182
7183 // Navigation resize (keyboard/gamepad)
7184 // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
7185 // Not even sure the callback works here.
7186 if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
7187 {
7188 ImVec2 nav_resize_dir;
7189 if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
7190 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_LeftArrow, key_right: ImGuiKey_RightArrow, key_up: ImGuiKey_UpArrow, key_down: ImGuiKey_DownArrow);
7191 if (g.NavInputSource == ImGuiInputSource_Gamepad)
7192 nav_resize_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadDpadLeft, key_right: ImGuiKey_GamepadDpadRight, key_up: ImGuiKey_GamepadDpadUp, key_down: ImGuiKey_GamepadDpadDown);
7193 if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
7194 {
7195 const float NAV_RESIZE_SPEED = 600.0f;
7196 const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(lhs: g.IO.DisplayFramebufferScale.x, rhs: g.IO.DisplayFramebufferScale.y);
7197 g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
7198 g.NavWindowingAccumDeltaSize = ImMax(lhs: g.NavWindowingAccumDeltaSize, rhs: clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
7199 g.NavWindowingToggleLayer = false;
7200 g.NavHighlightItemUnderNav = true;
7201 resize_grip_col[0] = GetColorU32(idx: ImGuiCol_ResizeGripActive);
7202 ImVec2 accum_floored = ImTrunc(v: g.NavWindowingAccumDeltaSize);
7203 if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
7204 {
7205 // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
7206 size_target = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull + accum_floored);
7207 g.NavWindowingAccumDeltaSize -= accum_floored;
7208 }
7209 }
7210 }
7211
7212 // Apply back modified position/size to window
7213 const ImVec2 curr_pos = window->Pos;
7214 const ImVec2 curr_size = window->SizeFull;
7215 if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
7216 window->Size.x = window->SizeFull.x = size_target.x;
7217 if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
7218 window->Size.y = window->SizeFull.y = size_target.y;
7219 if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(f: pos_target.x))
7220 window->Pos.x = ImTrunc(f: pos_target.x);
7221 if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(f: pos_target.y))
7222 window->Pos.y = ImTrunc(f: pos_target.y);
7223 if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
7224 MarkIniSettingsDirty(window);
7225
7226 // Recalculate next expected border expected coordinates
7227 if (*border_held != -1)
7228 g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_n: *border_held, perp_padding: grip_hover_inner_size, thickness: g.WindowsBorderHoverPadding);
7229
7230 return ret_auto_fit_mask;
7231}
7232
7233static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
7234{
7235 ImGuiContext& g = *GImGui;
7236 ImVec2 size_for_clamping = window->Size;
7237 if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
7238 size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
7239 else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7240 size_for_clamping.y = window->TitleBarHeight;
7241 window->Pos = ImClamp(v: window->Pos, mn: visibility_rect.Min - size_for_clamping, mx: visibility_rect.Max);
7242}
7243
7244static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
7245{
7246 const ImGuiResizeBorderDef& def = resize_border_def[border_n];
7247 const float rounding = window->WindowRounding;
7248 const ImRect border_r = GetResizeBorderRect(window, border_n, perp_padding: rounding, thickness: 0.0f);
7249 window->DrawList->PathArcTo(center: ImLerp(a: border_r.Min, b: border_r.Max, t: def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, radius: rounding, a_min: def.OuterAngle - IM_PI * 0.25f, a_max: def.OuterAngle);
7250 window->DrawList->PathArcTo(center: ImLerp(a: border_r.Min, b: border_r.Max, t: def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, radius: rounding, a_min: def.OuterAngle, a_max: def.OuterAngle + IM_PI * 0.25f);
7251 window->DrawList->PathStroke(col: border_col, flags: ImDrawFlags_None, thickness: border_size);
7252}
7253
7254static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
7255{
7256 ImGuiContext& g = *GImGui;
7257 const float border_size = window->WindowBorderSize;
7258 const ImU32 border_col = GetColorU32(idx: ImGuiCol_Border);
7259 if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
7260 window->DrawList->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, col: border_col, rounding: window->WindowRounding, flags: 0, thickness: window->WindowBorderSize);
7261 else if (border_size > 0.0f)
7262 {
7263 if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
7264 RenderWindowOuterSingleBorder(window, border_n: 1, border_col, border_size);
7265 if (window->ChildFlags & ImGuiChildFlags_ResizeY)
7266 RenderWindowOuterSingleBorder(window, border_n: 3, border_col, border_size);
7267 }
7268 if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
7269 {
7270 const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
7271 const ImU32 border_col_resizing = GetColorU32(idx: (window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
7272 RenderWindowOuterSingleBorder(window, border_n, border_col: border_col_resizing, border_size: ImMax(lhs: 2.0f, rhs: window->WindowBorderSize)); // Thicker than usual
7273 }
7274 if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7275 {
7276 float y = window->Pos.y + window->TitleBarHeight - 1;
7277 window->DrawList->AddLine(p1: ImVec2(window->Pos.x + border_size * 0.5f, y), p2: ImVec2(window->Pos.x + window->Size.x - border_size * 0.5f, y), col: border_col, thickness: g.Style.FrameBorderSize);
7278 }
7279}
7280
7281// Draw background and borders
7282// Draw and handle scrollbars
7283void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
7284{
7285 ImGuiContext& g = *GImGui;
7286 ImGuiStyle& style = g.Style;
7287 ImGuiWindowFlags flags = window->Flags;
7288
7289 // Ensure that Scrollbar() doesn't read last frame's SkipItems
7290 IM_ASSERT(window->BeginCount == 0);
7291 window->SkipItems = false;
7292 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7293
7294 // Draw window + handle manual resize
7295 // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
7296 const float window_rounding = window->WindowRounding;
7297 const float window_border_size = window->WindowBorderSize;
7298 if (window->Collapsed)
7299 {
7300 // Title bar only
7301 const float backup_border_size = style.FrameBorderSize;
7302 g.Style.FrameBorderSize = window->WindowBorderSize;
7303 ImU32 title_bar_col = GetColorU32(idx: (title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
7304 if (window->ViewportOwned)
7305 title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
7306 RenderFrame(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, fill_col: title_bar_col, borders: true, rounding: window_rounding);
7307 g.Style.FrameBorderSize = backup_border_size;
7308 }
7309 else
7310 {
7311 // Window background
7312 if (!(flags & ImGuiWindowFlags_NoBackground))
7313 {
7314 bool is_docking_transparent_payload = false;
7315 if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
7316 if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
7317 is_docking_transparent_payload = true;
7318
7319 ImU32 bg_col = GetColorU32(idx: GetWindowBgColorIdx(window));
7320 if (window->ViewportOwned)
7321 {
7322 bg_col |= IM_COL32_A_MASK; // No alpha
7323 if (is_docking_transparent_payload)
7324 window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
7325 }
7326 else
7327 {
7328 // Adjust alpha. For docking
7329 bool override_alpha = false;
7330 float alpha = 1.0f;
7331 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha)
7332 {
7333 alpha = g.NextWindowData.BgAlphaVal;
7334 override_alpha = true;
7335 }
7336 if (is_docking_transparent_payload)
7337 {
7338 alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
7339 override_alpha = true;
7340 }
7341 if (override_alpha)
7342 bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
7343 }
7344
7345 // Render, for docked windows and host windows we ensure bg goes before decorations
7346 if (window->DockIsActive)
7347 window->DockNode->LastBgColor = bg_col;
7348 ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
7349 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7350 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
7351 bg_draw_list->AddRectFilled(p_min: window->Pos + ImVec2(0, window->TitleBarHeight), p_max: window->Pos + window->Size, col: bg_col, rounding: window_rounding, flags: (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
7352 if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
7353 bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
7354 }
7355 if (window->DockIsActive)
7356 window->DockNode->IsBgDrawnThisFrame = true;
7357
7358 // Title bar
7359 // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
7360 // in order for their pos/size to be matching their undocking state.)
7361 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7362 {
7363 ImU32 title_bar_col = GetColorU32(idx: title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
7364 if (window->ViewportOwned)
7365 title_bar_col |= IM_COL32_A_MASK; // No alpha
7366 window->DrawList->AddRectFilled(p_min: title_bar_rect.Min, p_max: title_bar_rect.Max, col: title_bar_col, rounding: window_rounding, flags: ImDrawFlags_RoundCornersTop);
7367 }
7368
7369 // Menu bar
7370 if (flags & ImGuiWindowFlags_MenuBar)
7371 {
7372 ImRect menu_bar_rect = window->MenuBarRect();
7373 menu_bar_rect.ClipWith(r: window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
7374 window->DrawList->AddRectFilled(p_min: menu_bar_rect.Min, p_max: menu_bar_rect.Max, col: GetColorU32(idx: ImGuiCol_MenuBarBg), rounding: (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, flags: ImDrawFlags_RoundCornersTop);
7375 if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
7376 window->DrawList->AddLine(p1: menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), p2: menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), col: GetColorU32(idx: ImGuiCol_Border), thickness: style.FrameBorderSize);
7377 }
7378
7379 // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
7380 ImGuiDockNode* node = window->DockNode;
7381 if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
7382 {
7383 float unhide_sz_draw = ImTrunc(f: g.FontSize * 0.70f);
7384 float unhide_sz_hit = ImTrunc(f: g.FontSize * 0.55f);
7385 ImVec2 p = node->Pos;
7386 ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
7387 ImGuiID unhide_id = window->GetID(str: "#UNHIDE");
7388 KeepAliveID(id: unhide_id);
7389 bool hovered, held;
7390 if (ButtonBehavior(bb: r, id: unhide_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren))
7391 node->WantHiddenTabBarToggle = true;
7392 else if (held && IsMouseDragging(button: 0))
7393 StartMouseMovingWindowOrNode(window, node, undock: true); // Undock from tab-bar triangle = same as window/collapse menu button
7394
7395 // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
7396 ImU32 col = GetColorU32(idx: ((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
7397 window->DrawList->AddTriangleFilled(p1: p, p2: p + ImVec2(unhide_sz_draw, 0.0f), p3: p + ImVec2(0.0f, unhide_sz_draw), col);
7398 }
7399
7400 // Scrollbars
7401 if (window->ScrollbarX)
7402 Scrollbar(axis: ImGuiAxis_X);
7403 if (window->ScrollbarY)
7404 Scrollbar(axis: ImGuiAxis_Y);
7405
7406 // Render resize grips (after their input handling so we don't have a frame of latency)
7407 if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
7408 {
7409 for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
7410 {
7411 const ImU32 col = resize_grip_col[resize_grip_n];
7412 if ((col & IM_COL32_A_MASK) == 0)
7413 continue;
7414 const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
7415 const ImVec2 corner = ImLerp(a: window->Pos, b: window->Pos + window->Size, t: grip.CornerPosN);
7416 const float border_inner = IM_ROUND(window_border_size * 0.5f);
7417 window->DrawList->PathLineTo(pos: corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner)));
7418 window->DrawList->PathLineTo(pos: corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size)));
7419 window->DrawList->PathArcToFast(center: ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), radius: window_rounding, a_min_of_12: grip.AngleMin12, a_max_of_12: grip.AngleMax12);
7420 window->DrawList->PathFillConvex(col);
7421 }
7422 }
7423
7424 // Borders (for dock node host they will be rendered over after the tab bar)
7425 if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
7426 RenderWindowOuterBorders(window);
7427 }
7428 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7429}
7430
7431// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
7432// Render title text, collapse button, close button
7433void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
7434{
7435 ImGuiContext& g = *GImGui;
7436 ImGuiStyle& style = g.Style;
7437 ImGuiWindowFlags flags = window->Flags;
7438
7439 const bool has_close_button = (p_open != NULL);
7440 const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
7441
7442 // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
7443 // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
7444 const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
7445 g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
7446 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
7447
7448 // Layout buttons
7449 // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
7450 float pad_l = style.FramePadding.x;
7451 float pad_r = style.FramePadding.x;
7452 float button_sz = g.FontSize;
7453 ImVec2 close_button_pos;
7454 ImVec2 collapse_button_pos;
7455 if (has_close_button)
7456 {
7457 close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7458 pad_r += button_sz + style.ItemInnerSpacing.x;
7459 }
7460 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
7461 {
7462 collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
7463 pad_r += button_sz + style.ItemInnerSpacing.x;
7464 }
7465 if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
7466 {
7467 collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
7468 pad_l += button_sz + style.ItemInnerSpacing.x;
7469 }
7470
7471 // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
7472 if (has_collapse_button)
7473 if (CollapseButton(id: window->GetID(str: "#COLLAPSE"), pos: collapse_button_pos, NULL))
7474 window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
7475
7476 // Close button
7477 if (has_close_button)
7478 {
7479 g.CurrentItemFlags |= ImGuiItemFlags_NoFocus;
7480 if (CloseButton(id: window->GetID(str: "#CLOSE"), pos: close_button_pos))
7481 *p_open = false;
7482 g.CurrentItemFlags &= ~ImGuiItemFlags_NoFocus;
7483 }
7484
7485 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7486 g.CurrentItemFlags = item_flags_backup;
7487
7488 // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
7489 // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
7490 const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
7491 const ImVec2 text_size = CalcTextSize(text: name, NULL, hide_text_after_double_hash: true) + ImVec2(marker_size_x, 0.0f);
7492
7493 // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
7494 // while uncentered title text will still reach edges correctly.
7495 if (pad_l > style.FramePadding.x)
7496 pad_l += g.Style.ItemInnerSpacing.x;
7497 if (pad_r > style.FramePadding.x)
7498 pad_r += g.Style.ItemInnerSpacing.x;
7499 if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
7500 {
7501 float centerness = ImSaturate(f: 1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
7502 float pad_extend = ImMin(lhs: ImMax(lhs: pad_l, rhs: pad_r), rhs: title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
7503 pad_l = ImMax(lhs: pad_l, rhs: pad_extend * centerness);
7504 pad_r = ImMax(lhs: pad_r, rhs: pad_extend * centerness);
7505 }
7506
7507 ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
7508 ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(lhs: layout_r.Max.x + g.Style.ItemInnerSpacing.x, rhs: title_bar_rect.Max.x), layout_r.Max.y);
7509 if (flags & ImGuiWindowFlags_UnsavedDocument)
7510 {
7511 ImVec2 marker_pos;
7512 marker_pos.x = ImClamp(v: layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, mn: layout_r.Min.x, mx: layout_r.Max.x);
7513 marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
7514 if (marker_pos.x > layout_r.Min.x)
7515 {
7516 RenderBullet(draw_list: window->DrawList, pos: marker_pos, col: GetColorU32(idx: ImGuiCol_Text));
7517 clip_r.Max.x = ImMin(lhs: clip_r.Max.x, rhs: marker_pos.x - (int)(marker_size_x * 0.5f));
7518 }
7519 }
7520 //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7521 //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
7522 RenderTextClipped(pos_min: layout_r.Min, pos_max: layout_r.Max, text: name, NULL, text_size_if_known: &text_size, align: style.WindowTitleAlign, clip_rect: &clip_r);
7523}
7524
7525void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
7526{
7527 window->ParentWindow = parent_window;
7528 window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
7529 if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
7530 {
7531 window->RootWindowDockTree = parent_window->RootWindowDockTree;
7532 if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
7533 window->RootWindow = parent_window->RootWindow;
7534 }
7535 if (parent_window && (flags & ImGuiWindowFlags_Popup))
7536 window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
7537 if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
7538 window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
7539 while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
7540 {
7541 IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
7542 window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
7543 }
7544}
7545
7546// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
7547// This is designed as a toy/test-bed for
7548void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
7549{
7550 ImGuiContext& g = *GImGui;
7551 window->SkipRefresh = false;
7552 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
7553 return;
7554 if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
7555 {
7556 // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
7557 if (window->Appearing) // If currently appearing
7558 return;
7559 if (window->Hidden) // If was hidden (previous frame)
7560 return;
7561 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow)
7562 if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(window: g.HoveredWindow->RootWindow, potential_parent: window))
7563 return;
7564 if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow)
7565 if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(window: g.NavWindow->RootWindow, potential_parent: window))
7566 return;
7567 window->DrawList = NULL;
7568 window->SkipRefresh = true;
7569 }
7570}
7571
7572static void SetWindowActiveForSkipRefresh(ImGuiWindow* window)
7573{
7574 window->Active = true;
7575 for (ImGuiWindow* child : window->DC.ChildWindows)
7576 if (!child->Hidden)
7577 {
7578 child->Active = child->SkipRefresh = true;
7579 SetWindowActiveForSkipRefresh(child);
7580 }
7581}
7582
7583// Push a new Dear ImGui window to add widgets to.
7584// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
7585// - Begin/End can be called multiple times during the frame with the same window name to append content.
7586// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
7587// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
7588// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
7589// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
7590bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
7591{
7592 ImGuiContext& g = *GImGui;
7593 const ImGuiStyle& style = g.Style;
7594 IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
7595 IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
7596 IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
7597
7598 // Find or create
7599 ImGuiWindow* window = FindWindowByName(name);
7600 const bool window_just_created = (window == NULL);
7601 if (window_just_created)
7602 window = CreateNewWindow(name, flags);
7603
7604 // [DEBUG] Debug break requested by user
7605 if (g.DebugBreakInWindow == window->ID)
7606 IM_DEBUG_BREAK();
7607
7608 // Automatically disable manual moving/resizing when NoInputs is set
7609 if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
7610 flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
7611
7612 const int current_frame = g.FrameCount;
7613 const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
7614 window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
7615
7616 // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
7617 bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
7618 if (flags & ImGuiWindowFlags_Popup)
7619 {
7620 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7621 window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
7622 window_just_activated_by_user |= (window != popup_ref.Window);
7623 }
7624
7625 // Update Flags, LastFrameActive, BeginOrderXXX fields
7626 const bool window_was_appearing = window->Appearing;
7627 if (first_begin_of_the_frame)
7628 {
7629 UpdateWindowInFocusOrderList(window, just_created: window_just_created, new_flags: flags);
7630 window->Appearing = window_just_activated_by_user;
7631 if (window->Appearing)
7632 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
7633 window->FlagsPreviousFrame = window->Flags;
7634 window->Flags = (ImGuiWindowFlags)flags;
7635 window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7636 window->LastFrameActive = current_frame;
7637 window->LastTimeActive = (float)g.Time;
7638 window->BeginOrderWithinParent = 0;
7639 window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7640 }
7641 else
7642 {
7643 flags = window->Flags;
7644 }
7645
7646 // Docking
7647 // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7648 IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7649 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasDock)
7650 SetWindowDock(window, dock_id: g.NextWindowData.DockId, cond: g.NextWindowData.DockCond);
7651 if (first_begin_of_the_frame)
7652 {
7653 bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7654 bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7655 bool dock_node_was_visible = window->DockNodeIsVisible;
7656 bool dock_tab_was_visible = window->DockTabIsVisible;
7657 if (has_dock_node || new_auto_dock_node)
7658 {
7659 BeginDocked(window, p_open);
7660 flags = window->Flags;
7661 if (window->DockIsActive)
7662 {
7663 IM_ASSERT(window->DockNode != NULL);
7664 g.NextWindowData.HasFlags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7665 }
7666
7667 // Amend the Appearing flag
7668 if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7669 {
7670 window->Appearing = true;
7671 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: true);
7672 }
7673 }
7674 else
7675 {
7676 window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7677 }
7678 }
7679
7680 // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
7681 ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7682 ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7683 IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7684
7685 // We allow window memory to be compacted so recreate the base stack when needed.
7686 if (window->IDStack.Size == 0)
7687 window->IDStack.push_back(v: window->ID);
7688
7689 // Add to stack
7690 g.CurrentWindow = window;
7691 g.CurrentWindowStack.resize(new_size: g.CurrentWindowStack.Size + 1);
7692 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7693 window_stack_data.Window = window;
7694 window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7695 window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7696 window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f;
7697 ErrorRecoveryStoreState(state_out: &window_stack_data.StackSizesInBegin);
7698 g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
7699 if (flags & ImGuiWindowFlags_ChildMenu)
7700 g.BeginMenuDepth++;
7701
7702 // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7703 if (first_begin_of_the_frame)
7704 {
7705 UpdateWindowParentAndRootLinks(window, flags, parent_window);
7706 window->ParentWindowInBeginStack = parent_window_in_stack;
7707
7708 // Focus route
7709 // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7710 // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7711 window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7712 if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7713 if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7714 window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7715
7716 // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7717 if (window->WindowClass.FocusRouteParentWindowId != 0)
7718 {
7719 window->ParentWindowForFocusRoute = FindWindowByID(id: window->WindowClass.FocusRouteParentWindowId);
7720 IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7721 }
7722
7723 // Inherit SetWindowFontScale() from parent until we fix this system...
7724 window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f;
7725 }
7726
7727 // Add to focus scope stack
7728 PushFocusScope(id: (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7729 window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7730
7731 // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7732 if (flags & ImGuiWindowFlags_Popup)
7733 {
7734 ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7735 popup_ref.Window = window;
7736 popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7737 g.BeginPopupStack.push_back(v: popup_ref);
7738 window->PopupId = popup_ref.PopupId;
7739 }
7740
7741 // Process SetNextWindow***() calls
7742 // (FIXME: Consider splitting the HasXXX flags into X/Y components
7743 bool window_pos_set_by_api = false;
7744 bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7745 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos)
7746 {
7747 window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7748 if (window_pos_set_by_api && ImLengthSqr(lhs: g.NextWindowData.PosPivotVal) > 0.00001f)
7749 {
7750 // May be processed on the next frame if this is our first frame and we are measuring size
7751 // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7752 window->SetWindowPosVal = g.NextWindowData.PosVal;
7753 window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7754 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7755 }
7756 else
7757 {
7758 SetWindowPos(window, pos: g.NextWindowData.PosVal, cond: g.NextWindowData.PosCond);
7759 }
7760 }
7761 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize)
7762 {
7763 window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7764 window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7765 if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7766 g.NextWindowData.SizeVal.x = window->SizeFull.x;
7767 if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7768 g.NextWindowData.SizeVal.y = window->SizeFull.y;
7769 SetWindowSize(window, size: g.NextWindowData.SizeVal, cond: g.NextWindowData.SizeCond);
7770 }
7771 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll)
7772 {
7773 if (g.NextWindowData.ScrollVal.x >= 0.0f)
7774 {
7775 window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7776 window->ScrollTargetCenterRatio.x = 0.0f;
7777 }
7778 if (g.NextWindowData.ScrollVal.y >= 0.0f)
7779 {
7780 window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7781 window->ScrollTargetCenterRatio.y = 0.0f;
7782 }
7783 }
7784 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize)
7785 window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7786 else if (first_begin_of_the_frame)
7787 window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7788 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowClass)
7789 window->WindowClass = g.NextWindowData.WindowClass;
7790 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed)
7791 SetWindowCollapsed(window, collapsed: g.NextWindowData.CollapsedVal, cond: g.NextWindowData.CollapsedCond);
7792 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus)
7793 FocusWindow(window);
7794 if (window->Appearing)
7795 SetWindowConditionAllowFlags(window, flags: ImGuiCond_Appearing, enabled: false);
7796
7797 // [EXPERIMENTAL] Skip Refresh mode
7798 UpdateWindowSkipRefresh(window);
7799
7800 // Nested root windows (typically tooltips) override disabled state
7801 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7802 BeginDisabledOverrideReenable();
7803
7804 // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7805 g.CurrentWindow = NULL;
7806
7807 // When reusing window again multiple times a frame, just append content (don't need to setup again)
7808 if (first_begin_of_the_frame && !window->SkipRefresh)
7809 {
7810 // Initialize
7811 const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7812 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7813 window->Active = true;
7814 window->HasCloseButton = (p_open != NULL);
7815 window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7816 window->IDStack.resize(new_size: 1);
7817 window->DrawList->_ResetForNewFrame();
7818 window->DC.CurrentTableIdx = -1;
7819 if (flags & ImGuiWindowFlags_DockNodeHost)
7820 {
7821 window->DrawList->ChannelsSplit(count: 2);
7822 window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7823 }
7824
7825 // Restore buffer capacity when woken from a compacted state, to avoid
7826 if (window->MemoryCompacted)
7827 GcAwakeTransientWindowBuffers(window);
7828
7829 // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7830 // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7831 bool window_title_visible_elsewhere = false;
7832 if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7833 window_title_visible_elsewhere = true;
7834 else if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
7835 window_title_visible_elsewhere = true;
7836 else if (flags & ImGuiWindowFlags_ChildMenu)
7837 window_title_visible_elsewhere = true;
7838 if (window_title_visible_elsewhere && !window_just_created && strcmp(s1: name, s2: window->Name) != 0)
7839 {
7840 size_t buf_len = (size_t)window->NameBufLen;
7841 window->Name = ImStrdupcpy(dst: window->Name, p_dst_size: &buf_len, src: name);
7842 window->NameBufLen = (int)buf_len;
7843 }
7844
7845 // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7846
7847 // Update contents size from last frame for auto-fitting (or use explicit size)
7848 CalcWindowContentSizes(window, content_size_current: &window->ContentSize, content_size_ideal: &window->ContentSizeIdeal);
7849
7850 // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7851 // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7852 // it has a single usage before this code block and may be set below before it is finally checked.
7853 if (window->HiddenFramesCanSkipItems > 0)
7854 window->HiddenFramesCanSkipItems--;
7855 if (window->HiddenFramesCannotSkipItems > 0)
7856 window->HiddenFramesCannotSkipItems--;
7857 if (window->HiddenFramesForRenderOnly > 0)
7858 window->HiddenFramesForRenderOnly--;
7859
7860 // Hide new windows for one frame until they calculate their size
7861 if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7862 window->HiddenFramesCannotSkipItems = 1;
7863
7864 // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7865 // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7866 if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7867 {
7868 window->HiddenFramesCannotSkipItems = 1;
7869 if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7870 {
7871 if (!window_size_x_set_by_api)
7872 window->Size.x = window->SizeFull.x = 0.f;
7873 if (!window_size_y_set_by_api)
7874 window->Size.y = window->SizeFull.y = 0.f;
7875 window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7876 }
7877 }
7878
7879 // SELECT VIEWPORT
7880 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7881
7882 WindowSelectViewport(window);
7883 SetCurrentViewport(window, viewport: window->Viewport);
7884 SetCurrentWindow(window);
7885 flags = window->Flags;
7886
7887 // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7888 // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7889
7890 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7891 window->WindowBorderSize = style.ChildBorderSize;
7892 else
7893 window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7894 window->WindowPadding = style.WindowPadding;
7895 if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7896 window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7897
7898 // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7899 window->DC.MenuBarOffset.x = ImMax(lhs: ImMax(lhs: window->WindowPadding.x, rhs: style.ItemSpacing.x), rhs: g.NextWindowData.MenuBarOffsetMinVal.x);
7900 window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7901 window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7902 window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7903 window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window.
7904
7905 // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7906 // Those flags will be altered further down in the function depending on more conditions.
7907 bool use_current_size_for_scrollbar_x = window_just_created;
7908 bool use_current_size_for_scrollbar_y = window_just_created;
7909 if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7910 use_current_size_for_scrollbar_x = true;
7911 if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7912 use_current_size_for_scrollbar_y = true;
7913
7914 // Collapse window by double-clicking on title bar
7915 // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7916 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7917 {
7918 // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
7919 // so verify that we don't have items over the title bar.
7920 ImRect title_bar_rect = window->TitleBarRect();
7921 if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max))
7922 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(key: ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7923 window->WantCollapseToggle = true;
7924 if (window->WantCollapseToggle)
7925 {
7926 window->Collapsed = !window->Collapsed;
7927 if (!window->Collapsed)
7928 use_current_size_for_scrollbar_y = true;
7929 MarkIniSettingsDirty(window);
7930 }
7931 }
7932 else
7933 {
7934 window->Collapsed = false;
7935 }
7936 window->WantCollapseToggle = false;
7937
7938 // SIZE
7939
7940 // Outer Decoration Sizes
7941 // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7942 const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7943 window->DecoOuterSizeX1 = 0.0f;
7944 window->DecoOuterSizeX2 = 0.0f;
7945 window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7946 window->DecoOuterSizeY2 = 0.0f;
7947 window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7948
7949 // Calculate auto-fit size, handle automatic resize
7950 const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents: window->ContentSizeIdeal);
7951 if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7952 {
7953 // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7954 if (!window_size_x_set_by_api)
7955 {
7956 window->SizeFull.x = size_auto_fit.x;
7957 use_current_size_for_scrollbar_x = true;
7958 }
7959 if (!window_size_y_set_by_api)
7960 {
7961 window->SizeFull.y = size_auto_fit.y;
7962 use_current_size_for_scrollbar_y = true;
7963 }
7964 }
7965 else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7966 {
7967 // Auto-fit may only grow window during the first few frames
7968 // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7969 if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7970 {
7971 window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.x, rhs: size_auto_fit.x) : size_auto_fit.x;
7972 use_current_size_for_scrollbar_x = true;
7973 }
7974 if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7975 {
7976 window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(lhs: window->SizeFull.y, rhs: size_auto_fit.y) : size_auto_fit.y;
7977 use_current_size_for_scrollbar_y = true;
7978 }
7979 if (!window->Collapsed)
7980 MarkIniSettingsDirty(window);
7981 }
7982
7983 // Apply minimum/maximum window size constraints and final size
7984 window->SizeFull = CalcWindowSizeAfterConstraint(window, size_desired: window->SizeFull);
7985 window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7986
7987 // POSITION
7988
7989 // Popup latch its initial position, will position itself when it appears next frame
7990 if (window_just_activated_by_user)
7991 {
7992 window->AutoPosLastDirection = ImGuiDir_None;
7993 if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7994 window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7995 }
7996
7997 // Position child window
7998 if (flags & ImGuiWindowFlags_ChildWindow)
7999 {
8000 IM_ASSERT(parent_window && parent_window->Active);
8001 window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
8002 parent_window->DC.ChildWindows.push_back(v: window);
8003 if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
8004 window->Pos = parent_window->DC.CursorPos;
8005 }
8006
8007 const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
8008 if (window_pos_with_pivot)
8009 SetWindowPos(window, pos: window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, cond: 0); // Position given a pivot (e.g. for centering)
8010 else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
8011 window->Pos = FindBestWindowPosForPopup(window);
8012 else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
8013 window->Pos = FindBestWindowPosForPopup(window);
8014 else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
8015 window->Pos = FindBestWindowPosForPopup(window);
8016
8017 // Late create viewport if we don't fit within our current host viewport.
8018 if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
8019 if (!window->Viewport->GetMainRect().Contains(r: window->Rect()))
8020 {
8021 // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
8022 //ImGuiViewport* old_viewport = window->Viewport;
8023 window->Viewport = AddUpdateViewport(window, id: window->ID, platform_pos: window->Pos, size: window->Size, flags: ImGuiViewportFlags_NoFocusOnAppearing);
8024
8025 // FIXME-DPI
8026 //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
8027 SetCurrentViewport(window, viewport: window->Viewport);
8028 SetCurrentWindow(window);
8029 }
8030
8031 if (window->ViewportOwned)
8032 WindowSyncOwnedViewport(window, parent_window_in_stack);
8033
8034 // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
8035 // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
8036 ImRect viewport_rect(window->Viewport->GetMainRect());
8037 ImRect viewport_work_rect(window->Viewport->GetWorkRect());
8038 ImVec2 visibility_padding = ImMax(lhs: style.DisplayWindowPadding, rhs: style.DisplaySafeAreaPadding);
8039 ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
8040
8041 // Clamp position/size so window stays visible within its viewport or monitor
8042 // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
8043 // FIXME: Similar to code in GetWindowAllowedExtentRect()
8044 if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
8045 {
8046 if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
8047 {
8048 ClampWindowPos(window, visibility_rect);
8049 }
8050 else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
8051 {
8052 if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
8053 {
8054 // While moving windows we allow them to straddle monitors (#7299, #3071)
8055 visibility_rect = g.PlatformMonitorsFullWorkRect;
8056 }
8057 else
8058 {
8059 // When not moving ensure visible in its monitor
8060 // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
8061 const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(viewport: window->Viewport);
8062 visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
8063 }
8064 visibility_rect.Expand(amount: -visibility_padding);
8065 ClampWindowPos(window, visibility_rect);
8066 }
8067 }
8068 window->Pos = ImTrunc(v: window->Pos);
8069
8070 // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
8071 // Large values tend to lead to variety of artifacts and are not recommended.
8072 if (window->ViewportOwned || window->DockIsActive)
8073 window->WindowRounding = 0.0f;
8074 else
8075 window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
8076
8077 // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
8078 //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
8079 // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
8080
8081 // Apply window focus (new and reactivated windows are moved to front)
8082 bool want_focus = false;
8083 if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
8084 {
8085 if (flags & ImGuiWindowFlags_Popup)
8086 want_focus = true;
8087 else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
8088 want_focus = true;
8089 }
8090
8091 // [Test Engine] Register whole window in the item system (before submitting further decorations)
8092#ifdef IMGUI_ENABLE_TEST_ENGINE
8093 if (g.TestEngineHookItems)
8094 {
8095 IM_ASSERT(window->IDStack.Size == 1);
8096 window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
8097 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8098 IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
8099 IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
8100 window->IDStack.Size = 1;
8101 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8102
8103 }
8104#endif
8105
8106 // Decide if we are going to handle borders and resize grips
8107 // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815)
8108 // Whenever we add support for full decorated child windows we will likely make this logic more general.
8109 bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
8110 if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems)
8111 handle_borders_and_resize_grips = false;
8112
8113 // Handle manual resize: Resize Grips, Borders, Gamepad
8114 int border_hovered = -1, border_held = -1;
8115 ImU32 resize_grip_col[4] = {};
8116 const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
8117 const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
8118 if (handle_borders_and_resize_grips && !window->Collapsed)
8119 if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, border_hovered: &border_hovered, border_held: &border_held, resize_grip_count, resize_grip_col: &resize_grip_col[0], visibility_rect))
8120 {
8121 if (auto_fit_mask & (1 << ImGuiAxis_X))
8122 use_current_size_for_scrollbar_x = true;
8123 if (auto_fit_mask & (1 << ImGuiAxis_Y))
8124 use_current_size_for_scrollbar_y = true;
8125 }
8126 window->ResizeBorderHovered = (signed char)border_hovered;
8127 window->ResizeBorderHeld = (signed char)border_held;
8128
8129 // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
8130 if (window->ViewportOwned)
8131 {
8132 if (!window->Viewport->PlatformRequestMove)
8133 window->Viewport->Pos = window->Pos;
8134 if (!window->Viewport->PlatformRequestResize)
8135 window->Viewport->Size = window->Size;
8136 window->Viewport->UpdateWorkRect();
8137 viewport_rect = window->Viewport->GetMainRect();
8138 }
8139
8140 // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
8141 window->ViewportPos = window->Viewport->Pos;
8142
8143 // SCROLLBAR VISIBILITY
8144
8145 // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
8146 if (!window->Collapsed)
8147 {
8148 // When reading the current size we need to read it after size constraints have been applied.
8149 // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
8150 // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
8151 ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
8152 ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
8153 ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
8154 float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
8155 float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
8156 bool scrollbar_x_prev = window->ScrollbarX;
8157 //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
8158 window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
8159 window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
8160
8161 // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
8162 // (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause.
8163 // The better solution is to, either (1) enforce visibility by using ImGuiWindowFlags_AlwaysHorizontalScrollbar or (2) declare stable contents width with SetNextWindowContentSize(), if you can compute it)
8164 window->ScrollbarXStabilizeToggledHistory <<= 1;
8165 window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00;
8166 const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(v: window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history.
8167 if (scrollbar_x_stabilize)
8168 window->ScrollbarX = true;
8169 //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled)
8170 // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name);
8171 window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize;
8172
8173 if (window->ScrollbarX && !window->ScrollbarY)
8174 window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
8175 window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
8176
8177 // Amend the partially filled window->DecorationXXX values.
8178 window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
8179 window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
8180 }
8181
8182 // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
8183 // Update various regions. Variables they depend on should be set above in this function.
8184 // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
8185
8186 // Outer rectangle
8187 // Not affected by window border size. Used by:
8188 // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
8189 // - Begin() initial clipping rect for drawing window background and borders.
8190 // - Begin() clipping whole child
8191 const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
8192 const ImRect outer_rect = window->Rect();
8193 const ImRect title_bar_rect = window->TitleBarRect();
8194 window->OuterRectClipped = outer_rect;
8195 if (window->DockIsActive)
8196 window->OuterRectClipped.Min.y += window->TitleBarHeight;
8197 window->OuterRectClipped.ClipWith(r: host_rect);
8198
8199 // Inner rectangle
8200 // Not affected by window border size. Used by:
8201 // - InnerClipRect
8202 // - ScrollToRectEx()
8203 // - NavUpdatePageUpPageDown()
8204 // - Scrollbar()
8205 window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
8206 window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
8207 window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
8208 window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
8209
8210 // Inner clipping rectangle.
8211 // - Extend a outside of normal work region up to borders.
8212 // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
8213 // - It also makes clipped items be more noticeable.
8214 // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
8215 // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
8216 // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
8217 // Affected by window/frame border size. Used by:
8218 // - Begin() initial clip rect
8219 float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
8220
8221 // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner.
8222 // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize,
8223 // see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5f here).
8224 window->InnerClipRect.Min.x = ImFloor(f: 0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f);
8225 window->InnerClipRect.Min.y = ImFloor(f: 0.5f + window->InnerRect.Min.y + top_border_size * 0.5f);
8226 window->InnerClipRect.Max.x = ImFloor(f: window->InnerRect.Max.x - window->WindowBorderSize * 0.5f);
8227 window->InnerClipRect.Max.y = ImFloor(f: window->InnerRect.Max.y - window->WindowBorderSize * 0.5f);
8228 window->InnerClipRect.ClipWithFull(r: host_rect);
8229
8230 // SCROLLING
8231
8232 // Lock down maximum scrolling
8233 // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
8234 // for right/bottom aligned items without creating a scrollbar.
8235 window->ScrollMax.x = ImMax(lhs: 0.0f, rhs: window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
8236 window->ScrollMax.y = ImMax(lhs: 0.0f, rhs: window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
8237
8238 // Apply scrolling
8239 window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
8240 window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
8241 window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
8242
8243 // DRAWING
8244
8245 // Setup draw list and outer clipping rectangle
8246 IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
8247 window->DrawList->PushTexture(tex_ref: g.Font->ContainerAtlas->TexRef);
8248 PushClipRect(clip_rect_min: host_rect.Min, clip_rect_max: host_rect.Max, intersect_with_current_clip_rect: false);
8249
8250 // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
8251 // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
8252 // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
8253 const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
8254 if (is_undocked_or_docked_visible)
8255 {
8256 bool render_decorations_in_parent = false;
8257 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
8258 {
8259 // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
8260 // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
8261 ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
8262 bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(r: window->Rect()) : false;
8263 bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
8264 if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
8265 render_decorations_in_parent = true;
8266 }
8267 if (render_decorations_in_parent)
8268 window->DrawList = parent_window->DrawList;
8269
8270 // Handle title bar, scrollbar, resize grips and resize borders
8271 const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
8272 const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
8273 RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
8274
8275 if (render_decorations_in_parent)
8276 window->DrawList = &window->DrawListInst;
8277 }
8278
8279 // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
8280
8281 // Work rectangle.
8282 // Affected by window padding and border size. Used by:
8283 // - Columns() for right-most edge
8284 // - TreeNode(), CollapsingHeader() for right-most edge
8285 // - BeginTabBar() for right-most edge
8286 const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
8287 const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
8288 const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(lhs: allow_scrollbar_x ? window->ContentSize.x : 0.0f, rhs: window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
8289 const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(lhs: allow_scrollbar_y ? window->ContentSize.y : 0.0f, rhs: window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
8290 window->WorkRect.Min.x = ImTrunc(f: window->InnerRect.Min.x - window->Scroll.x + ImMax(lhs: window->WindowPadding.x, rhs: window->WindowBorderSize));
8291 window->WorkRect.Min.y = ImTrunc(f: window->InnerRect.Min.y - window->Scroll.y + ImMax(lhs: window->WindowPadding.y, rhs: window->WindowBorderSize));
8292 window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
8293 window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
8294 window->ParentWorkRect = window->WorkRect;
8295
8296 // [LEGACY] Content Region
8297 // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
8298 // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
8299 // Used by:
8300 // - Mouse wheel scrolling + many other things
8301 window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
8302 window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
8303 window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
8304 window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
8305
8306 // Setup drawing context
8307 // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
8308 window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
8309 window->DC.GroupOffset.x = 0.0f;
8310 window->DC.ColumnsOffset.x = 0.0f;
8311
8312 // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
8313 // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
8314 double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
8315 double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
8316 window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
8317 window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
8318 window->DC.CursorPos = window->DC.CursorStartPos;
8319 window->DC.CursorPosPrevLine = window->DC.CursorPos;
8320 window->DC.CursorMaxPos = window->DC.CursorStartPos;
8321 window->DC.IdealMaxPos = window->DC.CursorStartPos;
8322 window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
8323 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
8324 window->DC.IsSameLine = window->DC.IsSetPos = false;
8325
8326 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8327 window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
8328 window->DC.NavLayersActiveMaskNext = 0x00;
8329 window->DC.NavIsScrollPushableX = true;
8330 window->DC.NavHideHighlightOneFrame = false;
8331 window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
8332
8333 window->DC.MenuBarAppending = false;
8334 window->DC.MenuColumns.Update(spacing: style.ItemSpacing.x, window_reappearing: window_just_activated_by_user);
8335 window->DC.TreeDepth = 0;
8336 window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00;
8337 window->DC.ChildWindows.resize(new_size: 0);
8338 window->DC.StateStorage = &window->StateStorage;
8339 window->DC.CurrentColumns = NULL;
8340 window->DC.LayoutType = ImGuiLayoutType_Vertical;
8341 window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
8342
8343 // Default item width. Make it proportional to window size if window manually resizes
8344 if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
8345 window->ItemWidthDefault = ImTrunc(f: window->Size.x * 0.65f);
8346 else
8347 window->ItemWidthDefault = ImTrunc(f: g.FontSize * 16.0f);
8348 window->DC.ItemWidth = window->ItemWidthDefault;
8349 window->DC.TextWrapPos = -1.0f; // disabled
8350 window->DC.ItemWidthStack.resize(new_size: 0);
8351 window->DC.TextWrapPosStack.resize(new_size: 0);
8352 if (flags & ImGuiWindowFlags_Modal)
8353 window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(in: GetStyleColorVec4(idx: ImGuiCol_ModalWindowDimBg));
8354
8355 if (window->AutoFitFramesX > 0)
8356 window->AutoFitFramesX--;
8357 if (window->AutoFitFramesY > 0)
8358 window->AutoFitFramesY--;
8359
8360 // Clear SetNextWindowXXX data (can aim to move this higher in the function)
8361 g.NextWindowData.ClearFlags();
8362
8363 // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
8364 // We ImGuiFocusRequestFlags_UnlessBelowModal to:
8365 // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
8366 // - Position window behind the modal that is not a begin-parent of this window.
8367 if (want_focus)
8368 FocusWindow(window, flags: ImGuiFocusRequestFlags_UnlessBelowModal);
8369 if (want_focus && window == g.NavWindow)
8370 NavInitWindow(window, force_reinit: false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
8371
8372 // Close requested by platform window (apply to all windows in this viewport)
8373 if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
8374 {
8375 IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
8376 *p_open = false;
8377 g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
8378 }
8379
8380 // Pressing CTRL+C copy window content into the clipboard
8381 // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
8382 // [EXPERIMENTAL] Text outputs has many issues.
8383 if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
8384 if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(key_chord: ImGuiMod_Ctrl | ImGuiKey_C))
8385 LogToClipboard(auto_open_depth: 0);
8386
8387 // Title bar
8388 if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
8389 RenderWindowTitleBarContents(window, title_bar_rect: ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
8390 else if (!(flags & ImGuiWindowFlags_NoTitleBar) && window->DockIsActive)
8391 LogText(fmt: "%.*s\n", (int)(FindRenderedTextEnd(text: window->Name) - window->Name), window->Name);
8392
8393 // Clear hit test shape every frame
8394 window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
8395
8396 if (flags & ImGuiWindowFlags_Tooltip)
8397 g.TooltipPreviousWindow = window;
8398
8399 if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
8400 {
8401 // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
8402 // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
8403 if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
8404 BeginDockableDragDropSource(window);
8405
8406 // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
8407 if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
8408 if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
8409 if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
8410 BeginDockableDragDropTarget(window);
8411 }
8412
8413 // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
8414 // This is useful to allow creating context menus on title bar only, etc.
8415 window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None;
8416 window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(r_min: title_bar_rect.Min, r_max: title_bar_rect.Max, clip: false) ? ImGuiItemStatusFlags_HoveredRect : 0;
8417 SetLastItemDataForWindow(window, rect: title_bar_rect);
8418
8419 // [DEBUG]
8420#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8421 if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
8422 DebugLocateItemResolveWithLastItem();
8423#endif
8424
8425 // [Test Engine] Register title bar / tab with MoveId.
8426#ifdef IMGUI_ENABLE_TEST_ENGINE
8427 if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
8428 {
8429 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8430 IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
8431 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8432 }
8433#endif
8434 }
8435 else
8436 {
8437 // Skip refresh always mark active
8438 if (window->SkipRefresh)
8439 SetWindowActiveForSkipRefresh(window);
8440
8441 // Append
8442 SetCurrentViewport(window, viewport: window->Viewport);
8443 SetCurrentWindow(window);
8444 g.NextWindowData.ClearFlags();
8445 SetLastItemDataForWindow(window, rect: window->TitleBarRect());
8446 }
8447
8448 if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
8449 PushClipRect(clip_rect_min: window->InnerClipRect.Min, clip_rect_max: window->InnerClipRect.Max, intersect_with_current_clip_rect: true);
8450
8451 // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
8452 window->WriteAccessed = false;
8453 window->BeginCount++;
8454
8455 // Update visibility
8456 if (first_begin_of_the_frame && !window->SkipRefresh)
8457 {
8458 // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
8459 // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
8460 // This is analogous to regular windows being hidden from one frame.
8461 // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
8462 if (window->DockIsActive && !window->DockTabIsVisible)
8463 {
8464 if (window->LastFrameJustFocused == g.FrameCount)
8465 window->HiddenFramesCannotSkipItems = 1;
8466 else
8467 window->HiddenFramesCanSkipItems = 1;
8468 }
8469
8470 if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
8471 {
8472 // Child window can be out of sight and have "negative" clip windows.
8473 // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
8474 IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
8475 const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
8476 if (!g.LogEnabled && !nav_request)
8477 if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
8478 {
8479 if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
8480 window->HiddenFramesCannotSkipItems = 1;
8481 else
8482 window->HiddenFramesCanSkipItems = 1;
8483 }
8484
8485 // Hide along with parent or if parent is collapsed
8486 if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
8487 window->HiddenFramesCanSkipItems = 1;
8488 if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0)
8489 window->HiddenFramesCannotSkipItems = 1;
8490 }
8491
8492 // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
8493 if (style.Alpha <= 0.0f)
8494 window->HiddenFramesCanSkipItems = 1;
8495
8496 // Update the Hidden flag
8497 bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
8498 window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
8499
8500 // Disable inputs for requested number of frames
8501 if (window->DisableInputsFrames > 0)
8502 {
8503 window->DisableInputsFrames--;
8504 window->Flags |= ImGuiWindowFlags_NoInputs;
8505 }
8506
8507 // Update the SkipItems flag, used to early out of all items functions (no layout required)
8508 bool skip_items = false;
8509 if (window->Collapsed || !window->Active || hidden_regular)
8510 if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
8511 skip_items = true;
8512 window->SkipItems = skip_items;
8513
8514 // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
8515 if (window->SkipItems)
8516 window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
8517
8518 // Sanity check: there are two spots which can set Appearing = true
8519 // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
8520 // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
8521 if (window->SkipItems && !window->Appearing)
8522 IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
8523 }
8524 else if (first_begin_of_the_frame)
8525 {
8526 // Skip refresh mode
8527 window->SkipItems = true;
8528 }
8529
8530 // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
8531 // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
8532#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8533 if (!window->IsFallbackWindow)
8534 if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
8535 {
8536 if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
8537 if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
8538 return false;
8539 }
8540#endif
8541
8542 return !window->SkipItems;
8543}
8544
8545void ImGui::End()
8546{
8547 ImGuiContext& g = *GImGui;
8548 ImGuiWindow* window = g.CurrentWindow;
8549
8550 // Error checking: verify that user hasn't called End() too many times!
8551 if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
8552 {
8553 IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
8554 return;
8555 }
8556 ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
8557
8558 // Error checking: verify that user doesn't directly call End() on a child window.
8559 if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
8560 IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!");
8561
8562 // Close anything that is open
8563 if (window->DC.CurrentColumns)
8564 EndColumns();
8565 if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) // Pop inner window clip rectangle
8566 PopClipRect();
8567 PopFocusScope();
8568 if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
8569 EndDisabledOverrideReenable();
8570
8571 if (window->SkipRefresh)
8572 {
8573 IM_ASSERT(window->DrawList == NULL);
8574 window->DrawList = &window->DrawListInst;
8575 }
8576
8577 // Stop logging
8578 if (g.LogWindow == window) // FIXME: add more options for scope of logging
8579 LogFinish();
8580
8581 if (window->DC.IsSetPos)
8582 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
8583
8584 // Docking: report contents sizes to parent to allow for auto-resize
8585 if (window->DockNode && window->DockTabIsVisible)
8586 if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
8587 host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
8588
8589 // Pop from window stack
8590 g.LastItemData = window_stack_data.ParentLastItemDataBackup;
8591 if (window->Flags & ImGuiWindowFlags_ChildMenu)
8592 g.BeginMenuDepth--;
8593 if (window->Flags & ImGuiWindowFlags_Popup)
8594 g.BeginPopupStack.pop_back();
8595
8596 // Error handling, state recovery
8597 if (g.IO.ConfigErrorRecovery)
8598 ErrorRecoveryTryToRecoverWindowState(state_in: &window_stack_data.StackSizesInBegin);
8599
8600 g.CurrentWindowStack.pop_back();
8601 SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
8602 if (g.CurrentWindow)
8603 SetCurrentViewport(window: g.CurrentWindow, viewport: g.CurrentWindow->Viewport);
8604}
8605
8606void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8607{
8608 ImGuiContext& g = *GImGui;
8609 ImGuiItemFlags item_flags = g.CurrentItemFlags;
8610 IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8611 if (enabled)
8612 item_flags |= option;
8613 else
8614 item_flags &= ~option;
8615 g.CurrentItemFlags = item_flags;
8616 g.ItemFlagsStack.push_back(v: item_flags);
8617}
8618
8619void ImGui::PopItemFlag()
8620{
8621 ImGuiContext& g = *GImGui;
8622 if (g.ItemFlagsStack.Size <= 1)
8623 {
8624 IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!");
8625 return;
8626 }
8627 g.ItemFlagsStack.pop_back();
8628 g.CurrentItemFlags = g.ItemFlagsStack.back();
8629}
8630
8631// BeginDisabled()/EndDisabled()
8632// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8633// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8634// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8635// - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
8636// (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls)
8637// - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
8638void ImGui::BeginDisabled(bool disabled)
8639{
8640 ImGuiContext& g = *GImGui;
8641 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8642 if (!was_disabled && disabled)
8643 {
8644 g.DisabledAlphaBackup = g.Style.Alpha;
8645 g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8646 }
8647 if (was_disabled || disabled)
8648 g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8649 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8650 g.DisabledStackSize++;
8651}
8652
8653void ImGui::EndDisabled()
8654{
8655 ImGuiContext& g = *GImGui;
8656 if (g.DisabledStackSize <= 0)
8657 {
8658 IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!");
8659 return;
8660 }
8661 g.DisabledStackSize--;
8662 bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8663 //PopItemFlag();
8664 g.ItemFlagsStack.pop_back();
8665 g.CurrentItemFlags = g.ItemFlagsStack.back();
8666 if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8667 g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8668}
8669
8670// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8671// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8672// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8673void ImGui::BeginDisabledOverrideReenable()
8674{
8675 ImGuiContext& g = *GImGui;
8676 IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8677 g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha;
8678 g.Style.Alpha = g.DisabledAlphaBackup;
8679 g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8680 g.ItemFlagsStack.push_back(v: g.CurrentItemFlags);
8681 g.DisabledStackSize++;
8682}
8683
8684void ImGui::EndDisabledOverrideReenable()
8685{
8686 ImGuiContext& g = *GImGui;
8687 g.DisabledStackSize--;
8688 IM_ASSERT(g.DisabledStackSize > 0);
8689 g.ItemFlagsStack.pop_back();
8690 g.CurrentItemFlags = g.ItemFlagsStack.back();
8691 g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup;
8692}
8693
8694void ImGui::PushTextWrapPos(float wrap_pos_x)
8695{
8696 ImGuiContext& g = *GImGui;
8697 ImGuiWindow* window = g.CurrentWindow;
8698 window->DC.TextWrapPosStack.push_back(v: window->DC.TextWrapPos);
8699 window->DC.TextWrapPos = wrap_pos_x;
8700}
8701
8702void ImGui::PopTextWrapPos()
8703{
8704 ImGuiContext& g = *GImGui;
8705 ImGuiWindow* window = g.CurrentWindow;
8706 if (window->DC.TextWrapPosStack.Size <= 0)
8707 {
8708 IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
8709 return;
8710 }
8711 window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8712 window->DC.TextWrapPosStack.pop_back();
8713}
8714
8715static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8716{
8717 ImGuiWindow* last_window = NULL;
8718 while (last_window != window)
8719 {
8720 last_window = window;
8721 window = window->RootWindow;
8722 if (popup_hierarchy)
8723 window = window->RootWindowPopupTree;
8724 if (dock_hierarchy)
8725 window = window->RootWindowDockTree;
8726 }
8727 return window;
8728}
8729
8730bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8731{
8732 ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8733 if (window_root == potential_parent)
8734 return true;
8735 while (window != NULL)
8736 {
8737 if (window == potential_parent)
8738 return true;
8739 if (window == window_root) // end of chain
8740 return false;
8741 window = window->ParentWindow;
8742 }
8743 return false;
8744}
8745
8746bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8747{
8748 if (window->RootWindow == potential_parent)
8749 return true;
8750 while (window != NULL)
8751 {
8752 if (window == potential_parent)
8753 return true;
8754 window = window->ParentWindowInBeginStack;
8755 }
8756 return false;
8757}
8758
8759bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8760{
8761 ImGuiContext& g = *GImGui;
8762
8763 // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8764 const int display_layer_delta = GetWindowDisplayLayer(window: potential_above) - GetWindowDisplayLayer(window: potential_below);
8765 if (display_layer_delta != 0)
8766 return display_layer_delta > 0;
8767
8768 for (int i = g.Windows.Size - 1; i >= 0; i--)
8769 {
8770 ImGuiWindow* candidate_window = g.Windows[i];
8771 if (candidate_window == potential_above)
8772 return true;
8773 if (candidate_window == potential_below)
8774 return false;
8775 }
8776 return false;
8777}
8778
8779// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8780// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8781// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8782// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8783bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8784{
8785 ImGuiContext& g = *GImGui;
8786 IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
8787
8788 ImGuiWindow* ref_window = g.HoveredWindow;
8789 ImGuiWindow* cur_window = g.CurrentWindow;
8790 if (ref_window == NULL)
8791 return false;
8792
8793 if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8794 {
8795 IM_ASSERT(cur_window); // Not inside a Begin()/End()
8796 const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8797 const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8798 if (flags & ImGuiHoveredFlags_RootWindow)
8799 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy, dock_hierarchy);
8800
8801 bool result;
8802 if (flags & ImGuiHoveredFlags_ChildWindows)
8803 result = IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy, dock_hierarchy);
8804 else
8805 result = (ref_window == cur_window);
8806 if (!result)
8807 return false;
8808 }
8809
8810 if (!IsWindowContentHoverable(window: ref_window, flags))
8811 return false;
8812 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8813 if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8814 return false;
8815
8816 // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8817 // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8818 // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8819 // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8820 // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8821 if (flags & ImGuiHoveredFlags_ForTooltip)
8822 flags = ApplyHoverFlagsForTooltip(user_flags: flags, shared_flags: g.Style.HoverFlagsForTooltipMouse);
8823 if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8824 return false;
8825
8826 return true;
8827}
8828
8829ImGuiID ImGui::GetWindowDockID()
8830{
8831 ImGuiContext& g = *GImGui;
8832 return g.CurrentWindow->DockId;
8833}
8834
8835bool ImGui::IsWindowDocked()
8836{
8837 ImGuiContext& g = *GImGui;
8838 return g.CurrentWindow->DockIsActive;
8839}
8840
8841float ImGui::GetWindowWidth()
8842{
8843 ImGuiWindow* window = GImGui->CurrentWindow;
8844 return window->Size.x;
8845}
8846
8847float ImGui::GetWindowHeight()
8848{
8849 ImGuiWindow* window = GImGui->CurrentWindow;
8850 return window->Size.y;
8851}
8852
8853ImVec2 ImGui::GetWindowPos()
8854{
8855 ImGuiContext& g = *GImGui;
8856 ImGuiWindow* window = g.CurrentWindow;
8857 return window->Pos;
8858}
8859
8860void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8861{
8862 // Test condition (NB: bit 0 is always true) and clear flags for next time
8863 if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8864 return;
8865
8866 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8867 window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8868 window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8869
8870 // Set
8871 const ImVec2 old_pos = window->Pos;
8872 window->Pos = ImTrunc(v: pos);
8873 ImVec2 offset = window->Pos - old_pos;
8874 if (offset.x == 0.0f && offset.y == 0.0f)
8875 return;
8876 MarkIniSettingsDirty(window);
8877 // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8878 window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8879 window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8880 window->DC.IdealMaxPos += offset;
8881 window->DC.CursorStartPos += offset;
8882}
8883
8884void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8885{
8886 ImGuiWindow* window = GetCurrentWindowRead();
8887 SetWindowPos(window, pos, cond);
8888}
8889
8890void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8891{
8892 if (ImGuiWindow* window = FindWindowByName(name))
8893 SetWindowPos(window, pos, cond);
8894}
8895
8896ImVec2 ImGui::GetWindowSize()
8897{
8898 ImGuiWindow* window = GetCurrentWindowRead();
8899 return window->Size;
8900}
8901
8902void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8903{
8904 // Test condition (NB: bit 0 is always true) and clear flags for next time
8905 if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8906 return;
8907
8908 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8909 window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8910
8911 // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8912 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8913 window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8914 if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8915 window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8916
8917 // Set
8918 ImVec2 old_size = window->SizeFull;
8919 if (size.x <= 0.0f)
8920 window->AutoFitOnlyGrows = false;
8921 else
8922 window->SizeFull.x = IM_TRUNC(size.x);
8923 if (size.y <= 0.0f)
8924 window->AutoFitOnlyGrows = false;
8925 else
8926 window->SizeFull.y = IM_TRUNC(size.y);
8927 if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8928 MarkIniSettingsDirty(window);
8929}
8930
8931void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8932{
8933 SetWindowSize(window: GImGui->CurrentWindow, size, cond);
8934}
8935
8936void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8937{
8938 if (ImGuiWindow* window = FindWindowByName(name))
8939 SetWindowSize(window, size, cond);
8940}
8941
8942void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8943{
8944 // Test condition (NB: bit 0 is always true) and clear flags for next time
8945 if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8946 return;
8947 window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8948
8949 // Queue applying in Begin()
8950 if (window->WantCollapseToggle)
8951 window->Collapsed ^= 1;
8952 window->WantCollapseToggle = (window->Collapsed != collapsed);
8953}
8954
8955void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8956{
8957 IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
8958 window->HitTestHoleSize = ImVec2ih(size);
8959 window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8960}
8961
8962void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8963{
8964 window->Hidden = window->SkipItems = true;
8965 window->HiddenFramesCanSkipItems = 1;
8966}
8967
8968void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8969{
8970 SetWindowCollapsed(window: GImGui->CurrentWindow, collapsed, cond);
8971}
8972
8973bool ImGui::IsWindowCollapsed()
8974{
8975 ImGuiWindow* window = GetCurrentWindowRead();
8976 return window->Collapsed;
8977}
8978
8979bool ImGui::IsWindowAppearing()
8980{
8981 ImGuiWindow* window = GetCurrentWindowRead();
8982 return window->Appearing;
8983}
8984
8985void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8986{
8987 if (ImGuiWindow* window = FindWindowByName(name))
8988 SetWindowCollapsed(window, collapsed, cond);
8989}
8990
8991void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8992{
8993 ImGuiContext& g = *GImGui;
8994 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8995 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos;
8996 g.NextWindowData.PosVal = pos;
8997 g.NextWindowData.PosPivotVal = pivot;
8998 g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8999 g.NextWindowData.PosUndock = true;
9000}
9001
9002void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
9003{
9004 ImGuiContext& g = *GImGui;
9005 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9006 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize;
9007 g.NextWindowData.SizeVal = size;
9008 g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
9009}
9010
9011// For each axis:
9012// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
9013// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
9014// - See "Demo->Examples->Constrained-resizing window" for examples.
9015void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
9016{
9017 ImGuiContext& g = *GImGui;
9018 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
9019 g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
9020 g.NextWindowData.SizeCallback = custom_callback;
9021 g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
9022}
9023
9024// Content size = inner scrollable rectangle, padded with WindowPadding.
9025// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
9026void ImGui::SetNextWindowContentSize(const ImVec2& size)
9027{
9028 ImGuiContext& g = *GImGui;
9029 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize;
9030 g.NextWindowData.ContentSizeVal = ImTrunc(v: size);
9031}
9032
9033void ImGui::SetNextWindowScroll(const ImVec2& scroll)
9034{
9035 ImGuiContext& g = *GImGui;
9036 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll;
9037 g.NextWindowData.ScrollVal = scroll;
9038}
9039
9040void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
9041{
9042 ImGuiContext& g = *GImGui;
9043 IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
9044 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed;
9045 g.NextWindowData.CollapsedVal = collapsed;
9046 g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
9047}
9048
9049void ImGui::SetNextWindowBgAlpha(float alpha)
9050{
9051 ImGuiContext& g = *GImGui;
9052 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha;
9053 g.NextWindowData.BgAlphaVal = alpha;
9054}
9055
9056void ImGui::SetNextWindowViewport(ImGuiID id)
9057{
9058 ImGuiContext& g = *GImGui;
9059 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasViewport;
9060 g.NextWindowData.ViewportId = id;
9061}
9062
9063void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
9064{
9065 ImGuiContext& g = *GImGui;
9066 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasDock;
9067 g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
9068 g.NextWindowData.DockId = id;
9069}
9070
9071void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
9072{
9073 ImGuiContext& g = *GImGui;
9074 IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
9075 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasWindowClass;
9076 g.NextWindowData.WindowClass = *window_class;
9077}
9078
9079// This is experimental and meant to be a toy for exploring a future/wider range of features.
9080void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
9081{
9082 ImGuiContext& g = *GImGui;
9083 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
9084 g.NextWindowData.RefreshFlagsVal = flags;
9085}
9086
9087ImDrawList* ImGui::GetWindowDrawList()
9088{
9089 ImGuiWindow* window = GetCurrentWindow();
9090 return window->DrawList;
9091}
9092
9093float ImGui::GetWindowDpiScale()
9094{
9095 ImGuiContext& g = *GImGui;
9096 return g.CurrentDpiScale;
9097}
9098
9099ImGuiViewport* ImGui::GetWindowViewport()
9100{
9101 ImGuiContext& g = *GImGui;
9102 IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
9103 return g.CurrentViewport;
9104}
9105
9106ImFont* ImGui::GetFont()
9107{
9108 return GImGui->Font;
9109}
9110
9111ImFontBaked* ImGui::GetFontBaked()
9112{
9113 return GImGui->FontBaked;
9114}
9115
9116// Get current font size (= height in pixels) of current font, with global scale factors applied.
9117// - Use style.FontSizeBase to get value before global scale factors.
9118// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors)
9119float ImGui::GetFontSize()
9120{
9121 return GImGui->FontSize;
9122}
9123
9124ImVec2 ImGui::GetFontTexUvWhitePixel()
9125{
9126 return GImGui->DrawListSharedData.TexUvWhitePixel;
9127}
9128
9129// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows.
9130#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9131void ImGui::SetWindowFontScale(float scale)
9132{
9133 IM_ASSERT(scale > 0.0f);
9134 ImGuiWindow* window = GetCurrentWindow();
9135 window->FontWindowScale = scale;
9136 UpdateCurrentFontSize(restore_font_size_after_scaling: 0.0f);
9137}
9138#endif
9139
9140void ImGui::PushFocusScope(ImGuiID id)
9141{
9142 ImGuiContext& g = *GImGui;
9143 ImGuiFocusScopeData data;
9144 data.ID = id;
9145 data.WindowID = g.CurrentWindow->ID;
9146 g.FocusScopeStack.push_back(v: data);
9147 g.CurrentFocusScopeId = id;
9148}
9149
9150void ImGui::PopFocusScope()
9151{
9152 ImGuiContext& g = *GImGui;
9153 if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack)
9154 {
9155 IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
9156 return;
9157 }
9158 g.FocusScopeStack.pop_back();
9159 g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
9160}
9161
9162void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
9163{
9164 ImGuiContext& g = *GImGui;
9165 g.NavFocusScopeId = focus_scope_id;
9166 g.NavFocusRoute.resize(new_size: 0); // Invalidate
9167 if (focus_scope_id == 0)
9168 return;
9169 IM_ASSERT(g.NavWindow != NULL);
9170
9171 // Store current path (in reverse order)
9172 if (focus_scope_id == g.CurrentFocusScopeId)
9173 {
9174 // Top of focus stack contains local focus scopes inside current window
9175 for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
9176 g.NavFocusRoute.push_back(v: g.FocusScopeStack.Data[n]);
9177 }
9178 else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
9179 g.NavFocusRoute.push_back(v: { .ID: focus_scope_id, .WindowID: g.NavWindow->ID });
9180 else
9181 return;
9182
9183 // Then follow on manually set ParentWindowForFocusRoute field (#6798)
9184 for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
9185 g.NavFocusRoute.push_back(v: { .ID: window->NavRootFocusScopeId, .WindowID: window->ID });
9186 IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
9187}
9188
9189// Focus = move navigation cursor, set scrolling, set focus window.
9190void ImGui::FocusItem()
9191{
9192 ImGuiContext& g = *GImGui;
9193 ImGuiWindow* window = g.CurrentWindow;
9194 IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
9195 if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
9196 {
9197 IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
9198 return;
9199 }
9200
9201 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
9202 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9203 SetNavWindow(window);
9204 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: ImGuiDir_Up, move_flags, scroll_flags);
9205 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
9206}
9207
9208void ImGui::ActivateItemByID(ImGuiID id)
9209{
9210 ImGuiContext& g = *GImGui;
9211 g.NavNextActivateId = id;
9212 g.NavNextActivateFlags = ImGuiActivateFlags_None;
9213}
9214
9215// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
9216// But ActivateItem() should function without altering scroll/focus?
9217void ImGui::SetKeyboardFocusHere(int offset)
9218{
9219 ImGuiContext& g = *GImGui;
9220 ImGuiWindow* window = g.CurrentWindow;
9221 IM_ASSERT(offset >= -1); // -1 is allowed but not below
9222 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
9223
9224 // It makes sense in the vast majority of cases to never interrupt a drag and drop.
9225 // When we refactor this function into ActivateItem() we may want to make this an option.
9226 // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
9227 // is also automatically dropped in the event g.ActiveId is stolen.
9228 if (g.DragDropActive || g.MovingWindow != NULL)
9229 {
9230 IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
9231 return;
9232 }
9233
9234 SetNavWindow(window);
9235
9236 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
9237 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
9238 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir: offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
9239 if (offset == -1)
9240 {
9241 NavMoveRequestResolveWithLastItem(result: &g.NavMoveResultLocal);
9242 }
9243 else
9244 {
9245 g.NavTabbingDir = 1;
9246 g.NavTabbingCounter = offset + 1;
9247 }
9248}
9249
9250void ImGui::SetItemDefaultFocus()
9251{
9252 ImGuiContext& g = *GImGui;
9253 ImGuiWindow* window = g.CurrentWindow;
9254 if (!window->Appearing)
9255 return;
9256 if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
9257 return;
9258
9259 g.NavInitRequest = false;
9260 NavApplyItemToResult(result: &g.NavInitResult);
9261 NavUpdateAnyRequestFlag();
9262
9263 // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
9264 if (!window->ClipRect.Contains(r: g.LastItemData.Rect))
9265 ScrollToRectEx(window, rect: g.LastItemData.Rect, flags: ImGuiScrollFlags_None);
9266}
9267
9268void ImGui::SetStateStorage(ImGuiStorage* tree)
9269{
9270 ImGuiWindow* window = GImGui->CurrentWindow;
9271 window->DC.StateStorage = tree ? tree : &window->StateStorage;
9272}
9273
9274ImGuiStorage* ImGui::GetStateStorage()
9275{
9276 ImGuiWindow* window = GImGui->CurrentWindow;
9277 return window->DC.StateStorage;
9278}
9279
9280bool ImGui::IsRectVisible(const ImVec2& size)
9281{
9282 ImGuiWindow* window = GImGui->CurrentWindow;
9283 return window->ClipRect.Overlaps(r: ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
9284}
9285
9286bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
9287{
9288 ImGuiWindow* window = GImGui->CurrentWindow;
9289 return window->ClipRect.Overlaps(r: ImRect(rect_min, rect_max));
9290}
9291
9292//-----------------------------------------------------------------------------
9293// [SECTION] FONTS, TEXTURES
9294//-----------------------------------------------------------------------------
9295// Most of the relevant font logic is in imgui_draw.cpp.
9296// Those are high-level support functions.
9297//-----------------------------------------------------------------------------
9298// - UpdateTexturesNewFrame() [Internal]
9299// - UpdateTexturesEndFrame() [Internal]
9300// - UpdateFontsNewFrame() [Internal]
9301// - UpdateFontsEndFrame() [Internal]
9302// - GetDefaultFont() [Internal]
9303// - RegisterUserTexture() [Internal]
9304// - UnregisterUserTexture() [Internal]
9305// - RegisterFontAtlas() [Internal]
9306// - UnregisterFontAtlas() [Internal]
9307// - SetCurrentFont() [Internal]
9308// - UpdateCurrentFontSize() [Internal]
9309// - SetFontRasterizerDensity() [Internal]
9310// - PushFont()
9311// - PopFont()
9312//-----------------------------------------------------------------------------
9313
9314static void ImGui::UpdateTexturesNewFrame()
9315{
9316 // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count.
9317 ImGuiContext& g = *GImGui;
9318 const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0;
9319 for (ImFontAtlas* atlas : g.FontAtlases)
9320 {
9321 if (atlas->OwnerContext == &g)
9322 {
9323 ImFontAtlasUpdateNewFrame(atlas, frame_count: g.FrameCount, renderer_has_textures: has_textures);
9324 }
9325 else
9326 {
9327 // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it.
9328 // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context.
9329 // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that.
9330 // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures.
9331 IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1);
9332 IM_ASSERT(atlas->RendererHasTextures == has_textures);
9333 }
9334 }
9335}
9336
9337// Build a single texture list
9338static void ImGui::UpdateTexturesEndFrame()
9339{
9340 ImGuiContext& g = *GImGui;
9341 g.PlatformIO.Textures.resize(new_size: 0);
9342 for (ImFontAtlas* atlas : g.FontAtlases)
9343 for (ImTextureData* tex : atlas->TexList)
9344 {
9345 // We provide this information so backends can decide whether to destroy textures.
9346 // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized.
9347 tex->RefCount = (unsigned short)atlas->RefCount;
9348 g.PlatformIO.Textures.push_back(v: tex);
9349 }
9350 for (ImTextureData* tex : g.UserTextures)
9351 g.PlatformIO.Textures.push_back(v: tex);
9352}
9353
9354void ImGui::UpdateFontsNewFrame()
9355{
9356 ImGuiContext& g = *GImGui;
9357 if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0)
9358 for (ImFontAtlas* atlas : g.FontAtlases)
9359 atlas->Locked = true;
9360
9361 if (g.Style._NextFrameFontSizeBase != 0.0f)
9362 {
9363 g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase;
9364 g.Style._NextFrameFontSizeBase = 0.0f;
9365 }
9366
9367 // Apply default font size the first time
9368 ImFont* font = ImGui::GetDefaultFont();
9369 if (g.Style.FontSizeBase <= 0.0f)
9370 g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE);
9371
9372 // Set initial font
9373 g.Font = font;
9374 g.FontSizeBase = g.Style.FontSizeBase;
9375 g.FontSize = 0.0f;
9376 ImFontStackData font_stack_data = { .Font: font, .FontSizeBeforeScaling: g.Style.FontSizeBase, .FontSizeAfterScaling: g.Style.FontSizeBase }; // <--- Will restore FontSize
9377 SetCurrentFont(font: font_stack_data.Font, font_size_before_scaling: font_stack_data.FontSizeBeforeScaling, font_size_after_scaling: 0.0f); // <--- but use 0.0f to enable scale
9378 g.FontStack.push_back(v: font_stack_data);
9379 IM_ASSERT(g.Font->IsLoaded());
9380}
9381
9382void ImGui::UpdateFontsEndFrame()
9383{
9384 PopFont();
9385}
9386
9387ImFont* ImGui::GetDefaultFont()
9388{
9389 ImGuiContext& g = *GImGui;
9390 ImFontAtlas* atlas = g.IO.Fonts;
9391 if (atlas->Builder == NULL || atlas->Fonts.Size == 0)
9392 ImFontAtlasBuildMain(atlas);
9393 return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0];
9394}
9395
9396// EXPERIMENTAL: DO NOT USE YET.
9397void ImGui::RegisterUserTexture(ImTextureData* tex)
9398{
9399 ImGuiContext& g = *GImGui;
9400 tex->RefCount++;
9401 g.UserTextures.push_back(v: tex);
9402}
9403
9404void ImGui::UnregisterUserTexture(ImTextureData* tex)
9405{
9406 ImGuiContext& g = *GImGui;
9407 IM_ASSERT(tex->RefCount > 0);
9408 tex->RefCount--;
9409 g.UserTextures.find_erase(v: tex);
9410}
9411
9412void ImGui::RegisterFontAtlas(ImFontAtlas* atlas)
9413{
9414 ImGuiContext& g = *GImGui;
9415 if (g.FontAtlases.Size == 0)
9416 IM_ASSERT(atlas == g.IO.Fonts);
9417 atlas->RefCount++;
9418 g.FontAtlases.push_back(v: atlas);
9419 ImFontAtlasAddDrawListSharedData(atlas, data: &g.DrawListSharedData);
9420}
9421
9422void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas)
9423{
9424 ImGuiContext& g = *GImGui;
9425 IM_ASSERT(atlas->RefCount > 0);
9426 ImFontAtlasRemoveDrawListSharedData(atlas, data: &g.DrawListSharedData);
9427 g.FontAtlases.find_erase(v: atlas);
9428 atlas->RefCount--;
9429}
9430
9431// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList.
9432// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls.
9433// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did...
9434// - Some code paths never really fully worked with multiple atlas textures.
9435// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture()
9436// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem
9437// because we have a concrete need and a test bed for multiple atlas textures.
9438// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ?
9439void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling)
9440{
9441 ImGuiContext& g = *GImGui;
9442 g.Font = font;
9443 g.FontSizeBase = font_size_before_scaling;
9444 UpdateCurrentFontSize(restore_font_size_after_scaling: font_size_after_scaling);
9445
9446 if (font != NULL)
9447 {
9448 IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
9449#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9450 IM_ASSERT(font->Scale > 0.0f);
9451#endif
9452 ImFontAtlas* atlas = font->ContainerAtlas;
9453 g.DrawListSharedData.FontAtlas = atlas;
9454 g.DrawListSharedData.Font = font;
9455 ImFontAtlasUpdateDrawListsSharedData(atlas);
9456 if (g.CurrentWindow != NULL)
9457 g.CurrentWindow->DrawList->_SetTexture(tex_ref: atlas->TexRef);
9458 }
9459}
9460
9461void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling)
9462{
9463 ImGuiContext& g = *GImGui;
9464 ImGuiWindow* window = g.CurrentWindow;
9465
9466 g.Style.FontSizeBase = g.FontSizeBase;
9467
9468 // Early out to avoid hidden window keeping bakes referenced and out of GC reach.
9469 // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching.
9470 // FIXME: perhaps g.FontSize should be updated?
9471 if (window != NULL && window->SkipItems)
9472 {
9473 ImGuiTable* table = g.CurrentTable;
9474 if (table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false)) // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data.
9475 return;
9476 }
9477
9478 // Restoring is pretty much only used by PopFont()
9479 float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f;
9480 if (final_size == 0.0f)
9481 {
9482 final_size = g.FontSizeBase;
9483
9484 // Global scale factors
9485 final_size *= g.Style.FontScaleMain; // Main global scale factor
9486 final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled.
9487
9488 // Window scale (mostly obsolete now)
9489 if (window != NULL)
9490 final_size *= window->FontWindowScale;
9491
9492 // Legacy scale factors
9493#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9494 final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead!
9495 if (g.Font != NULL)
9496 final_size *= g.Font->Scale; // Was never really useful.
9497#endif
9498 }
9499
9500 // Round font size
9501 // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
9502 // - We may support it better later and remove this rounding.
9503 final_size = GetRoundedFontSize(size: final_size);
9504 final_size = ImClamp(v: final_size, mn: 1.0f, IMGUI_FONT_SIZE_MAX);
9505 if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures))
9506 g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity;
9507 g.FontSize = final_size;
9508 g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(font_size: final_size) : NULL;
9509 g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f;
9510 g.DrawListSharedData.FontSize = g.FontSize;
9511 g.DrawListSharedData.FontScale = g.FontBakedScale;
9512}
9513
9514// Exposed in case user may want to override setting density.
9515// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it.
9516void ImGui::SetFontRasterizerDensity(float rasterizer_density)
9517{
9518 ImGuiContext& g = *GImGui;
9519 IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures);
9520 if (g.FontRasterizerDensity == rasterizer_density)
9521 return;
9522 g.FontRasterizerDensity = rasterizer_density;
9523 UpdateCurrentFontSize(restore_font_size_after_scaling: 0.0f);
9524}
9525
9526// If you want to scale an existing font size! Read comments in imgui.h!
9527void ImGui::PushFont(ImFont* font, float font_size_base)
9528{
9529 ImGuiContext& g = *GImGui;
9530 if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont())
9531 font = g.Font;
9532 IM_ASSERT(font != NULL);
9533 IM_ASSERT(font_size_base >= 0.0f);
9534
9535 g.FontStack.push_back(v: { .Font: g.Font, .FontSizeBeforeScaling: g.FontSizeBase, .FontSizeAfterScaling: g.FontSize });
9536 if (font_size_base == 0.0f)
9537 font_size_base = g.FontSizeBase; // Keep current font size
9538 SetCurrentFont(font, font_size_before_scaling: font_size_base, font_size_after_scaling: 0.0f);
9539}
9540
9541void ImGui::PopFont()
9542{
9543 ImGuiContext& g = *GImGui;
9544 if (g.FontStack.Size <= 0)
9545 {
9546 IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
9547 return;
9548 }
9549 ImFontStackData* font_stack_data = &g.FontStack.back();
9550 SetCurrentFont(font: font_stack_data->Font, font_size_before_scaling: font_stack_data->FontSizeBeforeScaling, font_size_after_scaling: font_stack_data->FontSizeAfterScaling);
9551 g.FontStack.pop_back();
9552}
9553
9554//-----------------------------------------------------------------------------
9555// [SECTION] ID STACK
9556//-----------------------------------------------------------------------------
9557
9558// This is one of the very rare legacy case where we use ImGuiWindow methods,
9559// it should ideally be flattened at some point but it's been used a lots by widgets.
9560IM_MSVC_RUNTIME_CHECKS_OFF
9561ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
9562{
9563 ImGuiID seed = IDStack.back();
9564 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
9565#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9566 ImGuiContext& g = *Ctx;
9567 if (g.DebugHookIdInfo == id)
9568 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
9569#endif
9570 return id;
9571}
9572
9573ImGuiID ImGuiWindow::GetID(const void* ptr)
9574{
9575 ImGuiID seed = IDStack.back();
9576 ImGuiID id = ImHashData(data_p: &ptr, data_size: sizeof(void*), seed);
9577#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9578 ImGuiContext& g = *Ctx;
9579 if (g.DebugHookIdInfo == id)
9580 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_Pointer, data_id: ptr, NULL);
9581#endif
9582 return id;
9583}
9584
9585ImGuiID ImGuiWindow::GetID(int n)
9586{
9587 ImGuiID seed = IDStack.back();
9588 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
9589#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9590 ImGuiContext& g = *Ctx;
9591 if (g.DebugHookIdInfo == id)
9592 ImGui::DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
9593#endif
9594 return id;
9595}
9596
9597// This is only used in rare/specific situations to manufacture an ID out of nowhere.
9598// FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
9599ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs)
9600{
9601 ImGuiID seed = IDStack.back();
9602 ImVec2 p_rel = ImGui::WindowPosAbsToRel(window: this, p: p_abs);
9603 ImGuiID id = ImHashData(data_p: &p_rel, data_size: sizeof(p_rel), seed);
9604 return id;
9605}
9606
9607// "
9608ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
9609{
9610 ImGuiID seed = IDStack.back();
9611 ImRect r_rel = ImGui::WindowRectAbsToRel(window: this, r: r_abs);
9612 ImGuiID id = ImHashData(data_p: &r_rel, data_size: sizeof(r_rel), seed);
9613 return id;
9614}
9615
9616void ImGui::PushID(const char* str_id)
9617{
9618 ImGuiContext& g = *GImGui;
9619 ImGuiWindow* window = g.CurrentWindow;
9620 ImGuiID id = window->GetID(str: str_id);
9621 window->IDStack.push_back(v: id);
9622}
9623
9624void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
9625{
9626 ImGuiContext& g = *GImGui;
9627 ImGuiWindow* window = g.CurrentWindow;
9628 ImGuiID id = window->GetID(str: str_id_begin, str_end: str_id_end);
9629 window->IDStack.push_back(v: id);
9630}
9631
9632void ImGui::PushID(const void* ptr_id)
9633{
9634 ImGuiContext& g = *GImGui;
9635 ImGuiWindow* window = g.CurrentWindow;
9636 ImGuiID id = window->GetID(ptr: ptr_id);
9637 window->IDStack.push_back(v: id);
9638}
9639
9640void ImGui::PushID(int int_id)
9641{
9642 ImGuiContext& g = *GImGui;
9643 ImGuiWindow* window = g.CurrentWindow;
9644 ImGuiID id = window->GetID(n: int_id);
9645 window->IDStack.push_back(v: id);
9646}
9647
9648// Push a given id value ignoring the ID stack as a seed.
9649void ImGui::PushOverrideID(ImGuiID id)
9650{
9651 ImGuiContext& g = *GImGui;
9652 ImGuiWindow* window = g.CurrentWindow;
9653#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9654 if (g.DebugHookIdInfo == id)
9655 DebugHookIdInfo(id, data_type: ImGuiDataType_ID, NULL, NULL);
9656#endif
9657 window->IDStack.push_back(v: id);
9658}
9659
9660// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
9661// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
9662// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
9663ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
9664{
9665 ImGuiID id = ImHashStr(data_p: str, data_size: str_end ? (str_end - str) : 0, seed);
9666#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9667 ImGuiContext& g = *GImGui;
9668 if (g.DebugHookIdInfo == id)
9669 DebugHookIdInfo(id, data_type: ImGuiDataType_String, data_id: str, data_id_end: str_end);
9670#endif
9671 return id;
9672}
9673
9674ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
9675{
9676 ImGuiID id = ImHashData(data_p: &n, data_size: sizeof(n), seed);
9677#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9678 ImGuiContext& g = *GImGui;
9679 if (g.DebugHookIdInfo == id)
9680 DebugHookIdInfo(id, data_type: ImGuiDataType_S32, data_id: (void*)(intptr_t)n, NULL);
9681#endif
9682 return id;
9683}
9684
9685void ImGui::PopID()
9686{
9687 ImGuiWindow* window = GImGui->CurrentWindow;
9688 if (window->IDStack.Size <= 1)
9689 {
9690 IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!");
9691 return;
9692 }
9693 window->IDStack.pop_back();
9694}
9695
9696ImGuiID ImGui::GetID(const char* str_id)
9697{
9698 ImGuiWindow* window = GImGui->CurrentWindow;
9699 return window->GetID(str: str_id);
9700}
9701
9702ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9703{
9704 ImGuiWindow* window = GImGui->CurrentWindow;
9705 return window->GetID(str: str_id_begin, str_end: str_id_end);
9706}
9707
9708ImGuiID ImGui::GetID(const void* ptr_id)
9709{
9710 ImGuiWindow* window = GImGui->CurrentWindow;
9711 return window->GetID(ptr: ptr_id);
9712}
9713
9714ImGuiID ImGui::GetID(int int_id)
9715{
9716 ImGuiWindow* window = GImGui->CurrentWindow;
9717 return window->GetID(n: int_id);
9718}
9719IM_MSVC_RUNTIME_CHECKS_RESTORE
9720
9721//-----------------------------------------------------------------------------
9722// [SECTION] INPUTS
9723//-----------------------------------------------------------------------------
9724// - GetModForLRModKey() [Internal]
9725// - FixupKeyChord() [Internal]
9726// - GetKeyData() [Internal]
9727// - GetKeyIndex() [Internal]
9728// - GetKeyName()
9729// - GetKeyChordName() [Internal]
9730// - CalcTypematicRepeatAmount() [Internal]
9731// - GetTypematicRepeatRate() [Internal]
9732// - GetKeyPressedAmount() [Internal]
9733// - GetKeyMagnitude2d() [Internal]
9734//-----------------------------------------------------------------------------
9735// - UpdateKeyRoutingTable() [Internal]
9736// - GetRoutingIdFromOwnerId() [Internal]
9737// - GetShortcutRoutingData() [Internal]
9738// - CalcRoutingScore() [Internal]
9739// - SetShortcutRouting() [Internal]
9740// - TestShortcutRouting() [Internal]
9741//-----------------------------------------------------------------------------
9742// - IsKeyDown()
9743// - IsKeyPressed()
9744// - IsKeyReleased()
9745//-----------------------------------------------------------------------------
9746// - IsMouseDown()
9747// - IsMouseClicked()
9748// - IsMouseReleased()
9749// - IsMouseDoubleClicked()
9750// - GetMouseClickedCount()
9751// - IsMouseHoveringRect() [Internal]
9752// - IsMouseDragPastThreshold() [Internal]
9753// - IsMouseDragging()
9754// - GetMousePos()
9755// - SetMousePos() [Internal]
9756// - GetMousePosOnOpeningCurrentPopup()
9757// - IsMousePosValid()
9758// - IsAnyMouseDown()
9759// - GetMouseDragDelta()
9760// - ResetMouseDragDelta()
9761// - GetMouseCursor()
9762// - SetMouseCursor()
9763//-----------------------------------------------------------------------------
9764// - UpdateAliasKey()
9765// - GetMergedModsFromKeys()
9766// - UpdateKeyboardInputs()
9767// - UpdateMouseInputs()
9768//-----------------------------------------------------------------------------
9769// - LockWheelingWindow [Internal]
9770// - FindBestWheelingWindow [Internal]
9771// - UpdateMouseWheel() [Internal]
9772//-----------------------------------------------------------------------------
9773// - SetNextFrameWantCaptureKeyboard()
9774// - SetNextFrameWantCaptureMouse()
9775//-----------------------------------------------------------------------------
9776// - GetInputSourceName() [Internal]
9777// - DebugPrintInputEvent() [Internal]
9778// - UpdateInputEvents() [Internal]
9779//-----------------------------------------------------------------------------
9780// - GetKeyOwner() [Internal]
9781// - TestKeyOwner() [Internal]
9782// - SetKeyOwner() [Internal]
9783// - SetItemKeyOwner() [Internal]
9784// - Shortcut() [Internal]
9785//-----------------------------------------------------------------------------
9786
9787static ImGuiKeyChord GetModForLRModKey(ImGuiKey key)
9788{
9789 if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9790 return ImGuiMod_Ctrl;
9791 if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9792 return ImGuiMod_Shift;
9793 if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9794 return ImGuiMod_Alt;
9795 if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9796 return ImGuiMod_Super;
9797 return ImGuiMod_None;
9798}
9799
9800ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9801{
9802 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9803 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9804 if (IsLRModKey(key))
9805 key_chord |= GetModForLRModKey(key);
9806 return key_chord;
9807}
9808
9809ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9810{
9811 ImGuiContext& g = *ctx;
9812
9813 // Special storage location for mods
9814 if (key & ImGuiMod_Mask_)
9815 key = ConvertSingleModFlagToKey(key);
9816
9817 IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9818 return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
9819}
9820
9821// Those names are provided for debugging purpose and are not meant to be saved persistently nor compared.
9822static const char* const GKeyNames[] =
9823{
9824 "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9825 "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9826 "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9827 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9828 "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9829 "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9830 "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9831 "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9832 "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9833 "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9834 "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9835 "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9836 "AppBack", "AppForward", "Oem102",
9837 "GamepadStart", "GamepadBack",
9838 "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9839 "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9840 "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9841 "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9842 "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9843 "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9844 "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9845};
9846IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9847
9848const char* ImGui::GetKeyName(ImGuiKey key)
9849{
9850 if (key == ImGuiKey_None)
9851 return "None";
9852 IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9853 if (key & ImGuiMod_Mask_)
9854 key = ConvertSingleModFlagToKey(key);
9855 if (!IsNamedKey(key))
9856 return "Unknown";
9857
9858 return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9859}
9860
9861// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9862// Lifetime of return value: valid until next call to same function.
9863const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9864{
9865 ImGuiContext& g = *GImGui;
9866
9867 const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9868 if (IsLRModKey(key))
9869 key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9870 ImFormatString(buf: g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), fmt: "%s%s%s%s%s",
9871 (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9872 (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9873 (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9874 (key_chord & ImGuiMod_Super) ? "Super+" : "",
9875 (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9876 size_t len;
9877 if (key == ImGuiKey_None && key_chord != 0)
9878 if ((len = ImStrlen(s: g.TempKeychordName)) != 0) // Remove trailing '+'
9879 g.TempKeychordName[len - 1] = 0;
9880 return g.TempKeychordName;
9881}
9882
9883// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9884// t1 = current time (e.g.: g.Time)
9885// An event is triggered at:
9886// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
9887int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9888{
9889 if (t1 == 0.0f)
9890 return 1;
9891 if (t0 >= t1)
9892 return 0;
9893 if (repeat_rate <= 0.0f)
9894 return (t0 < repeat_delay) && (t1 >= repeat_delay);
9895 const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9896 const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9897 const int count = count_t1 - count_t0;
9898 return count;
9899}
9900
9901void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9902{
9903 ImGuiContext& g = *GImGui;
9904 switch (flags & ImGuiInputFlags_RepeatRateMask_)
9905 {
9906 case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9907 case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9908 case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9909 }
9910}
9911
9912// Return value representing the number of presses in the last time period, for the given repeat rate
9913// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9914int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9915{
9916 ImGuiContext& g = *GImGui;
9917 const ImGuiKeyData* key_data = GetKeyData(key);
9918 if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9919 return 0;
9920 const float t = key_data->DownDuration;
9921 return CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay, repeat_rate);
9922}
9923
9924// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9925ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9926{
9927 return ImVec2(
9928 GetKeyData(key: key_right)->AnalogValue - GetKeyData(key: key_left)->AnalogValue,
9929 GetKeyData(key: key_down)->AnalogValue - GetKeyData(key: key_up)->AnalogValue);
9930}
9931
9932// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9933// Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D
9934// Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
9935// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9936static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9937{
9938 ImGuiContext& g = *GImGui;
9939 rt->EntriesNext.resize(new_size: 0);
9940 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9941 {
9942 const int new_routing_start_idx = rt->EntriesNext.Size;
9943 ImGuiKeyRoutingData* routing_entry;
9944 for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9945 {
9946 routing_entry = &rt->Entries[old_routing_idx];
9947 routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9948 routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9949 routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9950 routing_entry->RoutingNextScore = 255;
9951 if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9952 continue;
9953 rt->EntriesNext.push_back(v: *routing_entry); // Write alive ones into new buffer
9954
9955 // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9956 // This is the result of previous frame's SetShortcutRouting() call.
9957 if (routing_entry->Mods == g.IO.KeyMods)
9958 {
9959 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
9960 if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9961 {
9962 owner_data->OwnerCurr = routing_entry->RoutingCurr;
9963 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9964 }
9965 }
9966 }
9967
9968 // Rewrite linked-list
9969 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9970 for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9971 rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9972 }
9973 rt->Entries.swap(rhs&: rt->EntriesNext); // Swap new and old indexes
9974}
9975
9976// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9977static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9978{
9979 ImGuiContext& g = *GImGui;
9980 return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9981}
9982
9983ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9984{
9985 // Majority of shortcuts will be Key + any number of Mods
9986 // We accept _Single_ mod with ImGuiKey_None.
9987 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl); // Legal
9988 // - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift); // Legal
9989 // - Shortcut(ImGuiMod_Ctrl); // Legal
9990 // - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift); // Not legal
9991 ImGuiContext& g = *GImGui;
9992 ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9993 ImGuiKeyRoutingData* routing_data;
9994 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9995 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9996 if (key == ImGuiKey_None)
9997 key = ConvertSingleModFlagToKey(key: mods);
9998 IM_ASSERT(IsNamedKey(key));
9999
10000 // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
10001 // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
10002 for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
10003 {
10004 routing_data = &rt->Entries[idx];
10005 if (routing_data->Mods == mods)
10006 return routing_data;
10007 }
10008
10009 // Add to linked-list
10010 ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
10011 rt->Entries.push_back(v: ImGuiKeyRoutingData());
10012 routing_data = &rt->Entries[routing_data_idx];
10013 routing_data->Mods = (ImU16)mods;
10014 routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
10015 rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
10016 return routing_data;
10017}
10018
10019// Current score encoding (lower is highest priority):
10020// - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
10021// - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
10022// - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
10023// - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
10024// - 254: ImGuiInputFlags_RouteGlobal
10025// - 255: never route
10026// 'flags' should include an explicit routing policy
10027static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
10028{
10029 ImGuiContext& g = *GImGui;
10030 if (flags & ImGuiInputFlags_RouteFocused)
10031 {
10032 // ActiveID gets top priority
10033 // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
10034 if (owner_id != 0 && g.ActiveId == owner_id)
10035 return 1;
10036
10037 // Score based on distance to focused window (lower is better)
10038 // Assuming both windows are submitting a routing request,
10039 // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
10040 // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best)
10041 // Assuming only WindowA is submitting a routing request,
10042 // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
10043 // This essentially follow the window->ParentWindowForFocusRoute chain.
10044 if (focus_scope_id == 0)
10045 return 255;
10046 for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
10047 if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
10048 return 3 + index_in_focus_path;
10049 return 255;
10050 }
10051 else if (flags & ImGuiInputFlags_RouteActive)
10052 {
10053 if (owner_id != 0 && g.ActiveId == owner_id)
10054 return 1;
10055 return 255;
10056 }
10057 else if (flags & ImGuiInputFlags_RouteGlobal)
10058 {
10059 if (flags & ImGuiInputFlags_RouteOverActive)
10060 return 0;
10061 if (flags & ImGuiInputFlags_RouteOverFocused)
10062 return 2;
10063 return 254;
10064 }
10065 IM_ASSERT(0);
10066 return 0;
10067}
10068
10069// - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
10070// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
10071// - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey_G also emitting a G character.
10072static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
10073{
10074 // Mimic 'ignore_char_inputs' logic in InputText()
10075 ImGuiContext& g = *GImGui;
10076
10077 // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
10078 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10079 const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
10080 if (ignore_char_inputs)
10081 return false;
10082
10083 // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
10084 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10085 if (key == ImGuiKey_None)
10086 return false;
10087 return g.KeysMayBeCharInput.TestBit(n: key);
10088}
10089
10090// Request a desired route for an input chord (key + mods).
10091// Return true if the route is available this frame.
10092// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
10093// (Conceptually this does a "Submit for next frame" + "Test for current frame".
10094// As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
10095bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10096{
10097 ImGuiContext& g = *GImGui;
10098 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10099 flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
10100 else
10101 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
10102 IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
10103 if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
10104 IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
10105
10106 // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
10107 key_chord = FixupKeyChord(key_chord);
10108
10109 // [DEBUG] Debug break requested by user
10110 if (g.DebugBreakInShortcutRouting == key_chord)
10111 IM_DEBUG_BREAK();
10112
10113 if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
10114 if (g.NavWindow == NULL)
10115 return false;
10116
10117 // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
10118 if (flags & ImGuiInputFlags_RouteAlways)
10119 {
10120 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
10121 return true;
10122 }
10123
10124 // Specific culling when there's an active item.
10125 if (g.ActiveId != 0 && g.ActiveId != owner_id)
10126 {
10127 if (flags & ImGuiInputFlags_RouteActive)
10128 return false;
10129
10130 // Cull shortcuts with no modifiers when it could generate a character.
10131 // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
10132 // but Shortcut(Ctrl+G) should generally trigger when InputText() is active.
10133 // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
10134 // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
10135 if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
10136 {
10137 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
10138 return false;
10139 }
10140
10141 // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
10142 if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
10143 {
10144 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10145 if (key == ImGuiKey_None)
10146 key = ConvertSingleModFlagToKey(key: (ImGuiKey)(key_chord & ImGuiMod_Mask_));
10147 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10148 return false;
10149 }
10150 }
10151
10152 // Where do we evaluate route for?
10153 ImGuiID focus_scope_id = g.CurrentFocusScopeId;
10154 if (flags & ImGuiInputFlags_RouteFromRootWindow)
10155 focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
10156
10157 const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
10158 IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
10159 if (score == 255)
10160 return false;
10161
10162 // Submit routing for NEXT frame (assuming score is sufficient)
10163 // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
10164 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
10165 //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
10166 if (score < routing_data->RoutingNextScore)
10167 {
10168 routing_data->RoutingNext = owner_id;
10169 routing_data->RoutingNextScore = (ImU8)score;
10170 }
10171
10172 // Return routing state for CURRENT frame
10173 if (routing_data->RoutingCurr == owner_id)
10174 IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
10175 return routing_data->RoutingCurr == owner_id;
10176}
10177
10178// Currently unused by core (but used by tests)
10179// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
10180bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
10181{
10182 const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
10183 key_chord = FixupKeyChord(key_chord);
10184 ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
10185 return routing_data->RoutingCurr == routing_id;
10186}
10187
10188// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
10189// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
10190bool ImGui::IsKeyDown(ImGuiKey key)
10191{
10192 return IsKeyDown(key, ImGuiKeyOwner_Any);
10193}
10194
10195bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
10196{
10197 const ImGuiKeyData* key_data = GetKeyData(key);
10198 if (!key_data->Down)
10199 return false;
10200 if (!TestKeyOwner(key, owner_id))
10201 return false;
10202 return true;
10203}
10204
10205bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
10206{
10207 return IsKeyPressed(key, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10208}
10209
10210// Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
10211bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
10212{
10213 const ImGuiKeyData* key_data = GetKeyData(key);
10214 if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
10215 return false;
10216 const float t = key_data->DownDuration;
10217 if (t < 0.0f)
10218 return false;
10219 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
10220 if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
10221 flags |= ImGuiInputFlags_Repeat;
10222
10223 bool pressed = (t == 0.0f);
10224 if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
10225 {
10226 float repeat_delay, repeat_rate;
10227 GetTypematicRepeatRate(flags, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
10228 pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
10229 if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
10230 {
10231 // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
10232 // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
10233 ImGuiContext& g = *GImGui;
10234 double key_pressed_time = g.Time - t + 0.00001f;
10235 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
10236 pressed = false;
10237 if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
10238 pressed = false;
10239 if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
10240 pressed = false;
10241 }
10242 }
10243 if (!pressed)
10244 return false;
10245 if (!TestKeyOwner(key, owner_id))
10246 return false;
10247 return true;
10248}
10249
10250bool ImGui::IsKeyReleased(ImGuiKey key)
10251{
10252 return IsKeyReleased(key, ImGuiKeyOwner_Any);
10253}
10254
10255bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
10256{
10257 const ImGuiKeyData* key_data = GetKeyData(key);
10258 if (key_data->DownDurationPrev < 0.0f || key_data->Down)
10259 return false;
10260 if (!TestKeyOwner(key, owner_id))
10261 return false;
10262 return true;
10263}
10264
10265bool ImGui::IsMouseDown(ImGuiMouseButton button)
10266{
10267 ImGuiContext& g = *GImGui;
10268 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10269 return g.IO.MouseDown[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
10270}
10271
10272bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
10273{
10274 ImGuiContext& g = *GImGui;
10275 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10276 return g.IO.MouseDown[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
10277}
10278
10279bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
10280{
10281 return IsMouseClicked(button, flags: repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10282}
10283
10284bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
10285{
10286 ImGuiContext& g = *GImGui;
10287 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10288 if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
10289 return false;
10290 const float t = g.IO.MouseDownDuration[button];
10291 if (t < 0.0f)
10292 return false;
10293 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
10294
10295 const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
10296 const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t0: t - g.IO.DeltaTime, t1: t, repeat_delay: g.IO.KeyRepeatDelay, repeat_rate: g.IO.KeyRepeatRate) > 0);
10297 if (!pressed)
10298 return false;
10299
10300 if (!TestKeyOwner(key: MouseButtonToKey(button), owner_id))
10301 return false;
10302
10303 return true;
10304}
10305
10306bool ImGui::IsMouseReleased(ImGuiMouseButton button)
10307{
10308 ImGuiContext& g = *GImGui;
10309 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10310 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
10311}
10312
10313bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
10314{
10315 ImGuiContext& g = *GImGui;
10316 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10317 return g.IO.MouseReleased[button] && TestKeyOwner(key: MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
10318}
10319
10320// Use if you absolutely need to distinguish single-click from double-click by introducing a delay.
10321// Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test.
10322// This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename.
10323bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay)
10324{
10325 ImGuiContext& g = *GImGui;
10326 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10327 const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]);
10328 return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay);
10329}
10330
10331bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
10332{
10333 ImGuiContext& g = *GImGui;
10334 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10335 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), ImGuiKeyOwner_Any);
10336}
10337
10338bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
10339{
10340 ImGuiContext& g = *GImGui;
10341 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10342 return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(key: MouseButtonToKey(button), owner_id);
10343}
10344
10345int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
10346{
10347 ImGuiContext& g = *GImGui;
10348 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10349 return g.IO.MouseClickedCount[button];
10350}
10351
10352// Test if mouse cursor is hovering given rectangle
10353// NB- Rectangle is clipped by our current clip setting
10354// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
10355bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
10356{
10357 ImGuiContext& g = *GImGui;
10358
10359 // Clip
10360 ImRect rect_clipped(r_min, r_max);
10361 if (clip)
10362 rect_clipped.ClipWith(r: g.CurrentWindow->ClipRect);
10363
10364 // Hit testing, expanded for touch input
10365 if (!rect_clipped.ContainsWithPad(p: g.IO.MousePos, pad: g.Style.TouchExtraPadding))
10366 return false;
10367 if (!g.MouseViewport->GetMainRect().Overlaps(r: rect_clipped))
10368 return false;
10369 return true;
10370}
10371
10372// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
10373// [Internal] This doesn't test if the button is pressed
10374bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
10375{
10376 ImGuiContext& g = *GImGui;
10377 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10378 if (lock_threshold < 0.0f)
10379 lock_threshold = g.IO.MouseDragThreshold;
10380 return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
10381}
10382
10383bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
10384{
10385 ImGuiContext& g = *GImGui;
10386 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10387 if (!g.IO.MouseDown[button])
10388 return false;
10389 return IsMouseDragPastThreshold(button, lock_threshold);
10390}
10391
10392ImVec2 ImGui::GetMousePos()
10393{
10394 ImGuiContext& g = *GImGui;
10395 return g.IO.MousePos;
10396}
10397
10398// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
10399// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
10400void ImGui::TeleportMousePos(const ImVec2& pos)
10401{
10402 ImGuiContext& g = *GImGui;
10403 g.IO.MousePos = g.IO.MousePosPrev = pos;
10404 g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
10405 g.IO.WantSetMousePos = true;
10406 //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
10407}
10408
10409// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
10410ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
10411{
10412 ImGuiContext& g = *GImGui;
10413 if (g.BeginPopupStack.Size > 0)
10414 return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
10415 return g.IO.MousePos;
10416}
10417
10418// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
10419bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
10420{
10421 // The assert is only to silence a false-positive in XCode Static Analysis.
10422 // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
10423 IM_ASSERT(GImGui != NULL);
10424 const float MOUSE_INVALID = -256000.0f;
10425 ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
10426 return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
10427}
10428
10429// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
10430bool ImGui::IsAnyMouseDown()
10431{
10432 ImGuiContext& g = *GImGui;
10433 for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
10434 if (g.IO.MouseDown[n])
10435 return true;
10436 return false;
10437}
10438
10439// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
10440// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
10441// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
10442ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
10443{
10444 ImGuiContext& g = *GImGui;
10445 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10446 if (lock_threshold < 0.0f)
10447 lock_threshold = g.IO.MouseDragThreshold;
10448 if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
10449 if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
10450 if (IsMousePosValid(mouse_pos: &g.IO.MousePos) && IsMousePosValid(mouse_pos: &g.IO.MouseClickedPos[button]))
10451 return g.IO.MousePos - g.IO.MouseClickedPos[button];
10452 return ImVec2(0.0f, 0.0f);
10453}
10454
10455void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
10456{
10457 ImGuiContext& g = *GImGui;
10458 IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
10459 // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
10460 g.IO.MouseClickedPos[button] = g.IO.MousePos;
10461}
10462
10463// Get desired mouse cursor shape.
10464// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
10465// updated during the frame, and locked in EndFrame()/Render().
10466// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
10467ImGuiMouseCursor ImGui::GetMouseCursor()
10468{
10469 ImGuiContext& g = *GImGui;
10470 return g.MouseCursor;
10471}
10472
10473// We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
10474// Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may
10475// handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
10476void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
10477{
10478 ImGuiContext& g = *GImGui;
10479 g.MouseCursor = cursor_type;
10480}
10481
10482static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
10483{
10484 IM_ASSERT(ImGui::IsAliasKey(key));
10485 ImGuiKeyData* key_data = ImGui::GetKeyData(key);
10486 key_data->Down = v;
10487 key_data->AnalogValue = analog_value;
10488}
10489
10490// [Internal] Do not use directly
10491static ImGuiKeyChord GetMergedModsFromKeys()
10492{
10493 ImGuiKeyChord mods = 0;
10494 if (ImGui::IsKeyDown(key: ImGuiMod_Ctrl)) { mods |= ImGuiMod_Ctrl; }
10495 if (ImGui::IsKeyDown(key: ImGuiMod_Shift)) { mods |= ImGuiMod_Shift; }
10496 if (ImGui::IsKeyDown(key: ImGuiMod_Alt)) { mods |= ImGuiMod_Alt; }
10497 if (ImGui::IsKeyDown(key: ImGuiMod_Super)) { mods |= ImGuiMod_Super; }
10498 return mods;
10499}
10500
10501static void ImGui::UpdateKeyboardInputs()
10502{
10503 ImGuiContext& g = *GImGui;
10504 ImGuiIO& io = g.IO;
10505
10506 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10507 io.ClearInputKeys();
10508
10509 // Update aliases
10510 for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
10511 UpdateAliasKey(key: MouseButtonToKey(button: n), v: io.MouseDown[n], analog_value: io.MouseDown[n] ? 1.0f : 0.0f);
10512 UpdateAliasKey(key: ImGuiKey_MouseWheelX, v: io.MouseWheelH != 0.0f, analog_value: io.MouseWheelH);
10513 UpdateAliasKey(key: ImGuiKey_MouseWheelY, v: io.MouseWheel != 0.0f, analog_value: io.MouseWheel);
10514
10515 // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
10516 // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10517 // - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
10518 // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
10519 const ImGuiKeyChord prev_key_mods = io.KeyMods;
10520 io.KeyMods = GetMergedModsFromKeys();
10521 io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
10522 io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
10523 io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
10524 io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
10525 if (prev_key_mods != io.KeyMods)
10526 g.LastKeyModsChangeTime = g.Time;
10527 if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
10528 g.LastKeyModsChangeFromNoneTime = g.Time;
10529
10530 // Clear gamepad data if disabled
10531 if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
10532 for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
10533 {
10534 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
10535 io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
10536 }
10537
10538 // Update keys
10539 for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
10540 {
10541 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10542 key_data->DownDurationPrev = key_data->DownDuration;
10543 key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
10544 if (key_data->DownDuration == 0.0f)
10545 {
10546 if (IsKeyboardKey(key: (ImGuiKey)key))
10547 g.LastKeyboardKeyPressTime = g.Time;
10548 else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
10549 g.LastKeyboardKeyPressTime = g.Time;
10550 }
10551 }
10552
10553 // Update keys/input owner (named keys only): one entry per key
10554 for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
10555 {
10556 ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
10557 ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
10558 owner_data->OwnerCurr = owner_data->OwnerNext;
10559 if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
10560 owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
10561 owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down; // Clear LockUntilRelease when key is not Down anymore
10562 }
10563
10564 // Update key routing (for e.g. shortcuts)
10565 UpdateKeyRoutingTable(rt: &g.KeysRoutingTable);
10566}
10567
10568static void ImGui::UpdateMouseInputs()
10569{
10570 ImGuiContext& g = *GImGui;
10571 ImGuiIO& io = g.IO;
10572
10573 // Mouse Wheel swapping flag
10574 // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
10575 // - We avoid doing it on OSX as it the OS input layer handles this already.
10576 // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
10577 // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
10578 io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
10579
10580 // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
10581 if (IsMousePosValid(mouse_pos: &io.MousePos))
10582 io.MousePos = g.MouseLastValidPos = ImFloor(v: io.MousePos);
10583
10584 // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
10585 if (IsMousePosValid(mouse_pos: &io.MousePos) && IsMousePosValid(mouse_pos: &io.MousePosPrev))
10586 io.MouseDelta = io.MousePos - io.MousePosPrev;
10587 else
10588 io.MouseDelta = ImVec2(0.0f, 0.0f);
10589
10590 // Update stationary timer.
10591 // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
10592 const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
10593 const bool mouse_stationary = (ImLengthSqr(lhs: io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
10594 g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
10595 //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
10596
10597 // If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
10598 if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
10599 g.NavHighlightItemUnderNav = false;
10600
10601 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
10602 {
10603 io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
10604 io.MouseClickedCount[i] = 0; // Will be filled below
10605 io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
10606 if (io.MouseReleased[i])
10607 io.MouseReleasedTime[i] = g.Time;
10608 io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
10609 io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
10610 if (io.MouseClicked[i])
10611 {
10612 bool is_repeated_click = false;
10613 if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
10614 {
10615 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10616 if (ImLengthSqr(lhs: delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
10617 is_repeated_click = true;
10618 }
10619 if (is_repeated_click)
10620 io.MouseClickedLastCount[i]++;
10621 else
10622 io.MouseClickedLastCount[i] = 1;
10623 io.MouseClickedTime[i] = g.Time;
10624 io.MouseClickedPos[i] = io.MousePos;
10625 io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10626 io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10627 io.MouseDragMaxDistanceSqr[i] = 0.0f;
10628 }
10629 else if (io.MouseDown[i])
10630 {
10631 // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10632 ImVec2 delta_from_click_pos = IsMousePosValid(mouse_pos: &io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10633 io.MouseDragMaxDistanceSqr[i] = ImMax(lhs: io.MouseDragMaxDistanceSqr[i], rhs: ImLengthSqr(lhs: delta_from_click_pos));
10634 io.MouseDragMaxDistanceAbs[i].x = ImMax(lhs: io.MouseDragMaxDistanceAbs[i].x, rhs: delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
10635 io.MouseDragMaxDistanceAbs[i].y = ImMax(lhs: io.MouseDragMaxDistanceAbs[i].y, rhs: delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
10636 }
10637
10638 // We provide io.MouseDoubleClicked[] as a legacy service
10639 io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10640
10641 // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
10642 if (io.MouseClicked[i])
10643 g.NavHighlightItemUnderNav = false;
10644 }
10645}
10646
10647static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10648{
10649 ImGuiContext& g = *GImGui;
10650 if (window)
10651 g.WheelingWindowReleaseTimer = ImMin(lhs: g.WheelingWindowReleaseTimer + ImAbs(x: wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, rhs: WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10652 else
10653 g.WheelingWindowReleaseTimer = 0.0f;
10654 if (g.WheelingWindow == window)
10655 return;
10656 IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10657 g.WheelingWindow = window;
10658 g.WheelingWindowRefMousePos = g.IO.MousePos;
10659 if (window == NULL)
10660 {
10661 g.WheelingWindowStartFrame = -1;
10662 g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10663 }
10664}
10665
10666static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10667{
10668 // For each axis, find window in the hierarchy that may want to use scrolling
10669 ImGuiContext& g = *GImGui;
10670 ImGuiWindow* windows[2] = { NULL, NULL };
10671 for (int axis = 0; axis < 2; axis++)
10672 if (wheel[axis] != 0.0f)
10673 for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10674 {
10675 // Bubble up into parent window if:
10676 // - a child window doesn't allow any scrolling.
10677 // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10678 //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10679 const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10680 const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10681 //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10682 if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10683 break; // select this window
10684 }
10685 if (windows[0] == NULL && windows[1] == NULL)
10686 return NULL;
10687
10688 // If there's only one window or only one axis then there's no ambiguity
10689 if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10690 return windows[1] ? windows[1] : windows[0];
10691
10692 // If candidate are different windows we need to decide which one to prioritize
10693 // - First frame: only find a winner if one axis is zero.
10694 // - Subsequent frames: only find a winner when one is more than the other.
10695 if (g.WheelingWindowStartFrame == -1)
10696 g.WheelingWindowStartFrame = g.FrameCount;
10697 if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10698 {
10699 g.WheelingWindowWheelRemainder = wheel;
10700 return NULL;
10701 }
10702 return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10703}
10704
10705// Called by NewFrame()
10706void ImGui::UpdateMouseWheel()
10707{
10708 // Reset the locked window if we move the mouse or after the timer elapses.
10709 // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
10710 ImGuiContext& g = *GImGui;
10711 if (g.WheelingWindow != NULL)
10712 {
10713 g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10714 if (IsMousePosValid() && ImLengthSqr(lhs: g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10715 g.WheelingWindowReleaseTimer = 0.0f;
10716 if (g.WheelingWindowReleaseTimer <= 0.0f)
10717 LockWheelingWindow(NULL, wheel_amount: 0.0f);
10718 }
10719
10720 ImVec2 wheel;
10721 wheel.x = TestKeyOwner(key: ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10722 wheel.y = TestKeyOwner(key: ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10723
10724 //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10725 ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10726 if (!mouse_window || mouse_window->Collapsed)
10727 return;
10728
10729 // Zoom / Scale window
10730 // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10731 if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10732 {
10733 LockWheelingWindow(window: mouse_window, wheel_amount: wheel.y);
10734 ImGuiWindow* window = mouse_window;
10735 const float new_font_scale = ImClamp(v: window->FontWindowScale + g.IO.MouseWheel * 0.10f, mn: 0.50f, mx: 2.50f);
10736 const float scale = new_font_scale / window->FontWindowScale;
10737 window->FontWindowScale = new_font_scale;
10738 if (window == window->RootWindow)
10739 {
10740 const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10741 SetWindowPos(window, pos: window->Pos + offset, cond: 0);
10742 window->Size = ImTrunc(v: window->Size * scale);
10743 window->SizeFull = ImTrunc(v: window->SizeFull * scale);
10744 }
10745 return;
10746 }
10747 if (g.IO.KeyCtrl)
10748 return;
10749
10750 // Mouse wheel scrolling
10751 // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10752 if (g.IO.MouseWheelRequestAxisSwap)
10753 wheel = ImVec2(wheel.y, 0.0f);
10754
10755 // Maintain a rough average of moving magnitude on both axes
10756 // FIXME: should by based on wall clock time rather than frame-counter
10757 g.WheelingAxisAvg.x = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.x, sample: ImAbs(x: wheel.x), n: 30);
10758 g.WheelingAxisAvg.y = ImExponentialMovingAverage(avg: g.WheelingAxisAvg.y, sample: ImAbs(x: wheel.y), n: 30);
10759
10760 // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10761 wheel += g.WheelingWindowWheelRemainder;
10762 g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10763 if (wheel.x == 0.0f && wheel.y == 0.0f)
10764 return;
10765
10766 // Mouse wheel scrolling: find target and apply
10767 // - don't renew lock if axis doesn't apply on the window.
10768 // - select a main axis when both axes are being moved.
10769 if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10770 if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10771 {
10772 bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10773 if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10774 do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10775 if (do_scroll[ImGuiAxis_X])
10776 {
10777 LockWheelingWindow(window, wheel_amount: wheel.x);
10778 float max_step = window->InnerRect.GetWidth() * 0.67f;
10779 float scroll_step = ImTrunc(f: ImMin(lhs: 2 * window->FontRefSize, rhs: max_step));
10780 SetScrollX(window, scroll_x: window->Scroll.x - wheel.x * scroll_step);
10781 g.WheelingWindowScrolledFrame = g.FrameCount;
10782 }
10783 if (do_scroll[ImGuiAxis_Y])
10784 {
10785 LockWheelingWindow(window, wheel_amount: wheel.y);
10786 float max_step = window->InnerRect.GetHeight() * 0.67f;
10787 float scroll_step = ImTrunc(f: ImMin(lhs: 5 * window->FontRefSize, rhs: max_step));
10788 SetScrollY(window, scroll_y: window->Scroll.y - wheel.y * scroll_step);
10789 g.WheelingWindowScrolledFrame = g.FrameCount;
10790 }
10791 }
10792}
10793
10794void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10795{
10796 ImGuiContext& g = *GImGui;
10797 g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10798}
10799
10800void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10801{
10802 ImGuiContext& g = *GImGui;
10803 g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10804}
10805
10806#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10807static const char* GetInputSourceName(ImGuiInputSource source)
10808{
10809 const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10810 IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
10811 if (source < 0 || source >= ImGuiInputSource_COUNT)
10812 return "Unknown";
10813 return input_source_names[source];
10814}
10815static const char* GetMouseSourceName(ImGuiMouseSource source)
10816{
10817 const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10818 IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT);
10819 if (source < 0 || source >= ImGuiMouseSource_COUNT)
10820 return "Unknown";
10821 return mouse_source_names[source];
10822}
10823static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10824{
10825 ImGuiContext& g = *GImGui;
10826 if (e->Type == ImGuiInputEventType_MousePos) { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
10827 if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
10828 if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
10829 if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10830 if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
10831 if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10832 if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10833}
10834#endif
10835
10836// Process input queue
10837// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10838// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10839// - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
10840void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10841{
10842 ImGuiContext& g = *GImGui;
10843 ImGuiIO& io = g.IO;
10844
10845 // Only trickle chars<>key when working with InputText()
10846 // FIXME: InputText() could parse event trail?
10847 // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10848 const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10849
10850 bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
10851 int mouse_button_changed = 0x00;
10852 ImBitArray<ImGuiKey_NamedKey_COUNT> key_changed_mask;
10853
10854 int event_n = 0;
10855 for (; event_n < g.InputEventsQueue.Size; event_n++)
10856 {
10857 ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10858 if (e->Type == ImGuiInputEventType_MousePos)
10859 {
10860 if (g.IO.WantSetMousePos)
10861 continue;
10862 // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10863 ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10864 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10865 break;
10866 io.MousePos = event_pos;
10867 io.MouseSource = e->MousePos.MouseSource;
10868 mouse_moved = true;
10869 }
10870 else if (e->Type == ImGuiInputEventType_MouseButton)
10871 {
10872 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10873 const ImGuiMouseButton button = e->MouseButton.Button;
10874 IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10875 if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10876 break;
10877 if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10878 break;
10879 io.MouseDown[button] = e->MouseButton.Down;
10880 io.MouseSource = e->MouseButton.MouseSource;
10881 mouse_button_changed |= (1 << button);
10882 }
10883 else if (e->Type == ImGuiInputEventType_MouseWheel)
10884 {
10885 // Trickling Rule: Stop processing queued events if we got multiple action on the event
10886 if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10887 break;
10888 io.MouseWheelH += e->MouseWheel.WheelX;
10889 io.MouseWheel += e->MouseWheel.WheelY;
10890 io.MouseSource = e->MouseWheel.MouseSource;
10891 mouse_wheeled = true;
10892 }
10893 else if (e->Type == ImGuiInputEventType_MouseViewport)
10894 {
10895 io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10896 }
10897 else if (e->Type == ImGuiInputEventType_Key)
10898 {
10899 // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10900 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10901 continue;
10902 ImGuiKey key = e->Key.Key;
10903 IM_ASSERT(key != ImGuiKey_None);
10904 ImGuiKeyData* key_data = GetKeyData(key);
10905 const int key_data_index = (int)(key_data - g.IO.KeysData);
10906 if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(n: key_data_index) || mouse_button_changed != 0))
10907 break;
10908
10909 const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(key_chord: GetMergedModsFromKeys() | key);
10910 if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input))
10911 break;
10912
10913 if (key_data->Down != e->Key.Down) // Analog change only do not trigger this, so it won't block e.g. further mouse pos events testing key_changed.
10914 {
10915 key_changed = true;
10916 key_changed_mask.SetBit(key_data_index);
10917 if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
10918 key_changed_nonchar = true;
10919 }
10920
10921 key_data->Down = e->Key.Down;
10922 key_data->AnalogValue = e->Key.AnalogValue;
10923 }
10924 else if (e->Type == ImGuiInputEventType_Text)
10925 {
10926 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10927 continue;
10928 // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10929 if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10930 break;
10931 if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar)
10932 break;
10933 unsigned int c = e->Text.Char;
10934 io.InputQueueCharacters.push_back(v: c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10935 if (trickle_interleaved_nonchar_keys_and_text)
10936 text_inputted = true;
10937 }
10938 else if (e->Type == ImGuiInputEventType_Focus)
10939 {
10940 // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10941 // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10942 const bool focus_lost = !e->AppFocused.Focused;
10943 io.AppFocusLost = focus_lost;
10944 }
10945 else
10946 {
10947 IM_ASSERT(0 && "Unknown event!");
10948 }
10949 }
10950
10951 // Record trail (for domain-specific applications wanting to access a precise trail)
10952 //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10953 for (int n = 0; n < event_n; n++)
10954 g.InputEventsTrail.push_back(v: g.InputEventsQueue[n]);
10955
10956 // [DEBUG]
10957#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10958 if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10959 for (int n = 0; n < g.InputEventsQueue.Size; n++)
10960 DebugPrintInputEvent(prefix: n < event_n ? "Processed" : "Remaining", e: &g.InputEventsQueue[n]);
10961#endif
10962
10963 // Remaining events will be processed on the next frame
10964 if (event_n == g.InputEventsQueue.Size)
10965 g.InputEventsQueue.resize(new_size: 0);
10966 else
10967 g.InputEventsQueue.erase(it: g.InputEventsQueue.Data, it_last: g.InputEventsQueue.Data + event_n);
10968
10969 // Clear buttons state when focus is lost
10970 // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10971 // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10972 // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10973 if (g.IO.AppFocusLost)
10974 {
10975 g.IO.ClearInputKeys();
10976 g.IO.ClearInputMouse();
10977 }
10978}
10979
10980ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10981{
10982 if (!IsNamedKeyOrMod(key))
10983 return ImGuiKeyOwner_NoOwner;
10984
10985 ImGuiContext& g = *GImGui;
10986 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
10987 ImGuiID owner_id = owner_data->OwnerCurr;
10988
10989 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10990 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10991 return ImGuiKeyOwner_NoOwner;
10992
10993 return owner_id;
10994}
10995
10996// TestKeyOwner(..., ID) : (owner == None || owner == ID)
10997// TestKeyOwner(..., None) : (owner == None)
10998// TestKeyOwner(..., Any) : no owner test
10999// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
11000bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
11001{
11002 if (!IsNamedKeyOrMod(key))
11003 return true;
11004
11005 ImGuiContext& g = *GImGui;
11006 if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
11007 if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
11008 return false;
11009
11010 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
11011 if (owner_id == ImGuiKeyOwner_Any)
11012 return (owner_data->LockThisFrame == false);
11013
11014 // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
11015 // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
11016 // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
11017 if (owner_data->OwnerCurr != owner_id)
11018 {
11019 if (owner_data->LockThisFrame)
11020 return false;
11021 if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
11022 return false;
11023 }
11024
11025 return true;
11026}
11027
11028// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
11029// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
11030// - SetKeyOwner(..., None) : clears owner
11031// - SetKeyOwner(..., Any, !Lock) : illegal (assert)
11032// - SetKeyOwner(..., Any or None, Lock) : set lock
11033void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
11034{
11035 ImGuiContext& g = *GImGui;
11036 IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
11037 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
11038 //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
11039
11040 ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(ctx: &g, key);
11041 owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
11042
11043 // We cannot lock by default as it would likely break lots of legacy code.
11044 // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
11045 owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
11046 owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
11047}
11048
11049// Rarely used helper
11050void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
11051{
11052 if (key_chord & ImGuiMod_Ctrl) { SetKeyOwner(key: ImGuiMod_Ctrl, owner_id, flags); }
11053 if (key_chord & ImGuiMod_Shift) { SetKeyOwner(key: ImGuiMod_Shift, owner_id, flags); }
11054 if (key_chord & ImGuiMod_Alt) { SetKeyOwner(key: ImGuiMod_Alt, owner_id, flags); }
11055 if (key_chord & ImGuiMod_Super) { SetKeyOwner(key: ImGuiMod_Super, owner_id, flags); }
11056 if (key_chord & ~ImGuiMod_Mask_) { SetKeyOwner(key: (ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
11057}
11058
11059// This is more or less equivalent to:
11060// if (IsItemHovered() || IsItemActive())
11061// SetKeyOwner(key, GetItemID());
11062// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
11063// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
11064// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
11065void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
11066{
11067 ImGuiContext& g = *GImGui;
11068 ImGuiID id = g.LastItemData.ID;
11069 if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
11070 return;
11071 if ((flags & ImGuiInputFlags_CondMask_) == 0)
11072 flags |= ImGuiInputFlags_CondDefault_;
11073 if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
11074 {
11075 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
11076 SetKeyOwner(key, owner_id: id, flags: flags & ~ImGuiInputFlags_CondMask_);
11077 }
11078}
11079
11080void ImGui::SetItemKeyOwner(ImGuiKey key)
11081{
11082 SetItemKeyOwner(key, flags: ImGuiInputFlags_None);
11083}
11084
11085// This is the only public API until we expose owner_id versions of the API as replacements.
11086bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
11087{
11088 return IsKeyChordPressed(key_chord, flags: ImGuiInputFlags_None, ImGuiKeyOwner_Any);
11089}
11090
11091// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
11092bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11093{
11094 ImGuiContext& g = *GImGui;
11095 key_chord = FixupKeyChord(key_chord);
11096 ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
11097 if (g.IO.KeyMods != mods)
11098 return false;
11099
11100 // Special storage location for mods
11101 ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
11102 if (key == ImGuiKey_None)
11103 key = ConvertSingleModFlagToKey(key: mods);
11104 if (!IsKeyPressed(key, flags: (flags & ImGuiInputFlags_RepeatMask_), owner_id))
11105 return false;
11106 return true;
11107}
11108
11109void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11110{
11111 ImGuiContext& g = *GImGui;
11112 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
11113 g.NextItemData.Shortcut = key_chord;
11114 g.NextItemData.ShortcutFlags = flags;
11115}
11116
11117// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
11118void ImGui::ItemHandleShortcut(ImGuiID id)
11119{
11120 ImGuiContext& g = *GImGui;
11121 ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
11122 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
11123
11124 if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
11125 return;
11126 if (flags & ImGuiInputFlags_Tooltip)
11127 {
11128 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
11129 g.LastItemData.Shortcut = g.NextItemData.Shortcut;
11130 }
11131 if (!Shortcut(key_chord: g.NextItemData.Shortcut, flags: flags & ImGuiInputFlags_SupportedByShortcut, owner_id: id) || g.NavActivateId != 0)
11132 return;
11133
11134 // FIXME: Generalize Activation queue?
11135 g.NavActivateId = id; // Will effectively disable clipping.
11136 g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
11137 //if (g.ActiveId == 0 || g.ActiveId == id)
11138 g.NavActivateDownId = g.NavActivatePressedId = id;
11139 NavHighlightActivated(id);
11140}
11141
11142bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
11143{
11144 return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
11145}
11146
11147bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
11148{
11149 ImGuiContext& g = *GImGui;
11150 //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
11151
11152 // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
11153 if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
11154 flags |= ImGuiInputFlags_RouteFocused;
11155
11156 // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
11157 // Effectively makes Shortcut() always input-owner aware.
11158 if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
11159 owner_id = GetRoutingIdFromOwnerId(owner_id);
11160
11161 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11162 return false;
11163
11164 // Submit route
11165 if (!SetShortcutRouting(key_chord, flags, owner_id))
11166 return false;
11167
11168 // Default repeat behavior for Shortcut()
11169 // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
11170 if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
11171 flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
11172
11173 if (!IsKeyChordPressed(key_chord, flags, owner_id))
11174 return false;
11175
11176 // Claim mods during the press
11177 SetKeyOwnersForKeyChord(key_chord: key_chord & ImGuiMod_Mask_, owner_id);
11178
11179 IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
11180 return true;
11181}
11182
11183//-----------------------------------------------------------------------------
11184// [SECTION] ERROR CHECKING, STATE RECOVERY
11185//-----------------------------------------------------------------------------
11186// - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
11187// - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11188// - ErrorCheckNewFrameSanityChecks()
11189// - ErrorCheckEndFrameSanityChecks()
11190// - ErrorRecoveryStoreState()
11191// - ErrorRecoveryTryToRecoverState()
11192// - ErrorRecoveryTryToRecoverWindowState()
11193// - ErrorLog()
11194//-----------------------------------------------------------------------------
11195
11196// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
11197// Called by IMGUI_CHECKVERSION().
11198// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
11199// If this triggers you have mismatched headers and compiled code versions.
11200// - It could be because of a build issue (using new headers with old compiled code)
11201// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
11202// THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
11203// Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
11204// Otherwise it is possible that different compilation units would see different structure layout.
11205// If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
11206bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
11207{
11208 bool error = false;
11209 if (strcmp(s1: version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
11210 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
11211 if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
11212 if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
11213 if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
11214 if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
11215 if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
11216 return !error;
11217}
11218
11219// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos()
11220// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing
11221// windows, table column contents size used for auto-resizing columns, group size).
11222// This was causing issues and ambiguities and we needed to retire that.
11223// From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED.
11224//
11225// Previously this would make the window content size ~200x200:
11226// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE
11227// Instead, please submit an item:
11228// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
11229// Alternative:
11230// Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
11231//
11232// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item,
11233// and with a position that would grow the parent contents size.
11234//
11235// Advanced:
11236// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos())
11237// had a side-effect on layout! In particular this caused problem to compute group boundaries.
11238// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the
11239// group to be taller because auto-sizing generally adds padding on bottom and right side.
11240// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect.
11241// Using vertical alignment patterns would frequently trigger this sorts of issue.
11242// - See https://github.com/ocornut/imgui/issues/5548 for more details.
11243void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
11244{
11245 ImGuiContext& g = *GImGui;
11246 ImGuiWindow* window = g.CurrentWindow;
11247 IM_ASSERT(window->DC.IsSetPos);
11248 window->DC.IsSetPos = false;
11249 if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
11250 return;
11251 if (window->SkipItems)
11252 return;
11253 IM_ASSERT_USER_ERROR(0, "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries.\nPlease submit an item e.g. Dummy() afterwards in order to grow window/parent boundaries.");
11254
11255 // For reference, the old behavior was essentially:
11256 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11257}
11258
11259static void ImGui::ErrorCheckNewFrameSanityChecks()
11260{
11261 ImGuiContext& g = *GImGui;
11262
11263 // Check user IM_ASSERT macro
11264 // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
11265 // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
11266 // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
11267 // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
11268 // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
11269 if (true) IM_ASSERT(1); else IM_ASSERT(0);
11270
11271 // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
11272 // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
11273#ifdef __EMSCRIPTEN__
11274 if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
11275 g.IO.DeltaTime = 0.00001f;
11276#endif
11277
11278 // Check user data
11279 // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
11280 IM_ASSERT(g.Initialized);
11281 IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
11282 IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
11283 IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
11284 IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
11285 IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
11286 IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
11287 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!");
11288 IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders.
11289 IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
11290 IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
11291 IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes);
11292
11293 // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
11294 if (g.IO.ConfigErrorRecovery)
11295 IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
11296
11297#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11298 if (g.IO.FontGlobalScale > 1.0f)
11299 IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!");
11300
11301 // Remap legacy names
11302 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
11303 {
11304 g.IO.ConfigNavMoveSetMousePos = true;
11305 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
11306 }
11307 if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
11308 {
11309 g.IO.ConfigNavCaptureKeyboard = false;
11310 g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
11311 }
11312 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts)
11313 {
11314 g.IO.ConfigDpiScaleFonts = false;
11315 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts;
11316 }
11317 if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
11318 {
11319 g.IO.ConfigDpiScaleViewports = false;
11320 g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports;
11321 }
11322
11323 // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
11324 if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
11325 g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
11326 if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
11327 g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); };
11328#endif
11329
11330 // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
11331 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
11332 IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11333 if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
11334 IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
11335
11336 // Perform simple checks: multi-viewport and platform windows support
11337 if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
11338 {
11339 if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
11340 {
11341 IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
11342 IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
11343 IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
11344 IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
11345 IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
11346 IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
11347 IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
11348 IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
11349 IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
11350 if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
11351 IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
11352 }
11353 else
11354 {
11355 // Disable feature, our backends do not support it
11356 g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
11357 }
11358
11359 // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
11360 for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
11361 {
11362 IM_UNUSED(mon);
11363 IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
11364 IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
11365 IM_ASSERT(mon.DpiScale > 0.0f && mon.DpiScale < 99.0f && "Monitor DpiScale is invalid."); // Typical correct values would be between 1.0f and 4.0f
11366 }
11367 }
11368}
11369
11370static void ImGui::ErrorCheckEndFrameSanityChecks()
11371{
11372 // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
11373 // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
11374 // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
11375 // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
11376 // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
11377 // while still correctly asserting on mid-frame key press events.
11378 ImGuiContext& g = *GImGui;
11379 const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
11380 IM_UNUSED(g);
11381 IM_UNUSED(key_mods);
11382 IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
11383 IM_UNUSED(key_mods);
11384
11385 IM_ASSERT(g.CurrentWindowStack.Size == 1);
11386 IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
11387}
11388
11389// Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
11390void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
11391{
11392 ImGuiContext& g = *GImGui;
11393 state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
11394 state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
11395 state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
11396 state_out->SizeOfColorStack = (short)g.ColorStack.Size;
11397 state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
11398 state_out->SizeOfFontStack = (short)g.FontStack.Size;
11399 state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
11400 state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
11401 state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
11402 state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
11403 state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
11404}
11405
11406// Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
11407// Called by e.g. EndFrame() but may be called for manual recovery.
11408// Attempt to recover full window stack.
11409void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
11410{
11411 // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
11412 ImGuiContext& g = *GImGui;
11413 while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
11414 {
11415 // Recap:
11416 // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
11417 // - Always call a matching End() for each Begin() call, regardless of its return value!
11418 // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
11419 // - We will fix that in a future major update.
11420 ImGuiWindow* window = g.CurrentWindow;
11421 if (window->Flags & ImGuiWindowFlags_ChildWindow)
11422 {
11423 if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
11424 {
11425 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11426 EndTable();
11427 }
11428 else
11429 {
11430 IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
11431 EndChild();
11432 }
11433 }
11434 else
11435 {
11436 IM_ASSERT_USER_ERROR(0, "Missing End()");
11437 End();
11438 }
11439 }
11440 if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
11441 ErrorRecoveryTryToRecoverWindowState(state_in);
11442}
11443
11444// Called by e.g. End() but may be called for manual recovery.
11445// Read '// Error Handling [BETA]' block in imgui_internal.h for details.
11446// Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
11447void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
11448{
11449 ImGuiContext& g = *GImGui;
11450
11451 while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
11452 {
11453 IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
11454 EndTable();
11455 }
11456
11457 ImGuiWindow* window = g.CurrentWindow;
11458
11459 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
11460 while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
11461 {
11462 IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
11463 EndTabBar();
11464 }
11465 while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
11466 {
11467 IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
11468 EndMultiSelect();
11469 }
11470 if (window->DC.MenuBarAppending) //-V1044
11471 {
11472 IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()");
11473 EndMenuBar();
11474 }
11475 while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
11476 {
11477 IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
11478 TreePop();
11479 }
11480 while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
11481 {
11482 IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
11483 EndGroup();
11484 }
11485 IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
11486 while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
11487 {
11488 IM_ASSERT_USER_ERROR(0, "Missing PopID()");
11489 PopID();
11490 }
11491 while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
11492 {
11493 IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
11494 if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
11495 EndDisabled();
11496 else
11497 {
11498 EndDisabledOverrideReenable();
11499 g.CurrentWindowStack.back().DisabledOverrideReenable = false;
11500 }
11501 }
11502 IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
11503 while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
11504 {
11505 IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
11506 PopStyleColor();
11507 }
11508 while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
11509 {
11510 IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
11511 PopItemFlag();
11512 }
11513 while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
11514 {
11515 IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
11516 PopStyleVar();
11517 }
11518 while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
11519 {
11520 IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
11521 PopFont();
11522 }
11523 while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
11524 {
11525 IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
11526 PopFocusScope();
11527 }
11528 //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
11529}
11530
11531bool ImGui::ErrorLog(const char* msg)
11532{
11533 ImGuiContext& g = *GImGui;
11534
11535 // Output to debug log
11536#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11537 ImGuiWindow* window = g.CurrentWindow;
11538
11539 if (g.IO.ConfigErrorRecoveryEnableDebugLog)
11540 {
11541 if (g.ErrorFirst)
11542 IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
11543 g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
11544 IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
11545 }
11546 g.ErrorFirst = false;
11547
11548 // Output to tooltip
11549 if (g.IO.ConfigErrorRecoveryEnableTooltip)
11550 {
11551 if (g.WithinFrameScope && BeginErrorTooltip())
11552 {
11553 if (g.ErrorCountCurrentFrame < 20)
11554 {
11555 Text(fmt: "In window '%s': %s", window ? window->Name : "NULL", msg);
11556 if (window && (!window->IsFallbackWindow || window->WasActive))
11557 GetForegroundDrawList(window)->AddRect(p_min: window->Pos, p_max: window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
11558 }
11559 if (g.ErrorCountCurrentFrame == 20)
11560 Text(fmt: "(and more errors)");
11561 // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
11562 EndErrorTooltip();
11563 }
11564 g.ErrorCountCurrentFrame++;
11565 }
11566#endif
11567
11568 // Output to callback
11569 if (g.ErrorCallback != NULL)
11570 g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
11571
11572 // Return whether we should assert
11573 return g.IO.ConfigErrorRecoveryEnableAssert;
11574}
11575
11576void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
11577{
11578#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11579 ImGuiContext& g = *GImGui;
11580 if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false)
11581 g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
11582 if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
11583 {
11584 Text(fmt: "Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
11585 BulletText(fmt: "Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
11586 BulletText(fmt: "Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
11587 //BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused.
11588 BulletText(fmt: "Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
11589 Separator();
11590 if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker)
11591 {
11592 Text(fmt: "(Hold CTRL to: use ");
11593 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11594 if (SmallButton(label: "Item Picker"))
11595 DebugStartItemPicker();
11596 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11597 Text(fmt: " to break in item call-stack, or ");
11598 }
11599 else
11600 {
11601 Text(fmt: "(Hold CTRL to ");
11602 }
11603 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11604 if (SmallButton(label: "Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
11605 g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
11606 SameLine(offset_from_start_x: 0.0f, spacing: 0.0f);
11607 Text(fmt: ")");
11608 EndErrorTooltip();
11609 }
11610
11611 if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
11612 {
11613 Separator();
11614 Text(fmt: "(Hold CTRL to:");
11615 SameLine();
11616 if (SmallButton(label: "Enable Asserts"))
11617 g.IO.ConfigErrorRecoveryEnableAssert = true;
11618 //SameLine();
11619 //if (SmallButton("Hide Error Tooltips"))
11620 // g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
11621 SameLine(offset_from_start_x: 0, spacing: 0);
11622 Text(fmt: ")");
11623 EndErrorTooltip();
11624 }
11625#endif
11626}
11627
11628// Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it.
11629bool ImGui::BeginErrorTooltip()
11630{
11631 ImGuiContext& g = *GImGui;
11632 ImGuiWindow* window = FindWindowByName(name: "##Tooltip_Error");
11633 const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
11634 PushStyleColor(idx: ImGuiCol_PopupBg, col: ImLerp(a: g.Style.Colors[ImGuiCol_PopupBg], b: ImVec4(1.0f, 0.0f, 0.0f, 1.0f), t: 0.15f));
11635 if (use_locked_pos)
11636 SetNextWindowPos(pos: g.ErrorTooltipLockedPos);
11637 bool is_visible = Begin(name: "##Tooltip_Error", NULL, flags: ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
11638 PopStyleColor();
11639 if (is_visible && g.CurrentWindow->BeginCount == 1)
11640 {
11641 SeparatorText(label: "MESSAGE FROM DEAR IMGUI");
11642 BringWindowToDisplayFront(window: g.CurrentWindow);
11643 BringWindowToFocusFront(window: g.CurrentWindow);
11644 g.ErrorTooltipLockedPos = GetWindowPos();
11645 }
11646 else if (!is_visible)
11647 {
11648 End();
11649 }
11650 return is_visible;
11651}
11652
11653void ImGui::EndErrorTooltip()
11654{
11655 End();
11656}
11657
11658//-----------------------------------------------------------------------------
11659// [SECTION] ITEM SUBMISSION
11660//-----------------------------------------------------------------------------
11661// - KeepAliveID()
11662// - ItemAdd()
11663//-----------------------------------------------------------------------------
11664
11665// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
11666void ImGui::KeepAliveID(ImGuiID id)
11667{
11668 ImGuiContext& g = *GImGui;
11669 if (g.ActiveId == id)
11670 g.ActiveIdIsAlive = id;
11671 if (g.DeactivatedItemData.ID == id)
11672 g.DeactivatedItemData.IsAlive = true;
11673}
11674
11675// Declare item bounding box for clipping and interaction.
11676// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
11677// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
11678// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
11679IM_MSVC_RUNTIME_CHECKS_OFF
11680bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
11681{
11682 ImGuiContext& g = *GImGui;
11683 ImGuiWindow* window = g.CurrentWindow;
11684
11685 // Set item data
11686 // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
11687 g.LastItemData.ID = id;
11688 g.LastItemData.Rect = bb;
11689 g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
11690 g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
11691 g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
11692 // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
11693
11694 if (id != 0)
11695 {
11696 KeepAliveID(id);
11697
11698 // Directional navigation processing
11699 // Runs prior to clipping early-out
11700 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
11701 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
11702 // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
11703 // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
11704 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
11705 // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
11706 // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
11707 // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
11708 if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
11709 {
11710 // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
11711 window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
11712 if (g.NavId == id || g.NavAnyRequest)
11713 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
11714 if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
11715 NavProcessItem();
11716 }
11717
11718 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
11719 ItemHandleShortcut(id);
11720 }
11721
11722 // Lightweight clear of SetNextItemXXX data.
11723 g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
11724 g.NextItemData.ItemFlags = ImGuiItemFlags_None;
11725
11726#ifdef IMGUI_ENABLE_TEST_ENGINE
11727 if (id != 0)
11728 IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
11729#endif
11730
11731 // Clipping test
11732 // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
11733 // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
11734 const bool is_rect_visible = bb.Overlaps(r: window->ClipRect);
11735 if (!is_rect_visible)
11736 if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
11737 if (!g.ItemUnclipByLog)
11738 return false;
11739
11740 // [DEBUG]
11741#ifndef IMGUI_DISABLE_DEBUG_TOOLS
11742 if (id != 0)
11743 {
11744 if (id == g.DebugLocateId)
11745 DebugLocateItemResolveWithLastItem();
11746
11747 // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
11748 // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
11749 // READ THE FAQ: https://dearimgui.com/faq
11750 IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
11751
11752 // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED.
11753 // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd().
11754#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS
11755 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0)
11756 {
11757 int* p_alive = g.DebugDrawIdConflictsAliveCount.GetIntRef(id, -1); // Could halve lookups if we knew ImGuiStorage can store 64-bit, or by storing FrameCount as 30-bits + highlight as 2-bits. But the point is that we should not pretend that this is fast.
11758 int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1);
11759 if (*p_alive == g.FrameCount)
11760 *p_highlight = g.FrameCount;
11761 *p_alive = g.FrameCount;
11762 if (*p_highlight >= g.FrameCount - 1)
11763 window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f);
11764 }
11765#endif
11766 }
11767 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
11768 //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
11769 // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
11770#endif
11771
11772 if (id != 0 && g.DeactivatedItemData.ID == id)
11773 g.DeactivatedItemData.ElapseFrame = g.FrameCount;
11774
11775 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
11776 if (is_rect_visible)
11777 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
11778 if (IsMouseHoveringRect(r_min: bb.Min, r_max: bb.Max))
11779 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
11780 return true;
11781}
11782IM_MSVC_RUNTIME_CHECKS_RESTORE
11783
11784//-----------------------------------------------------------------------------
11785// [SECTION] LAYOUT
11786//-----------------------------------------------------------------------------
11787// - ItemSize()
11788// - SameLine()
11789// - GetCursorScreenPos()
11790// - SetCursorScreenPos()
11791// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
11792// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
11793// - GetCursorStartPos()
11794// - Indent()
11795// - Unindent()
11796// - SetNextItemWidth()
11797// - PushItemWidth()
11798// - PushMultiItemsWidths()
11799// - PopItemWidth()
11800// - CalcItemWidth()
11801// - CalcItemSize()
11802// - GetTextLineHeight()
11803// - GetTextLineHeightWithSpacing()
11804// - GetFrameHeight()
11805// - GetFrameHeightWithSpacing()
11806// - GetContentRegionMax()
11807// - GetContentRegionAvail(),
11808// - BeginGroup()
11809// - EndGroup()
11810// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11811//-----------------------------------------------------------------------------
11812
11813// Advance cursor given item size for layout.
11814// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11815// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11816// THIS IS IN THE PERFORMANCE CRITICAL PATH.
11817IM_MSVC_RUNTIME_CHECKS_OFF
11818void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11819{
11820 ImGuiContext& g = *GImGui;
11821 ImGuiWindow* window = g.CurrentWindow;
11822 if (window->SkipItems)
11823 return;
11824
11825 // We increase the height in this function to accommodate for baseline offset.
11826 // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11827 // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11828 const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(lhs: 0.0f, rhs: window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11829
11830 const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11831 const float line_height = ImMax(lhs: window->DC.CurrLineSize.y, /*ImMax(*/rhs: window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
11832
11833 // Always align ourselves on pixel boundaries
11834 //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
11835 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11836 window->DC.CursorPosPrevLine.y = line_y1;
11837 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
11838 window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
11839 window->DC.CursorMaxPos.x = ImMax(lhs: window->DC.CursorMaxPos.x, rhs: window->DC.CursorPosPrevLine.x);
11840 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11841 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11842
11843 window->DC.PrevLineSize.y = line_height;
11844 window->DC.CurrLineSize.y = 0.0f;
11845 window->DC.PrevLineTextBaseOffset = ImMax(lhs: window->DC.CurrLineTextBaseOffset, rhs: text_baseline_y);
11846 window->DC.CurrLineTextBaseOffset = 0.0f;
11847 window->DC.IsSameLine = window->DC.IsSetPos = false;
11848
11849 // Horizontal layout mode
11850 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11851 SameLine();
11852}
11853IM_MSVC_RUNTIME_CHECKS_RESTORE
11854
11855// Gets back to previous line and continue with horizontal layout
11856// offset_from_start_x == 0 : follow right after previous item
11857// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11858// spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11859// spacing_w >= 0 : enforce spacing amount
11860void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11861{
11862 ImGuiContext& g = *GImGui;
11863 ImGuiWindow* window = g.CurrentWindow;
11864 if (window->SkipItems)
11865 return;
11866
11867 if (offset_from_start_x != 0.0f)
11868 {
11869 if (spacing_w < 0.0f)
11870 spacing_w = 0.0f;
11871 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11872 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11873 }
11874 else
11875 {
11876 if (spacing_w < 0.0f)
11877 spacing_w = g.Style.ItemSpacing.x;
11878 window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11879 window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11880 }
11881 window->DC.CurrLineSize = window->DC.PrevLineSize;
11882 window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11883 window->DC.IsSameLine = true;
11884}
11885
11886ImVec2 ImGui::GetCursorScreenPos()
11887{
11888 ImGuiWindow* window = GetCurrentWindowRead();
11889 return window->DC.CursorPos;
11890}
11891
11892void ImGui::SetCursorScreenPos(const ImVec2& pos)
11893{
11894 ImGuiWindow* window = GetCurrentWindow();
11895 window->DC.CursorPos = pos;
11896 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11897 window->DC.IsSetPos = true;
11898}
11899
11900// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11901// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
11902ImVec2 ImGui::GetCursorPos()
11903{
11904 ImGuiWindow* window = GetCurrentWindowRead();
11905 return window->DC.CursorPos - window->Pos + window->Scroll;
11906}
11907
11908float ImGui::GetCursorPosX()
11909{
11910 ImGuiWindow* window = GetCurrentWindowRead();
11911 return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11912}
11913
11914float ImGui::GetCursorPosY()
11915{
11916 ImGuiWindow* window = GetCurrentWindowRead();
11917 return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11918}
11919
11920void ImGui::SetCursorPos(const ImVec2& local_pos)
11921{
11922 ImGuiWindow* window = GetCurrentWindow();
11923 window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11924 //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11925 window->DC.IsSetPos = true;
11926}
11927
11928void ImGui::SetCursorPosX(float x)
11929{
11930 ImGuiWindow* window = GetCurrentWindow();
11931 window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11932 //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11933 window->DC.IsSetPos = true;
11934}
11935
11936void ImGui::SetCursorPosY(float y)
11937{
11938 ImGuiWindow* window = GetCurrentWindow();
11939 window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11940 //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11941 window->DC.IsSetPos = true;
11942}
11943
11944ImVec2 ImGui::GetCursorStartPos()
11945{
11946 ImGuiWindow* window = GetCurrentWindowRead();
11947 return window->DC.CursorStartPos - window->Pos;
11948}
11949
11950void ImGui::Indent(float indent_w)
11951{
11952 ImGuiContext& g = *GImGui;
11953 ImGuiWindow* window = GetCurrentWindow();
11954 window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11955 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11956}
11957
11958void ImGui::Unindent(float indent_w)
11959{
11960 ImGuiContext& g = *GImGui;
11961 ImGuiWindow* window = GetCurrentWindow();
11962 window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11963 window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11964}
11965
11966// Affect large frame+labels widgets only.
11967void ImGui::SetNextItemWidth(float item_width)
11968{
11969 ImGuiContext& g = *GImGui;
11970 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
11971 g.NextItemData.Width = item_width;
11972}
11973
11974// FIXME: Remove the == 0.0f behavior?
11975void ImGui::PushItemWidth(float item_width)
11976{
11977 ImGuiContext& g = *GImGui;
11978 ImGuiWindow* window = g.CurrentWindow;
11979 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
11980 window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11981 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
11982}
11983
11984void ImGui::PushMultiItemsWidths(int components, float w_full)
11985{
11986 ImGuiContext& g = *GImGui;
11987 ImGuiWindow* window = g.CurrentWindow;
11988 IM_ASSERT(components > 0);
11989 const ImGuiStyle& style = g.Style;
11990 window->DC.ItemWidthStack.push_back(v: window->DC.ItemWidth); // Backup current width
11991 float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11992 float prev_split = w_items;
11993 for (int i = components - 1; i > 0; i--)
11994 {
11995 float next_split = IM_TRUNC(w_items * i / components);
11996 window->DC.ItemWidthStack.push_back(v: ImMax(lhs: prev_split - next_split, rhs: 1.0f));
11997 prev_split = next_split;
11998 }
11999 window->DC.ItemWidth = ImMax(lhs: prev_split, rhs: 1.0f);
12000 g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
12001}
12002
12003void ImGui::PopItemWidth()
12004{
12005 ImGuiContext& g = *GImGui;
12006 ImGuiWindow* window = g.CurrentWindow;
12007 if (window->DC.ItemWidthStack.Size <= 0)
12008 {
12009 IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
12010 return;
12011 }
12012 window->DC.ItemWidth = window->DC.ItemWidthStack.back();
12013 window->DC.ItemWidthStack.pop_back();
12014}
12015
12016// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
12017// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
12018float ImGui::CalcItemWidth()
12019{
12020 ImGuiContext& g = *GImGui;
12021 ImGuiWindow* window = g.CurrentWindow;
12022 float w;
12023 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
12024 w = g.NextItemData.Width;
12025 else
12026 w = window->DC.ItemWidth;
12027 if (w < 0.0f)
12028 {
12029 float region_avail_x = GetContentRegionAvail().x;
12030 w = ImMax(lhs: 1.0f, rhs: region_avail_x + w);
12031 }
12032 w = IM_TRUNC(w);
12033 return w;
12034}
12035
12036// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
12037// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
12038// Note that only CalcItemWidth() is publicly exposed.
12039// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
12040ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
12041{
12042 ImVec2 avail;
12043 if (size.x < 0.0f || size.y < 0.0f)
12044 avail = GetContentRegionAvail();
12045
12046 if (size.x == 0.0f)
12047 size.x = default_w;
12048 else if (size.x < 0.0f)
12049 size.x = ImMax(lhs: 4.0f, rhs: avail.x + size.x); // <-- size.x is negative here so we are subtracting
12050
12051 if (size.y == 0.0f)
12052 size.y = default_h;
12053 else if (size.y < 0.0f)
12054 size.y = ImMax(lhs: 4.0f, rhs: avail.y + size.y); // <-- size.y is negative here so we are subtracting
12055
12056 return size;
12057}
12058
12059float ImGui::GetTextLineHeight()
12060{
12061 ImGuiContext& g = *GImGui;
12062 return g.FontSize;
12063}
12064
12065float ImGui::GetTextLineHeightWithSpacing()
12066{
12067 ImGuiContext& g = *GImGui;
12068 return g.FontSize + g.Style.ItemSpacing.y;
12069}
12070
12071float ImGui::GetFrameHeight()
12072{
12073 ImGuiContext& g = *GImGui;
12074 return g.FontSize + g.Style.FramePadding.y * 2.0f;
12075}
12076
12077float ImGui::GetFrameHeightWithSpacing()
12078{
12079 ImGuiContext& g = *GImGui;
12080 return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
12081}
12082
12083ImVec2 ImGui::GetContentRegionAvail()
12084{
12085 ImGuiContext& g = *GImGui;
12086 ImGuiWindow* window = g.CurrentWindow;
12087 ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
12088 return mx - window->DC.CursorPos;
12089}
12090
12091#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
12092
12093// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
12094// They are bizarre local-coordinates which don't play well with scrolling.
12095ImVec2 ImGui::GetContentRegionMax()
12096{
12097 return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
12098}
12099
12100ImVec2 ImGui::GetWindowContentRegionMin()
12101{
12102 ImGuiWindow* window = GImGui->CurrentWindow;
12103 return window->ContentRegionRect.Min - window->Pos;
12104}
12105
12106ImVec2 ImGui::GetWindowContentRegionMax()
12107{
12108 ImGuiWindow* window = GImGui->CurrentWindow;
12109 return window->ContentRegionRect.Max - window->Pos;
12110}
12111#endif
12112
12113// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
12114// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
12115// FIXME-OPT: Could we safely early out on ->SkipItems?
12116void ImGui::BeginGroup()
12117{
12118 ImGuiContext& g = *GImGui;
12119 ImGuiWindow* window = g.CurrentWindow;
12120
12121 g.GroupStack.resize(new_size: g.GroupStack.Size + 1);
12122 ImGuiGroupData& group_data = g.GroupStack.back();
12123 group_data.WindowID = window->ID;
12124 group_data.BackupCursorPos = window->DC.CursorPos;
12125 group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
12126 group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
12127 group_data.BackupIndent = window->DC.Indent;
12128 group_data.BackupGroupOffset = window->DC.GroupOffset;
12129 group_data.BackupCurrLineSize = window->DC.CurrLineSize;
12130 group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
12131 group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
12132 group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
12133 group_data.BackupIsSameLine = window->DC.IsSameLine;
12134 group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive;
12135 group_data.EmitItem = true;
12136
12137 window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
12138 window->DC.Indent = window->DC.GroupOffset;
12139 window->DC.CursorMaxPos = window->DC.CursorPos;
12140 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
12141 if (g.LogEnabled)
12142 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12143}
12144
12145void ImGui::EndGroup()
12146{
12147 ImGuiContext& g = *GImGui;
12148 ImGuiWindow* window = g.CurrentWindow;
12149 IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
12150
12151 ImGuiGroupData& group_data = g.GroupStack.back();
12152 IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
12153
12154 if (window->DC.IsSetPos)
12155 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
12156
12157 // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
12158 ImRect group_bb(group_data.BackupCursorPos, ImMax(lhs: ImMax(lhs: window->DC.CursorMaxPos, rhs: g.LastItemData.Rect.Max), rhs: group_data.BackupCursorPos));
12159 window->DC.CursorPos = group_data.BackupCursorPos;
12160 window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
12161 window->DC.CursorMaxPos = ImMax(lhs: group_data.BackupCursorMaxPos, rhs: group_bb.Max);
12162 window->DC.Indent = group_data.BackupIndent;
12163 window->DC.GroupOffset = group_data.BackupGroupOffset;
12164 window->DC.CurrLineSize = group_data.BackupCurrLineSize;
12165 window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
12166 window->DC.IsSameLine = group_data.BackupIsSameLine;
12167 if (g.LogEnabled)
12168 g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
12169
12170 if (!group_data.EmitItem)
12171 {
12172 g.GroupStack.pop_back();
12173 return;
12174 }
12175
12176 window->DC.CurrLineTextBaseOffset = ImMax(lhs: window->DC.PrevLineTextBaseOffset, rhs: group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
12177 ItemSize(size: group_bb.GetSize());
12178 ItemAdd(bb: group_bb, id: 0, NULL, extra_flags: ImGuiItemFlags_NoTabStop);
12179
12180 // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
12181 // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
12182 // Also if you grep for LastItemId you'll notice it is only used in that context.
12183 // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
12184 const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
12185 const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true);
12186 if (group_contains_curr_active_id)
12187 g.LastItemData.ID = g.ActiveId;
12188 else if (group_contains_deactivated_id)
12189 g.LastItemData.ID = g.DeactivatedItemData.ID;
12190 g.LastItemData.Rect = group_bb;
12191
12192 // Forward Hovered flag
12193 const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
12194 if (group_contains_curr_hovered_id)
12195 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
12196
12197 // Forward Edited flag
12198 if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
12199 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
12200
12201 // Forward Deactivated flag
12202 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
12203 if (group_contains_deactivated_id)
12204 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
12205
12206 g.GroupStack.pop_back();
12207 if (g.DebugShowGroupRects)
12208 window->DrawList->AddRect(p_min: group_bb.Min, p_max: group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
12209}
12210
12211
12212//-----------------------------------------------------------------------------
12213// [SECTION] SCROLLING
12214//-----------------------------------------------------------------------------
12215
12216// Helper to snap on edges when aiming at an item very close to the edge,
12217// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
12218// When we refactor the scrolling API this may be configurable with a flag?
12219// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
12220static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
12221{
12222 if (target <= snap_min + snap_threshold)
12223 return ImLerp(a: snap_min, b: target, t: center_ratio);
12224 if (target >= snap_max - snap_threshold)
12225 return ImLerp(a: target, b: snap_max, t: center_ratio);
12226 return target;
12227}
12228
12229static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
12230{
12231 ImVec2 scroll = window->Scroll;
12232 ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
12233 for (int axis = 0; axis < 2; axis++)
12234 {
12235 if (window->ScrollTarget[axis] < FLT_MAX)
12236 {
12237 float center_ratio = window->ScrollTargetCenterRatio[axis];
12238 float scroll_target = window->ScrollTarget[axis];
12239 if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
12240 {
12241 float snap_min = 0.0f;
12242 float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
12243 scroll_target = CalcScrollEdgeSnap(target: scroll_target, snap_min, snap_max, snap_threshold: window->ScrollTargetEdgeSnapDist[axis], center_ratio);
12244 }
12245 scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
12246 }
12247 scroll[axis] = ImRound64(f: ImMax(lhs: scroll[axis], rhs: 0.0f));
12248 if (!window->Collapsed && !window->SkipItems)
12249 scroll[axis] = ImMin(lhs: scroll[axis], rhs: window->ScrollMax[axis]);
12250 }
12251 return scroll;
12252}
12253
12254void ImGui::ScrollToItem(ImGuiScrollFlags flags)
12255{
12256 ImGuiContext& g = *GImGui;
12257 ImGuiWindow* window = g.CurrentWindow;
12258 ScrollToRectEx(window, rect: g.LastItemData.NavRect, flags);
12259}
12260
12261void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12262{
12263 ScrollToRectEx(window, rect: item_rect, flags);
12264}
12265
12266// Scroll to keep newly navigated item fully into view
12267ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
12268{
12269 ImGuiContext& g = *GImGui;
12270 ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
12271 scroll_rect.Min.x = ImMin(lhs: scroll_rect.Min.x + window->DecoInnerSizeX1, rhs: scroll_rect.Max.x);
12272 scroll_rect.Min.y = ImMin(lhs: scroll_rect.Min.y + window->DecoInnerSizeY1, rhs: scroll_rect.Max.y);
12273 //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
12274 //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
12275
12276 // Check that only one behavior is selected per axis
12277 IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
12278 IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
12279
12280 // Defaults
12281 ImGuiScrollFlags in_flags = flags;
12282 if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
12283 flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
12284 if ((flags & ImGuiScrollFlags_MaskY_) == 0)
12285 flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
12286
12287 const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
12288 const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
12289 const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
12290 const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
12291
12292 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
12293 {
12294 if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
12295 SetScrollFromPosX(window, local_x: item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 0.0f);
12296 else if (item_rect.Max.x >= scroll_rect.Max.x)
12297 SetScrollFromPosX(window, local_x: item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, center_x_ratio: 1.0f);
12298 }
12299 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
12300 {
12301 if (can_be_fully_visible_x)
12302 SetScrollFromPosX(window, local_x: ImTrunc(f: (item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, center_x_ratio: 0.5f);
12303 else
12304 SetScrollFromPosX(window, local_x: item_rect.Min.x - window->Pos.x, center_x_ratio: 0.0f);
12305 }
12306
12307 if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
12308 {
12309 if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
12310 SetScrollFromPosY(window, local_y: item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 0.0f);
12311 else if (item_rect.Max.y >= scroll_rect.Max.y)
12312 SetScrollFromPosY(window, local_y: item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, center_y_ratio: 1.0f);
12313 }
12314 else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
12315 {
12316 if (can_be_fully_visible_y)
12317 SetScrollFromPosY(window, local_y: ImTrunc(f: (item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, center_y_ratio: 0.5f);
12318 else
12319 SetScrollFromPosY(window, local_y: item_rect.Min.y - window->Pos.y, center_y_ratio: 0.0f);
12320 }
12321
12322 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12323 ImVec2 delta_scroll = next_scroll - window->Scroll;
12324
12325 // Also scroll parent window to keep us into view if necessary
12326 if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
12327 {
12328 // FIXME-SCROLL: May be an option?
12329 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
12330 in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
12331 if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
12332 in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
12333 delta_scroll += ScrollToRectEx(window: window->ParentWindow, item_rect: ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), flags: in_flags);
12334 }
12335
12336 return delta_scroll;
12337}
12338
12339float ImGui::GetScrollX()
12340{
12341 ImGuiWindow* window = GImGui->CurrentWindow;
12342 return window->Scroll.x;
12343}
12344
12345float ImGui::GetScrollY()
12346{
12347 ImGuiWindow* window = GImGui->CurrentWindow;
12348 return window->Scroll.y;
12349}
12350
12351float ImGui::GetScrollMaxX()
12352{
12353 ImGuiWindow* window = GImGui->CurrentWindow;
12354 return window->ScrollMax.x;
12355}
12356
12357float ImGui::GetScrollMaxY()
12358{
12359 ImGuiWindow* window = GImGui->CurrentWindow;
12360 return window->ScrollMax.y;
12361}
12362
12363void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
12364{
12365 window->ScrollTarget.x = scroll_x;
12366 window->ScrollTargetCenterRatio.x = 0.0f;
12367 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12368}
12369
12370void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
12371{
12372 window->ScrollTarget.y = scroll_y;
12373 window->ScrollTargetCenterRatio.y = 0.0f;
12374 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12375}
12376
12377void ImGui::SetScrollX(float scroll_x)
12378{
12379 ImGuiContext& g = *GImGui;
12380 SetScrollX(window: g.CurrentWindow, scroll_x);
12381}
12382
12383void ImGui::SetScrollY(float scroll_y)
12384{
12385 ImGuiContext& g = *GImGui;
12386 SetScrollY(window: g.CurrentWindow, scroll_y);
12387}
12388
12389// Note that a local position will vary depending on initial scroll value,
12390// This is a little bit confusing so bear with us:
12391// - local_pos = (absolution_pos - window->Pos)
12392// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
12393// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
12394// - They mostly exist because of legacy API.
12395// Following the rules above, when trying to work with scrolling code, consider that:
12396// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
12397// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
12398// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
12399void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
12400{
12401 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
12402 window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
12403 window->ScrollTargetCenterRatio.x = center_x_ratio;
12404 window->ScrollTargetEdgeSnapDist.x = 0.0f;
12405}
12406
12407void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
12408{
12409 IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
12410 window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
12411 window->ScrollTargetCenterRatio.y = center_y_ratio;
12412 window->ScrollTargetEdgeSnapDist.y = 0.0f;
12413}
12414
12415void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
12416{
12417 ImGuiContext& g = *GImGui;
12418 SetScrollFromPosX(window: g.CurrentWindow, local_x, center_x_ratio);
12419}
12420
12421void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
12422{
12423 ImGuiContext& g = *GImGui;
12424 SetScrollFromPosY(window: g.CurrentWindow, local_y, center_y_ratio);
12425}
12426
12427// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
12428void ImGui::SetScrollHereX(float center_x_ratio)
12429{
12430 ImGuiContext& g = *GImGui;
12431 ImGuiWindow* window = g.CurrentWindow;
12432 float spacing_x = ImMax(lhs: window->WindowPadding.x, rhs: g.Style.ItemSpacing.x);
12433 float target_pos_x = ImLerp(a: g.LastItemData.Rect.Min.x - spacing_x, b: g.LastItemData.Rect.Max.x + spacing_x, t: center_x_ratio);
12434 SetScrollFromPosX(window, local_x: target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
12435
12436 // Tweak: snap on edges when aiming at an item very close to the edge
12437 window->ScrollTargetEdgeSnapDist.x = ImMax(lhs: 0.0f, rhs: window->WindowPadding.x - spacing_x);
12438}
12439
12440// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
12441void ImGui::SetScrollHereY(float center_y_ratio)
12442{
12443 ImGuiContext& g = *GImGui;
12444 ImGuiWindow* window = g.CurrentWindow;
12445 float spacing_y = ImMax(lhs: window->WindowPadding.y, rhs: g.Style.ItemSpacing.y);
12446 float target_pos_y = ImLerp(a: window->DC.CursorPosPrevLine.y - spacing_y, b: window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, t: center_y_ratio);
12447 SetScrollFromPosY(window, local_y: target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
12448
12449 // Tweak: snap on edges when aiming at an item very close to the edge
12450 window->ScrollTargetEdgeSnapDist.y = ImMax(lhs: 0.0f, rhs: window->WindowPadding.y - spacing_y);
12451}
12452
12453//-----------------------------------------------------------------------------
12454// [SECTION] TOOLTIPS
12455//-----------------------------------------------------------------------------
12456
12457bool ImGui::BeginTooltip()
12458{
12459 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
12460}
12461
12462bool ImGui::BeginItemTooltip()
12463{
12464 if (!IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
12465 return false;
12466 return BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_None, extra_window_flags: ImGuiWindowFlags_None);
12467}
12468
12469bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
12470{
12471 ImGuiContext& g = *GImGui;
12472
12473 const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
12474 if (is_dragdrop_tooltip)
12475 {
12476 // Drag and Drop tooltips are positioning differently than other tooltips:
12477 // - offset visibility to increase visibility around mouse.
12478 // - never clamp within outer viewport boundary.
12479 // We call SetNextWindowPos() to enforce position and disable clamping.
12480 // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones).
12481 //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
12482 const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
12483 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12484 {
12485 ImVec2 tooltip_pos = is_touchscreen ? (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale) : (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale);
12486 ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
12487 SetNextWindowPos(pos: tooltip_pos, cond: ImGuiCond_None, pivot: tooltip_pivot);
12488 }
12489
12490 SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
12491 //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
12492 tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
12493 }
12494
12495 const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
12496 char window_name[32];
12497 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: window_name_template, g.TooltipOverrideCount);
12498 if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active)
12499 {
12500 // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
12501 //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
12502 SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
12503 ImFormatString(buf: window_name, IM_ARRAYSIZE(window_name), fmt: window_name_template, ++g.TooltipOverrideCount);
12504 }
12505
12506 ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
12507 Begin(name: window_name, NULL, flags: flags | extra_window_flags);
12508 // 2023-03-09: Added bool return value to the API, but currently always returning true.
12509 // If this ever returns false we need to update BeginDragDropSource() accordingly.
12510 //if (!ret)
12511 // End();
12512 //return ret;
12513 return true;
12514}
12515
12516void ImGui::EndTooltip()
12517{
12518 IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
12519 End();
12520}
12521
12522void ImGui::SetTooltip(const char* fmt, ...)
12523{
12524 va_list args;
12525 va_start(args, fmt);
12526 SetTooltipV(fmt, args);
12527 va_end(args);
12528}
12529
12530void ImGui::SetTooltipV(const char* fmt, va_list args)
12531{
12532 if (!BeginTooltipEx(tooltip_flags: ImGuiTooltipFlags_OverridePrevious, extra_window_flags: ImGuiWindowFlags_None))
12533 return;
12534 TextV(fmt, args);
12535 EndTooltip();
12536}
12537
12538// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
12539// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
12540void ImGui::SetItemTooltip(const char* fmt, ...)
12541{
12542 va_list args;
12543 va_start(args, fmt);
12544 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
12545 SetTooltipV(fmt, args);
12546 va_end(args);
12547}
12548
12549void ImGui::SetItemTooltipV(const char* fmt, va_list args)
12550{
12551 if (IsItemHovered(flags: ImGuiHoveredFlags_ForTooltip))
12552 SetTooltipV(fmt, args);
12553}
12554
12555
12556//-----------------------------------------------------------------------------
12557// [SECTION] POPUPS
12558//-----------------------------------------------------------------------------
12559
12560// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
12561bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
12562{
12563 ImGuiContext& g = *GImGui;
12564 if (popup_flags & ImGuiPopupFlags_AnyPopupId)
12565 {
12566 // Return true if any popup is open at the current BeginPopup() level of the popup stack
12567 // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
12568 IM_ASSERT(id == 0);
12569 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12570 return g.OpenPopupStack.Size > 0;
12571 else
12572 return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
12573 }
12574 else
12575 {
12576 if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
12577 {
12578 // Return true if the popup is open anywhere in the popup stack
12579 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12580 if (popup_data.PopupId == id)
12581 return true;
12582 return false;
12583 }
12584 else
12585 {
12586 // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
12587 return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
12588 }
12589 }
12590}
12591
12592bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
12593{
12594 ImGuiContext& g = *GImGui;
12595 ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str: str_id);
12596 if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
12597 IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
12598 return IsPopupOpen(id, popup_flags);
12599}
12600
12601// Also see FindBlockingModal(NULL)
12602ImGuiWindow* ImGui::GetTopMostPopupModal()
12603{
12604 ImGuiContext& g = *GImGui;
12605 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12606 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12607 if (popup->Flags & ImGuiWindowFlags_Modal)
12608 return popup;
12609 return NULL;
12610}
12611
12612// See Demo->Stacked Modal to confirm what this is for.
12613ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
12614{
12615 ImGuiContext& g = *GImGui;
12616 for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
12617 if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
12618 if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(window: popup))
12619 return popup;
12620 return NULL;
12621}
12622
12623
12624// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
12625// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
12626// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
12627// - WindowA // FindBlockingModal() returns Modal1
12628// - WindowB // .. returns Modal1
12629// - Modal1 // .. returns Modal2
12630// - WindowC // .. returns Modal2
12631// - WindowD // .. returns Modal2
12632// - Modal2 // .. returns Modal2
12633// - WindowE // .. returns NULL
12634// Notes:
12635// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
12636// Only difference is here we check for ->Active/WasActive but it may be unnecessary.
12637ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
12638{
12639 ImGuiContext& g = *GImGui;
12640 if (g.OpenPopupStack.Size <= 0)
12641 return NULL;
12642
12643 // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
12644 for (ImGuiPopupData& popup_data : g.OpenPopupStack)
12645 {
12646 ImGuiWindow* popup_window = popup_data.Window;
12647 if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
12648 continue;
12649 if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
12650 continue;
12651 if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
12652 return popup_window;
12653 if (IsWindowWithinBeginStackOf(window, potential_parent: popup_window)) // Window may be over modal
12654 continue;
12655 return popup_window; // Place window right below first block modal
12656 }
12657 return NULL;
12658}
12659
12660void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
12661{
12662 ImGuiContext& g = *GImGui;
12663 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
12664 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
12665 OpenPopupEx(id, popup_flags);
12666}
12667
12668void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
12669{
12670 OpenPopupEx(id, popup_flags);
12671}
12672
12673// Mark popup as open (toggle toward open state).
12674// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
12675// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
12676// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
12677void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
12678{
12679 ImGuiContext& g = *GImGui;
12680 ImGuiWindow* parent_window = g.CurrentWindow;
12681 const int current_stack_size = g.BeginPopupStack.Size;
12682
12683 if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
12684 if (IsPopupOpen(id: (ImGuiID)0, popup_flags: ImGuiPopupFlags_AnyPopupId))
12685 return;
12686
12687 ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
12688 popup_ref.PopupId = id;
12689 popup_ref.Window = NULL;
12690 popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
12691 popup_ref.OpenFrameCount = g.FrameCount;
12692 popup_ref.OpenParentId = parent_window->IDStack.back();
12693 popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
12694 popup_ref.OpenMousePos = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
12695
12696 IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
12697 if (g.OpenPopupStack.Size < current_stack_size + 1)
12698 {
12699 g.OpenPopupStack.push_back(v: popup_ref);
12700 }
12701 else
12702 {
12703 // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
12704 // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
12705 // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
12706 // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
12707 bool keep_existing = false;
12708 if (g.OpenPopupStack[current_stack_size].PopupId == id)
12709 if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
12710 keep_existing = true;
12711 if (keep_existing)
12712 {
12713 // No reopen
12714 g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
12715 }
12716 else
12717 {
12718 // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
12719 ClosePopupToLevel(remaining: current_stack_size, restore_focus_to_window_under_popup: true);
12720 g.OpenPopupStack.push_back(v: popup_ref);
12721 }
12722
12723 // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
12724 // This is equivalent to what ClosePopupToLevel() does.
12725 //if (g.OpenPopupStack[current_stack_size].PopupId == id)
12726 // FocusWindow(parent_window);
12727 }
12728}
12729
12730// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
12731// This function closes any popups that are over 'ref_window'.
12732void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
12733{
12734 ImGuiContext& g = *GImGui;
12735 if (g.OpenPopupStack.Size == 0)
12736 return;
12737
12738 // Don't close our own child popup windows.
12739 //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
12740 int popup_count_to_keep = 0;
12741 if (ref_window)
12742 {
12743 // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
12744 for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
12745 {
12746 ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
12747 if (!popup.Window)
12748 continue;
12749 IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
12750
12751 // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
12752 // - Clicking/Focusing Window2 won't close Popup1:
12753 // Window -> Popup1 -> Window2(Ref)
12754 // - Clicking/focusing Popup1 will close Popup2 and Popup3:
12755 // Window -> Popup1(Ref) -> Popup2 -> Popup3
12756 // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
12757 // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
12758 // We step through every popup from bottom to top to validate their position relative to reference window.
12759 bool ref_window_is_descendent_of_popup = false;
12760 for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
12761 if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
12762 //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
12763 if (IsWindowWithinBeginStackOf(window: ref_window, potential_parent: popup_window))
12764 {
12765 ref_window_is_descendent_of_popup = true;
12766 break;
12767 }
12768 if (!ref_window_is_descendent_of_popup)
12769 break;
12770 }
12771 }
12772 if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
12773 {
12774 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
12775 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup);
12776 }
12777}
12778
12779void ImGui::ClosePopupsExceptModals()
12780{
12781 ImGuiContext& g = *GImGui;
12782
12783 int popup_count_to_keep;
12784 for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
12785 {
12786 ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
12787 if (!window || (window->Flags & ImGuiWindowFlags_Modal))
12788 break;
12789 }
12790 if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
12791 ClosePopupToLevel(remaining: popup_count_to_keep, restore_focus_to_window_under_popup: true);
12792}
12793
12794void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
12795{
12796 ImGuiContext& g = *GImGui;
12797 IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
12798 IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
12799 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)
12800 for (int n = remaining; n < g.OpenPopupStack.Size; n++)
12801 IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"\n", g.OpenPopupStack[n].PopupId, g.OpenPopupStack[n].Window ? g.OpenPopupStack[n].Window->Name : NULL);
12802
12803 // Trim open popup stack
12804 ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
12805 g.OpenPopupStack.resize(new_size: remaining);
12806
12807 // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
12808 if (restore_focus_to_window_under_popup && prev_popup.Window)
12809 {
12810 ImGuiWindow* popup_window = prev_popup.Window;
12811 ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
12812 if (focus_window && !focus_window->WasActive)
12813 FocusTopMostWindowUnderOne(under_this_window: popup_window, NULL, NULL, flags: ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
12814 else
12815 FocusWindow(window: focus_window, flags: (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
12816 }
12817}
12818
12819// Close the popup we have begin-ed into.
12820void ImGui::CloseCurrentPopup()
12821{
12822 ImGuiContext& g = *GImGui;
12823 int popup_idx = g.BeginPopupStack.Size - 1;
12824 if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
12825 return;
12826
12827 // Closing a menu closes its top-most parent popup (unless a modal)
12828 while (popup_idx > 0)
12829 {
12830 ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
12831 ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
12832 bool close_parent = false;
12833 if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
12834 if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
12835 close_parent = true;
12836 if (!close_parent)
12837 break;
12838 popup_idx--;
12839 }
12840 IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
12841 ClosePopupToLevel(remaining: popup_idx, restore_focus_to_window_under_popup: true);
12842
12843 // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
12844 // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
12845 // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
12846 if (ImGuiWindow* window = g.NavWindow)
12847 window->DC.NavHideHighlightOneFrame = true;
12848}
12849
12850// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
12851bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
12852{
12853 ImGuiContext& g = *GImGui;
12854 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
12855 {
12856 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12857 return false;
12858 }
12859
12860 char name[20];
12861 IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx()
12862 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "##Popup_%08x", id); // No recycling, so we can close/open during the same frame
12863
12864 bool is_open = Begin(name, NULL, flags: extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
12865 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12866 EndPopup();
12867 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12868 return is_open;
12869}
12870
12871bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags)
12872{
12873 ImGuiContext& g = *GImGui;
12874 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
12875 {
12876 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12877 return false;
12878 }
12879
12880 char name[128];
12881 IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu);
12882 ImFormatString(buf: name, IM_ARRAYSIZE(name), fmt: "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth
12883 bool is_open = Begin(name, NULL, flags: extra_window_flags | ImGuiWindowFlags_Popup);
12884 if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12885 EndPopup();
12886 //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12887 return is_open;
12888}
12889
12890bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12891{
12892 ImGuiContext& g = *GImGui;
12893 if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12894 {
12895 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12896 return false;
12897 }
12898 flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12899 ImGuiID id = g.CurrentWindow->GetID(str: str_id);
12900 return BeginPopupEx(id, extra_window_flags: flags);
12901}
12902
12903// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12904// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12905// - *p_open set back to false in BeginPopupModal() when popup is not open.
12906// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12907bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12908{
12909 ImGuiContext& g = *GImGui;
12910 ImGuiWindow* window = g.CurrentWindow;
12911 const ImGuiID id = window->GetID(str: name);
12912 if (!IsPopupOpen(id, popup_flags: ImGuiPopupFlags_None))
12913 {
12914 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12915 if (p_open && *p_open)
12916 *p_open = false;
12917 return false;
12918 }
12919
12920 // Center modal windows by default for increased visibility
12921 // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12922 // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12923 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0)
12924 {
12925 const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12926 SetNextWindowPos(pos: viewport->GetCenter(), cond: ImGuiCond_FirstUseEver, pivot: ImVec2(0.5f, 0.5f));
12927 }
12928
12929 flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12930 const bool is_open = Begin(name, p_open, flags);
12931 if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12932 {
12933 EndPopup();
12934 if (is_open)
12935 ClosePopupToLevel(remaining: g.BeginPopupStack.Size, restore_focus_to_window_under_popup: true);
12936 return false;
12937 }
12938 return is_open;
12939}
12940
12941void ImGui::EndPopup()
12942{
12943 ImGuiContext& g = *GImGui;
12944 ImGuiWindow* window = g.CurrentWindow;
12945 if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0)
12946 {
12947 IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!");
12948 return;
12949 }
12950
12951 // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
12952 if (g.NavWindow == window)
12953 NavMoveRequestTryWrapping(window, move_flags: ImGuiNavMoveFlags_LoopY);
12954
12955 // Child-popups don't need to be laid out
12956 const ImGuiID backup_within_end_child_id = g.WithinEndChildID;
12957 if (window->Flags & ImGuiWindowFlags_ChildWindow)
12958 g.WithinEndChildID = window->ID;
12959 End();
12960 g.WithinEndChildID = backup_within_end_child_id;
12961}
12962
12963// Helper to open a popup if mouse button is released over the item
12964// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12965void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12966{
12967 ImGuiContext& g = *GImGui;
12968 ImGuiWindow* window = g.CurrentWindow;
12969 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12970 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12971 {
12972 ImGuiID id = str_id ? window->GetID(str: str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12973 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12974 OpenPopupEx(id, popup_flags);
12975 }
12976}
12977
12978// This is a helper to handle the simplest case of associating one named popup to one given widget.
12979// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12980// - To create a popup with a specific identifier, pass it in str_id.
12981// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12982// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12983// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12984// This is essentially the same as:
12985// id = str_id ? GetID(str_id) : GetItemID();
12986// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12987// return BeginPopup(id);
12988// Which is essentially the same as:
12989// id = str_id ? GetID(str_id) : GetItemID();
12990// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12991// OpenPopup(id);
12992// return BeginPopup(id);
12993// The main difference being that this is tweaked to avoid computing the ID twice.
12994bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12995{
12996 ImGuiContext& g = *GImGui;
12997 ImGuiWindow* window = g.CurrentWindow;
12998 if (window->SkipItems)
12999 return false;
13000 ImGuiID id = str_id ? window->GetID(str: str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
13001 IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
13002 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13003 if (IsMouseReleased(button: mouse_button) && IsItemHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13004 OpenPopupEx(id, popup_flags);
13005 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13006}
13007
13008bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
13009{
13010 ImGuiContext& g = *GImGui;
13011 ImGuiWindow* window = g.CurrentWindow;
13012 if (!str_id)
13013 str_id = "window_context";
13014 ImGuiID id = window->GetID(str: str_id);
13015 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13016 if (IsMouseReleased(button: mouse_button) && IsWindowHovered(flags: ImGuiHoveredFlags_AllowWhenBlockedByPopup))
13017 if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
13018 OpenPopupEx(id, popup_flags);
13019 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13020}
13021
13022bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
13023{
13024 ImGuiContext& g = *GImGui;
13025 ImGuiWindow* window = g.CurrentWindow;
13026 if (!str_id)
13027 str_id = "void_context";
13028 ImGuiID id = window->GetID(str: str_id);
13029 int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
13030 if (IsMouseReleased(button: mouse_button) && !IsWindowHovered(flags: ImGuiHoveredFlags_AnyWindow))
13031 if (GetTopMostPopupModal() == NULL)
13032 OpenPopupEx(id, popup_flags);
13033 return BeginPopupEx(id, extra_window_flags: ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
13034}
13035
13036// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
13037// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
13038// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
13039// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
13040// this allows us to have tooltips/popups displayed out of the parent viewport.)
13041ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
13042{
13043 ImVec2 base_pos_clamped = ImClamp(v: ref_pos, mn: r_outer.Min, mx: r_outer.Max - size);
13044 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
13045 //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
13046
13047 // Combo Box policy (we want a connecting edge)
13048 if (policy == ImGuiPopupPositionPolicy_ComboBox)
13049 {
13050 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
13051 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13052 {
13053 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13054 if (n != -1 && dir == *last_dir) // Already tried this direction?
13055 continue;
13056 ImVec2 pos;
13057 if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
13058 if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
13059 if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
13060 if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
13061 if (!r_outer.Contains(r: ImRect(pos, pos + size)))
13062 continue;
13063 *last_dir = dir;
13064 return pos;
13065 }
13066 }
13067
13068 // Tooltip and Default popup policy
13069 // (Always first try the direction we used on the last frame, if any)
13070 if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
13071 {
13072 const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
13073 for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
13074 {
13075 const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
13076 if (n != -1 && dir == *last_dir) // Already tried this direction?
13077 continue;
13078
13079 const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
13080 const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
13081
13082 // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
13083 if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
13084 continue;
13085 if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
13086 continue;
13087
13088 ImVec2 pos;
13089 pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
13090 pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
13091
13092 // Clamp top-left corner of popup
13093 pos.x = ImMax(lhs: pos.x, rhs: r_outer.Min.x);
13094 pos.y = ImMax(lhs: pos.y, rhs: r_outer.Min.y);
13095
13096 *last_dir = dir;
13097 return pos;
13098 }
13099 }
13100
13101 // Fallback when not enough room:
13102 *last_dir = ImGuiDir_None;
13103
13104 // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
13105 if (policy == ImGuiPopupPositionPolicy_Tooltip)
13106 return ref_pos + ImVec2(2, 2);
13107
13108 // Otherwise try to keep within display
13109 ImVec2 pos = ref_pos;
13110 pos.x = ImMax(lhs: ImMin(lhs: pos.x + size.x, rhs: r_outer.Max.x) - size.x, rhs: r_outer.Min.x);
13111 pos.y = ImMax(lhs: ImMin(lhs: pos.y + size.y, rhs: r_outer.Max.y) - size.y, rhs: r_outer.Min.y);
13112 return pos;
13113}
13114
13115// Note that this is used for popups, which can overlap the non work-area of individual viewports.
13116ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
13117{
13118 ImGuiContext& g = *GImGui;
13119 ImRect r_screen;
13120 if (window->ViewportAllowPlatformMonitorExtend >= 0)
13121 {
13122 // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
13123 const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
13124 r_screen.Min = monitor.WorkPos;
13125 r_screen.Max = monitor.WorkPos + monitor.WorkSize;
13126 }
13127 else
13128 {
13129 // Use the full viewport area (not work area) for popups
13130 r_screen = window->Viewport->GetMainRect();
13131 }
13132 ImVec2 padding = g.Style.DisplaySafeAreaPadding;
13133 r_screen.Expand(amount: ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
13134 return r_screen;
13135}
13136
13137ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
13138{
13139 ImGuiContext& g = *GImGui;
13140
13141 ImRect r_outer = GetPopupAllowedExtentRect(window);
13142 if (window->Flags & ImGuiWindowFlags_ChildMenu)
13143 {
13144 // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
13145 // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
13146 ImGuiWindow* parent_window = window->ParentWindow;
13147 float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
13148 ImRect r_avoid;
13149 if (parent_window->DC.MenuBarAppending)
13150 r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
13151 else
13152 r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
13153 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Default);
13154 }
13155 if (window->Flags & ImGuiWindowFlags_Popup)
13156 {
13157 return FindBestWindowPosForPopupEx(ref_pos: window->Pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid: ImRect(window->Pos, window->Pos), policy: ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
13158 }
13159 if (window->Flags & ImGuiWindowFlags_Tooltip)
13160 {
13161 // Position tooltip (always follows mouse + clamp within outer boundaries)
13162 // FIXME:
13163 // - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default).
13164 // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
13165 // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
13166 // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
13167 IM_ASSERT(g.CurrentWindow == window);
13168 const float scale = g.Style.MouseCursorScale;
13169 const ImVec2 ref_pos = NavCalcPreferredRefPos();
13170
13171 if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
13172 {
13173 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
13174 if (r_outer.Contains(r: ImRect(tooltip_pos, tooltip_pos + window->Size)))
13175 return tooltip_pos;
13176 }
13177
13178 ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
13179 ImRect r_avoid;
13180 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
13181 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
13182 else
13183 r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
13184 //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
13185
13186 return FindBestWindowPosForPopupEx(ref_pos: tooltip_pos, size: window->Size, last_dir: &window->AutoPosLastDirection, r_outer, r_avoid, policy: ImGuiPopupPositionPolicy_Tooltip);
13187 }
13188 IM_ASSERT(0);
13189 return window->Pos;
13190}
13191
13192//-----------------------------------------------------------------------------
13193// [SECTION] WINDOW FOCUS
13194//----------------------------------------------------------------------------
13195// - SetWindowFocus()
13196// - SetNextWindowFocus()
13197// - IsWindowFocused()
13198// - UpdateWindowInFocusOrderList() [Internal]
13199// - BringWindowToFocusFront() [Internal]
13200// - BringWindowToDisplayFront() [Internal]
13201// - BringWindowToDisplayBack() [Internal]
13202// - BringWindowToDisplayBehind() [Internal]
13203// - FindWindowDisplayIndex() [Internal]
13204// - FocusWindow() [Internal]
13205// - FocusTopMostWindowUnderOne() [Internal]
13206//-----------------------------------------------------------------------------
13207
13208void ImGui::SetWindowFocus()
13209{
13210 FocusWindow(window: GImGui->CurrentWindow);
13211}
13212
13213void ImGui::SetWindowFocus(const char* name)
13214{
13215 if (name)
13216 {
13217 if (ImGuiWindow* window = FindWindowByName(name))
13218 FocusWindow(window);
13219 }
13220 else
13221 {
13222 FocusWindow(NULL);
13223 }
13224}
13225
13226void ImGui::SetNextWindowFocus()
13227{
13228 ImGuiContext& g = *GImGui;
13229 g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus;
13230}
13231
13232// Similar to IsWindowHovered()
13233bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
13234{
13235 ImGuiContext& g = *GImGui;
13236 ImGuiWindow* ref_window = g.NavWindow;
13237 ImGuiWindow* cur_window = g.CurrentWindow;
13238
13239 if (ref_window == NULL)
13240 return false;
13241 if (flags & ImGuiFocusedFlags_AnyWindow)
13242 return true;
13243
13244 IM_ASSERT(cur_window); // Not inside a Begin()/End()
13245 const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
13246 const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
13247 if (flags & ImGuiFocusedFlags_RootWindow)
13248 cur_window = GetCombinedRootWindow(window: cur_window, popup_hierarchy, dock_hierarchy);
13249
13250 if (flags & ImGuiFocusedFlags_ChildWindows)
13251 return IsWindowChildOf(window: ref_window, potential_parent: cur_window, popup_hierarchy, dock_hierarchy);
13252 else
13253 return (ref_window == cur_window);
13254}
13255
13256static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13257{
13258 ImGuiContext& g = *GImGui;
13259 IM_UNUSED(g);
13260 int order = window->FocusOrder;
13261 IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13262 IM_ASSERT(g.WindowsFocusOrder[order] == window);
13263 return order;
13264}
13265
13266static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
13267{
13268 ImGuiContext& g = *GImGui;
13269
13270 const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
13271 const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
13272 if ((just_created || child_flag_changed) && !new_is_explicit_child)
13273 {
13274 IM_ASSERT(!g.WindowsFocusOrder.contains(window));
13275 g.WindowsFocusOrder.push_back(v: window);
13276 window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
13277 }
13278 else if (!just_created && child_flag_changed && new_is_explicit_child)
13279 {
13280 IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
13281 for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
13282 g.WindowsFocusOrder[n]->FocusOrder--;
13283 g.WindowsFocusOrder.erase(it: g.WindowsFocusOrder.Data + window->FocusOrder);
13284 window->FocusOrder = -1;
13285 }
13286 window->IsExplicitChild = new_is_explicit_child;
13287}
13288
13289void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
13290{
13291 ImGuiContext& g = *GImGui;
13292 IM_ASSERT(window == window->RootWindow);
13293
13294 const int cur_order = window->FocusOrder;
13295 IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
13296 if (g.WindowsFocusOrder.back() == window)
13297 return;
13298
13299 const int new_order = g.WindowsFocusOrder.Size - 1;
13300 for (int n = cur_order; n < new_order; n++)
13301 {
13302 g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
13303 g.WindowsFocusOrder[n]->FocusOrder--;
13304 IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
13305 }
13306 g.WindowsFocusOrder[new_order] = window;
13307 window->FocusOrder = (short)new_order;
13308}
13309
13310// Note technically focus related but rather adjacent and close to BringWindowToFocusFront()
13311void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
13312{
13313 ImGuiContext& g = *GImGui;
13314 ImGuiWindow* current_front_window = g.Windows.back();
13315 if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
13316 return;
13317 for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
13318 if (g.Windows[i] == window)
13319 {
13320 memmove(dest: &g.Windows[i], src: &g.Windows[i + 1], n: (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
13321 g.Windows[g.Windows.Size - 1] = window;
13322 break;
13323 }
13324}
13325
13326void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
13327{
13328 ImGuiContext& g = *GImGui;
13329 if (g.Windows[0] == window)
13330 return;
13331 for (int i = 0; i < g.Windows.Size; i++)
13332 if (g.Windows[i] == window)
13333 {
13334 memmove(dest: &g.Windows[1], src: &g.Windows[0], n: (size_t)i * sizeof(ImGuiWindow*));
13335 g.Windows[0] = window;
13336 break;
13337 }
13338}
13339
13340void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
13341{
13342 IM_ASSERT(window != NULL && behind_window != NULL);
13343 ImGuiContext& g = *GImGui;
13344 window = window->RootWindow;
13345 behind_window = behind_window->RootWindow;
13346 int pos_wnd = FindWindowDisplayIndex(window);
13347 int pos_beh = FindWindowDisplayIndex(window: behind_window);
13348 if (pos_wnd < pos_beh)
13349 {
13350 size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
13351 memmove(dest: &g.Windows.Data[pos_wnd], src: &g.Windows.Data[pos_wnd + 1], n: copy_bytes);
13352 g.Windows[pos_beh - 1] = window;
13353 }
13354 else
13355 {
13356 size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
13357 memmove(dest: &g.Windows.Data[pos_beh + 1], src: &g.Windows.Data[pos_beh], n: copy_bytes);
13358 g.Windows[pos_beh] = window;
13359 }
13360}
13361
13362int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
13363{
13364 ImGuiContext& g = *GImGui;
13365 return g.Windows.index_from_ptr(it: g.Windows.find(v: window));
13366}
13367
13368// Moving window to front of display and set focus (which happens to be back of our sorted list)
13369void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
13370{
13371 ImGuiContext& g = *GImGui;
13372
13373 // Modal check?
13374 if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
13375 if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
13376 {
13377 // This block would typically be reached in two situations:
13378 // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
13379 // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
13380 IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
13381 if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13382 BringWindowToDisplayBehind(window, behind_window: blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
13383 ClosePopupsOverWindow(ref_window: GetTopMostPopupModal(), restore_focus_to_window_under_popup: false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
13384 return;
13385 }
13386
13387 // Find last focused child (if any) and focus it instead.
13388 if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
13389 window = NavRestoreLastChildNavWindow(window);
13390
13391 // Apply focus
13392 if (g.NavWindow != window)
13393 {
13394 SetNavWindow(window);
13395 if (window && g.NavHighlightItemUnderNav)
13396 g.NavMousePosDirty = true;
13397 g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
13398 g.NavLayer = ImGuiNavLayer_Main;
13399 SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
13400 g.NavIdIsAlive = false;
13401 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13402
13403 // Close popups if any
13404 ClosePopupsOverWindow(ref_window: window, restore_focus_to_window_under_popup: false);
13405 }
13406
13407 // Move the root window to the top of the pile
13408 IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
13409 ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
13410 ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
13411 ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
13412 bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
13413
13414 // Steal active widgets. Some of the cases it triggers includes:
13415 // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
13416 // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
13417 // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
13418 if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
13419 if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
13420 ClearActiveID();
13421
13422 // Passing NULL allow to disable keyboard focus
13423 if (!window)
13424 return;
13425 window->LastFrameJustFocused = g.FrameCount;
13426
13427 // Select in dock node
13428 // For #2304 we avoid applying focus immediately before the tabbar is visible.
13429 //if (dock_node && dock_node->TabBar)
13430 // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
13431
13432 // Bring to front
13433 BringWindowToFocusFront(window: focus_front_window);
13434 if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
13435 BringWindowToDisplayFront(window: display_front_window);
13436}
13437
13438void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
13439{
13440 ImGuiContext& g = *GImGui;
13441 int start_idx = g.WindowsFocusOrder.Size - 1;
13442 if (under_this_window != NULL)
13443 {
13444 // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
13445 int offset = -1;
13446 while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
13447 {
13448 under_this_window = under_this_window->ParentWindow;
13449 offset = 0;
13450 }
13451 start_idx = FindWindowFocusIndex(window: under_this_window) + offset;
13452 }
13453 for (int i = start_idx; i >= 0; i--)
13454 {
13455 // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
13456 ImGuiWindow* window = g.WindowsFocusOrder[i];
13457 if (window == ignore_window || !window->WasActive)
13458 continue;
13459 if (filter_viewport != NULL && window->Viewport != filter_viewport)
13460 continue;
13461 if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
13462 {
13463 // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
13464 // This is failing (lagging by one frame) for docked windows.
13465 // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
13466 // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
13467 // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
13468 FocusWindow(window, flags);
13469 return;
13470 }
13471 }
13472 FocusWindow(NULL, flags);
13473}
13474
13475//-----------------------------------------------------------------------------
13476// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
13477//-----------------------------------------------------------------------------
13478
13479// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
13480// In our terminology those should be interchangeable, yet right now this is super confusing.
13481// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
13482
13483void ImGui::SetNavCursorVisible(bool visible)
13484{
13485 ImGuiContext& g = *GImGui;
13486 if (g.IO.ConfigNavCursorVisibleAlways)
13487 visible = true;
13488 g.NavCursorVisible = visible;
13489}
13490
13491// (was called NavRestoreHighlightAfterMove() before 1.91.4)
13492void ImGui::SetNavCursorVisibleAfterMove()
13493{
13494 ImGuiContext& g = *GImGui;
13495 if (g.IO.ConfigNavCursorVisibleAuto)
13496 g.NavCursorVisible = true;
13497 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
13498}
13499
13500void ImGui::SetNavWindow(ImGuiWindow* window)
13501{
13502 ImGuiContext& g = *GImGui;
13503 if (g.NavWindow != window)
13504 {
13505 IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
13506 g.NavWindow = window;
13507 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13508 }
13509 g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13510 NavUpdateAnyRequestFlag();
13511}
13512
13513void ImGui::NavHighlightActivated(ImGuiID id)
13514{
13515 ImGuiContext& g = *GImGui;
13516 g.NavHighlightActivatedId = id;
13517 g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
13518}
13519
13520void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
13521{
13522 ImGuiContext& g = *GImGui;
13523 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
13524}
13525
13526void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
13527{
13528 ImGuiContext& g = *GImGui;
13529 IM_ASSERT(g.NavWindow != NULL);
13530 IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
13531 g.NavId = id;
13532 g.NavLayer = nav_layer;
13533 SetNavFocusScope(focus_scope_id);
13534 g.NavWindow->NavLastIds[nav_layer] = id;
13535 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
13536
13537 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13538 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
13539 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13540}
13541
13542void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
13543{
13544 ImGuiContext& g = *GImGui;
13545 IM_ASSERT(id != 0);
13546
13547 if (g.NavWindow != window)
13548 SetNavWindow(window);
13549
13550 // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
13551 // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
13552 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
13553 g.NavId = id;
13554 g.NavLayer = nav_layer;
13555 SetNavFocusScope(g.CurrentFocusScopeId);
13556 window->NavLastIds[nav_layer] = id;
13557 if (g.LastItemData.ID == id)
13558 window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
13559
13560 if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
13561 g.NavHighlightItemUnderNav = true;
13562 else if (g.IO.ConfigNavCursorVisibleAuto)
13563 g.NavCursorVisible = false;
13564
13565 // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
13566 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
13567 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13568}
13569
13570static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
13571{
13572 if (ImFabs(dx) > ImFabs(dy))
13573 return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
13574 return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
13575}
13576
13577static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
13578{
13579 if (cand_max < curr_min)
13580 return cand_max - curr_min;
13581 if (curr_max < cand_min)
13582 return cand_min - curr_max;
13583 return 0.0f;
13584}
13585
13586// Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
13587static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb)
13588{
13589 ImGuiContext& g = *GImGui;
13590 ImGuiWindow* window = g.CurrentWindow;
13591 if (g.NavLayer != window->DC.NavLayerCurrent)
13592 return false;
13593
13594 // FIXME: Those are not good variables names
13595 ImRect cand = nav_bb; // Current item nav rectangle
13596 const ImRect curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
13597 g.NavScoringDebugCount++;
13598
13599 // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
13600 if (window->ParentWindow == g.NavWindow)
13601 {
13602 IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
13603 if (!window->ClipRect.Overlaps(r: cand))
13604 return false;
13605 cand.ClipWithFull(r: window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
13606 }
13607
13608 // Compute distance between boxes
13609 // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
13610 float dbx = NavScoreItemDistInterval(cand_min: cand.Min.x, cand_max: cand.Max.x, curr_min: curr.Min.x, curr_max: curr.Max.x);
13611 float dby = NavScoreItemDistInterval(cand_min: ImLerp(a: cand.Min.y, b: cand.Max.y, t: 0.2f), cand_max: ImLerp(a: cand.Min.y, b: cand.Max.y, t: 0.8f), curr_min: ImLerp(a: curr.Min.y, b: curr.Max.y, t: 0.2f), curr_max: ImLerp(a: curr.Min.y, b: curr.Max.y, t: 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
13612 if (dby != 0.0f && dbx != 0.0f)
13613 dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
13614 float dist_box = ImFabs(dbx) + ImFabs(dby);
13615
13616 // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
13617 float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
13618 float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
13619 float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
13620
13621 // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
13622 ImGuiDir quadrant;
13623 float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
13624 if (dbx != 0.0f || dby != 0.0f)
13625 {
13626 // For non-overlapping boxes, use distance between boxes
13627 // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y
13628 // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
13629 // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
13630 dax = dbx;
13631 day = dby;
13632 dist_axial = dist_box;
13633 quadrant = ImGetDirQuadrantFromDelta(dx: dbx, dy: dby);
13634 }
13635 else if (dcx != 0.0f || dcy != 0.0f)
13636 {
13637 // For overlapping boxes with different centers, use distance between centers
13638 dax = dcx;
13639 day = dcy;
13640 dist_axial = dist_center;
13641 quadrant = ImGetDirQuadrantFromDelta(dx: dcx, dy: dcy);
13642 }
13643 else
13644 {
13645 // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
13646 quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
13647 }
13648
13649 const ImGuiDir move_dir = g.NavMoveDir;
13650#if IMGUI_DEBUG_NAV_SCORING
13651 char buf[200];
13652 if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
13653 {
13654 if (quadrant == move_dir)
13655 {
13656 ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
13657 ImDrawList* draw_list = GetForegroundDrawList(window);
13658 draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
13659 draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
13660 draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
13661 }
13662 }
13663 const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
13664 const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
13665 if (debug_hovering || debug_tty)
13666 {
13667 ImFormatString(buf, IM_ARRAYSIZE(buf),
13668 "d-box (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
13669 dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
13670 if (debug_hovering)
13671 {
13672 ImDrawList* draw_list = GetForegroundDrawList(window);
13673 draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
13674 draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
13675 draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
13676 draw_list->AddText(cand.Max, ~0U, buf);
13677 }
13678 if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
13679 }
13680#endif
13681
13682 // Is it in the quadrant we're interested in moving to?
13683 bool new_best = false;
13684 if (quadrant == move_dir)
13685 {
13686 // Does it beat the current best candidate?
13687 if (dist_box < result->DistBox)
13688 {
13689 result->DistBox = dist_box;
13690 result->DistCenter = dist_center;
13691 return true;
13692 }
13693 if (dist_box == result->DistBox)
13694 {
13695 // Try using distance between center points to break ties
13696 if (dist_center < result->DistCenter)
13697 {
13698 result->DistCenter = dist_center;
13699 new_best = true;
13700 }
13701 else if (dist_center == result->DistCenter)
13702 {
13703 // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
13704 // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
13705 // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
13706 if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
13707 new_best = true;
13708 }
13709 }
13710 }
13711
13712 // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
13713 // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
13714 // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
13715 // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
13716 // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
13717 if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
13718 if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
13719 if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
13720 {
13721 result->DistAxial = dist_axial;
13722 new_best = true;
13723 }
13724
13725 return new_best;
13726}
13727
13728static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
13729{
13730 ImGuiContext& g = *GImGui;
13731 ImGuiWindow* window = g.CurrentWindow;
13732 result->Window = window;
13733 result->ID = g.LastItemData.ID;
13734 result->FocusScopeId = g.CurrentFocusScopeId;
13735 result->ItemFlags = g.LastItemData.ItemFlags;
13736 result->RectRel = WindowRectAbsToRel(window, r: g.LastItemData.NavRect);
13737 if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13738 {
13739 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13740 result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13741 }
13742}
13743
13744// True when current work location may be scrolled horizontally when moving left / right.
13745// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
13746void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
13747{
13748 ImGuiContext& g = *GImGui;
13749 ImGuiWindow* window = g.CurrentWindow;
13750 window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
13751}
13752
13753// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
13754// This is called after LastItemData is set, but NextItemData is also still valid.
13755static void ImGui::NavProcessItem()
13756{
13757 ImGuiContext& g = *GImGui;
13758 ImGuiWindow* window = g.CurrentWindow;
13759 const ImGuiID id = g.LastItemData.ID;
13760 const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
13761
13762 // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816)
13763 ImRect nav_bb = g.LastItemData.NavRect;
13764 if (window->DC.NavIsScrollPushableX == false)
13765 {
13766 nav_bb.Min.x = ImClamp(v: nav_bb.Min.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
13767 nav_bb.Max.x = ImClamp(v: nav_bb.Max.x, mn: window->ClipRect.Min.x, mx: window->ClipRect.Max.x);
13768 }
13769
13770 // Process Init Request
13771 if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
13772 {
13773 // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
13774 const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
13775 if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
13776 {
13777 NavApplyItemToResult(result: &g.NavInitResult);
13778 }
13779 if (candidate_for_nav_default_focus)
13780 {
13781 g.NavInitRequest = false; // Found a match, clear request
13782 NavUpdateAnyRequestFlag();
13783 }
13784 }
13785
13786 // Process Move Request (scoring for navigation)
13787 // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
13788 if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
13789 {
13790 if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
13791 {
13792 const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13793 if (is_tabbing)
13794 {
13795 NavProcessItemForTabbingRequest(id, item_flags, move_flags: g.NavMoveFlags);
13796 }
13797 else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
13798 {
13799 ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
13800 if (NavScoreItem(result, nav_bb))
13801 NavApplyItemToResult(result);
13802
13803 // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
13804 const float VISIBLE_RATIO = 0.70f;
13805 if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(r: nav_bb))
13806 if (ImClamp(v: nav_bb.Max.y, mn: window->ClipRect.Min.y, mx: window->ClipRect.Max.y) - ImClamp(v: nav_bb.Min.y, mn: window->ClipRect.Min.y, mx: window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
13807 if (NavScoreItem(result: &g.NavMoveResultLocalVisible, nav_bb))
13808 NavApplyItemToResult(result: &g.NavMoveResultLocalVisible);
13809 }
13810 }
13811 }
13812
13813 // Update information for currently focused/navigated item
13814 if (g.NavId == id)
13815 {
13816 if (g.NavWindow != window)
13817 SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
13818 g.NavLayer = window->DC.NavLayerCurrent;
13819 SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
13820 g.NavFocusScopeId = g.CurrentFocusScopeId;
13821 g.NavIdIsAlive = true;
13822 if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
13823 {
13824 IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
13825 g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
13826 }
13827 window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, r: nav_bb); // Store item bounding box (relative to window position)
13828 }
13829}
13830
13831// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
13832// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
13833// - Case 1: no nav/active id: set result to first eligible item, stop storing.
13834// - Case 2: tab forward: on ref id set counter, on counter elapse store result
13835// - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
13836// - Case 4: tab backward: store all results, on ref id pick prev, stop storing
13837// - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
13838void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
13839{
13840 ImGuiContext& g = *GImGui;
13841
13842 if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
13843 {
13844 if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
13845 return;
13846 if (g.NavFocusScopeId != g.CurrentFocusScopeId)
13847 return;
13848 }
13849
13850 // - Can always land on an item when using API call.
13851 // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
13852 // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
13853 bool can_stop;
13854 if (move_flags & ImGuiNavMoveFlags_FocusApi)
13855 can_stop = true;
13856 else
13857 can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
13858
13859 // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
13860 ImGuiNavItemData* result = &g.NavMoveResultLocal;
13861 if (g.NavTabbingDir == +1)
13862 {
13863 // Tab Forward or SetKeyboardFocusHere() with >= 0
13864 if (can_stop && g.NavTabbingResultFirst.ID == 0)
13865 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
13866 if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
13867 NavMoveRequestResolveWithLastItem(result);
13868 else if (g.NavId == id)
13869 g.NavTabbingCounter = 1;
13870 }
13871 else if (g.NavTabbingDir == -1)
13872 {
13873 // Tab Backward
13874 if (g.NavId == id)
13875 {
13876 if (result->ID)
13877 {
13878 g.NavMoveScoringItems = false;
13879 NavUpdateAnyRequestFlag();
13880 }
13881 }
13882 else if (can_stop)
13883 {
13884 // Keep applying until reaching NavId
13885 NavApplyItemToResult(result);
13886 }
13887 }
13888 else if (g.NavTabbingDir == 0)
13889 {
13890 if (can_stop && g.NavId == id)
13891 NavMoveRequestResolveWithLastItem(result);
13892 if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
13893 NavApplyItemToResult(result: &g.NavTabbingResultFirst);
13894 }
13895}
13896
13897bool ImGui::NavMoveRequestButNoResultYet()
13898{
13899 ImGuiContext& g = *GImGui;
13900 return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
13901}
13902
13903// FIXME: ScoringRect is not set
13904void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13905{
13906 ImGuiContext& g = *GImGui;
13907 IM_ASSERT(g.NavWindow != NULL);
13908 //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
13909
13910 if (move_flags & ImGuiNavMoveFlags_IsTabbing)
13911 move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
13912
13913 g.NavMoveSubmitted = g.NavMoveScoringItems = true;
13914 g.NavMoveDir = move_dir;
13915 g.NavMoveDirForDebug = move_dir;
13916 g.NavMoveClipDir = clip_dir;
13917 g.NavMoveFlags = move_flags;
13918 g.NavMoveScrollFlags = scroll_flags;
13919 g.NavMoveForwardToNextFrame = false;
13920 g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
13921 g.NavMoveResultLocal.Clear();
13922 g.NavMoveResultLocalVisible.Clear();
13923 g.NavMoveResultOther.Clear();
13924 g.NavTabbingCounter = 0;
13925 g.NavTabbingResultFirst.Clear();
13926 NavUpdateAnyRequestFlag();
13927}
13928
13929void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
13930{
13931 ImGuiContext& g = *GImGui;
13932 g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
13933 NavApplyItemToResult(result);
13934 NavUpdateAnyRequestFlag();
13935}
13936
13937// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent
13938void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data)
13939{
13940 ImGuiContext& g = *GImGui;
13941 g.NavMoveScoringItems = false;
13942 g.LastItemData.ID = tree_node_data->ID;
13943 g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
13944 g.LastItemData.NavRect = tree_node_data->NavRect;
13945 NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
13946 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
13947 NavUpdateAnyRequestFlag();
13948}
13949
13950void ImGui::NavMoveRequestCancel()
13951{
13952 ImGuiContext& g = *GImGui;
13953 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
13954 NavUpdateAnyRequestFlag();
13955}
13956
13957// Forward will reuse the move request again on the next frame (generally with modifications done to it)
13958void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
13959{
13960 ImGuiContext& g = *GImGui;
13961 IM_ASSERT(g.NavMoveForwardToNextFrame == false);
13962 NavMoveRequestCancel();
13963 g.NavMoveForwardToNextFrame = true;
13964 g.NavMoveDir = move_dir;
13965 g.NavMoveClipDir = clip_dir;
13966 g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
13967 g.NavMoveScrollFlags = scroll_flags;
13968}
13969
13970// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
13971// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
13972void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
13973{
13974 ImGuiContext& g = *GImGui;
13975 IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
13976
13977 // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
13978 // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
13979 if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
13980 g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
13981}
13982
13983// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
13984// This way we could find the last focused window among our children. It would be much less confusing this way?
13985static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
13986{
13987 ImGuiWindow* parent = nav_window;
13988 while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13989 parent = parent->ParentWindow;
13990 if (parent && parent != nav_window)
13991 parent->NavLastChildNavWindow = nav_window;
13992}
13993
13994// Restore the last focused child.
13995// Call when we are expected to land on the Main Layer (0) after FocusWindow()
13996static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
13997{
13998 if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
13999 return window->NavLastChildNavWindow;
14000 if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
14001 if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar: window->DockNodeAsHost->TabBar))
14002 return tab->Window;
14003 return window;
14004}
14005
14006void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
14007{
14008 ImGuiContext& g = *GImGui;
14009 if (layer == ImGuiNavLayer_Main)
14010 {
14011 ImGuiWindow* prev_nav_window = g.NavWindow;
14012 g.NavWindow = NavRestoreLastChildNavWindow(window: g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
14013 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14014 if (prev_nav_window)
14015 IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
14016 }
14017 ImGuiWindow* window = g.NavWindow;
14018 if (window->NavLastIds[layer] != 0)
14019 {
14020 SetNavID(id: window->NavLastIds[layer], nav_layer: layer, focus_scope_id: 0, rect_rel: window->NavRectRel[layer]);
14021 }
14022 else
14023 {
14024 g.NavLayer = layer;
14025 NavInitWindow(window, force_reinit: true);
14026 }
14027}
14028
14029static inline void ImGui::NavUpdateAnyRequestFlag()
14030{
14031 ImGuiContext& g = *GImGui;
14032 g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
14033 if (g.NavAnyRequest)
14034 IM_ASSERT(g.NavWindow != NULL);
14035}
14036
14037// This needs to be called before we submit any widget (aka in or before Begin)
14038void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
14039{
14040 // FIXME: ChildWindow test here is wrong for docking
14041 ImGuiContext& g = *GImGui;
14042 IM_ASSERT(window == g.NavWindow);
14043
14044 if (window->Flags & ImGuiWindowFlags_NoNavInputs)
14045 {
14046 g.NavId = 0;
14047 SetNavFocusScope(window->NavRootFocusScopeId);
14048 return;
14049 }
14050
14051 bool init_for_nav = false;
14052 if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
14053 init_for_nav = true;
14054 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
14055 if (init_for_nav)
14056 {
14057 SetNavID(id: 0, nav_layer: g.NavLayer, focus_scope_id: window->NavRootFocusScopeId, rect_rel: ImRect());
14058 g.NavInitRequest = true;
14059 g.NavInitRequestFromMove = false;
14060 g.NavInitResult.ID = 0;
14061 NavUpdateAnyRequestFlag();
14062 }
14063 else
14064 {
14065 g.NavId = window->NavLastIds[0];
14066 SetNavFocusScope(window->NavRootFocusScopeId);
14067 }
14068}
14069
14070static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
14071{
14072 ImGuiContext& g = *GImGui;
14073 ImGuiWindow* window = g.NavWindow;
14074 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14075
14076 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
14077 if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut)
14078 return ImGuiInputSource_Mouse;
14079 else
14080 return ImGuiInputSource_Keyboard; // or Nav in general
14081}
14082
14083static ImVec2 ImGui::NavCalcPreferredRefPos()
14084{
14085 ImGuiContext& g = *GImGui;
14086 ImGuiWindow* window = g.NavWindow;
14087 ImGuiInputSource source = NavCalcPreferredRefPosSource();
14088
14089 const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
14090
14091 // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
14092 if (source == ImGuiInputSource_Mouse)
14093 {
14094 // Mouse (we need a fallback in case the mouse becomes invalid after being used)
14095 // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
14096 // In theory we could move that +1.0f offset in OpenPopupEx()
14097 ImVec2 p = IsMousePosValid(mouse_pos: &g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
14098 return ImVec2(p.x + 1.0f, p.y);
14099 }
14100 else
14101 {
14102 // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
14103 ImRect ref_rect;
14104 if (activated_shortcut)
14105 ref_rect = g.LastItemData.NavRect;
14106 else
14107 ref_rect = WindowRectRelToAbs(window, r: window->NavRectRel[g.NavLayer]);
14108
14109 // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
14110 if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
14111 {
14112 ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
14113 ref_rect.Translate(d: window->Scroll - next_scroll);
14114 }
14115 ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(lhs: g.Style.FramePadding.x * 4, rhs: ref_rect.GetWidth()), ref_rect.Max.y - ImMin(lhs: g.Style.FramePadding.y, rhs: ref_rect.GetHeight()));
14116 ImGuiViewport* viewport = window->Viewport;
14117 return ImTrunc(v: ImClamp(v: pos, mn: viewport->Pos, mx: viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
14118 }
14119}
14120
14121float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
14122{
14123 ImGuiContext& g = *GImGui;
14124 float repeat_delay, repeat_rate;
14125 GetTypematicRepeatRate(flags: ImGuiInputFlags_RepeatRateNavTweak, repeat_delay: &repeat_delay, repeat_rate: &repeat_rate);
14126
14127 ImGuiKey key_less, key_more;
14128 if (g.NavInputSource == ImGuiInputSource_Gamepad)
14129 {
14130 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
14131 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
14132 }
14133 else
14134 {
14135 key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
14136 key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
14137 }
14138 float amount = (float)GetKeyPressedAmount(key: key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key: key_less, repeat_delay, repeat_rate);
14139 if (amount != 0.0f && IsKeyDown(key: key_less) && IsKeyDown(key: key_more)) // Cancel when opposite directions are held, regardless of repeat phase
14140 amount = 0.0f;
14141 return amount;
14142}
14143
14144static void ImGui::NavUpdate()
14145{
14146 ImGuiContext& g = *GImGui;
14147 ImGuiIO& io = g.IO;
14148
14149 io.WantSetMousePos = false;
14150 //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
14151
14152 // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
14153 // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
14154 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14155 const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
14156 if (nav_gamepad_active)
14157 for (ImGuiKey key : nav_gamepad_keys_to_change_source)
14158 if (IsKeyDown(key))
14159 g.NavInputSource = ImGuiInputSource_Gamepad;
14160 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14161 const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
14162 if (nav_keyboard_active)
14163 for (ImGuiKey key : nav_keyboard_keys_to_change_source)
14164 if (IsKeyDown(key))
14165 g.NavInputSource = ImGuiInputSource_Keyboard;
14166
14167 // Process navigation init request (select first/default focus)
14168 g.NavJustMovedToId = 0;
14169 g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
14170 if (g.NavInitResult.ID != 0)
14171 NavInitRequestApplyResult();
14172 g.NavInitRequest = false;
14173 g.NavInitRequestFromMove = false;
14174 g.NavInitResult.ID = 0;
14175
14176 // Process navigation move request
14177 if (g.NavMoveSubmitted)
14178 NavMoveRequestApplyResult();
14179 g.NavTabbingCounter = 0;
14180 g.NavMoveSubmitted = g.NavMoveScoringItems = false;
14181 if (g.NavCursorHideFrames > 0)
14182 if (--g.NavCursorHideFrames == 0)
14183 g.NavCursorVisible = true;
14184
14185 // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
14186 bool set_mouse_pos = false;
14187 if (g.NavMousePosDirty && g.NavIdIsAlive)
14188 if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
14189 set_mouse_pos = true;
14190 g.NavMousePosDirty = false;
14191 IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
14192
14193 // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
14194 if (g.NavWindow)
14195 NavSaveLastChildNavWindowIntoParent(nav_window: g.NavWindow);
14196 if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
14197 g.NavWindow->NavLastChildNavWindow = NULL;
14198
14199 // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
14200 NavUpdateWindowing();
14201
14202 // Set output flags for user application
14203 io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
14204 io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
14205
14206 // Process NavCancel input (to close a popup, get back to parent, clear focus)
14207 NavUpdateCancelRequest();
14208
14209 // Process manual activation request
14210 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
14211 g.NavActivateFlags = ImGuiActivateFlags_None;
14212 if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14213 {
14214 const bool activate_down = (nav_keyboard_active && IsKeyDown(key: ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
14215 const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Space, flags: 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, flags: 0, ImGuiKeyOwner_NoOwner)));
14216 const bool input_down = (nav_keyboard_active && (IsKeyDown(key: ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(key: ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
14217 const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(key: ImGuiKey_Enter, flags: 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(key: ImGuiKey_KeypadEnter, flags: 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, flags: 0, ImGuiKeyOwner_NoOwner)));
14218 if (g.ActiveId == 0 && activate_pressed)
14219 {
14220 g.NavActivateId = g.NavId;
14221 g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
14222 }
14223 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
14224 {
14225 g.NavActivateId = g.NavId;
14226 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
14227 }
14228 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
14229 g.NavActivateDownId = g.NavId;
14230 if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
14231 {
14232 g.NavActivatePressedId = g.NavId;
14233 NavHighlightActivated(id: g.NavId);
14234 }
14235 }
14236 if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
14237 g.NavCursorVisible = false;
14238 else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
14239 g.NavCursorVisible = true;
14240 if (g.NavActivateId != 0)
14241 IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
14242
14243 // Highlight
14244 if (g.NavHighlightActivatedTimer > 0.0f)
14245 g.NavHighlightActivatedTimer = ImMax(lhs: 0.0f, rhs: g.NavHighlightActivatedTimer - io.DeltaTime);
14246 if (g.NavHighlightActivatedTimer == 0.0f)
14247 g.NavHighlightActivatedId = 0;
14248
14249 // Process programmatic activation request
14250 // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
14251 if (g.NavNextActivateId != 0)
14252 {
14253 g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
14254 g.NavActivateFlags = g.NavNextActivateFlags;
14255 }
14256 g.NavNextActivateId = 0;
14257
14258 // Process move requests
14259 NavUpdateCreateMoveRequest();
14260 if (g.NavMoveDir == ImGuiDir_None)
14261 NavUpdateCreateTabbingRequest();
14262 NavUpdateAnyRequestFlag();
14263 g.NavIdIsAlive = false;
14264
14265 // Scrolling
14266 if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
14267 {
14268 // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
14269 ImGuiWindow* window = g.NavWindow;
14270 const float scroll_speed = IM_ROUND(window->FontRefSize * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
14271 const ImGuiDir move_dir = g.NavMoveDir;
14272 if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
14273 {
14274 if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
14275 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
14276 if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
14277 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
14278 }
14279
14280 // *Normal* Manual scroll with LStick
14281 // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
14282 if (nav_gamepad_active)
14283 {
14284 const ImVec2 scroll_dir = GetKeyMagnitude2d(key_left: ImGuiKey_GamepadLStickLeft, key_right: ImGuiKey_GamepadLStickRight, key_up: ImGuiKey_GamepadLStickUp, key_down: ImGuiKey_GamepadLStickDown);
14285 const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
14286 if (scroll_dir.x != 0.0f && window->ScrollbarX)
14287 SetScrollX(window, scroll_x: ImTrunc(f: window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
14288 if (scroll_dir.y != 0.0f)
14289 SetScrollY(window, scroll_y: ImTrunc(f: window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
14290 }
14291 }
14292
14293 // Always prioritize mouse highlight if navigation is disabled
14294 if (!nav_keyboard_active && !nav_gamepad_active)
14295 {
14296 g.NavCursorVisible = false;
14297 g.NavHighlightItemUnderNav = set_mouse_pos = false;
14298 }
14299
14300 // Update mouse position if requested
14301 // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
14302 if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
14303 TeleportMousePos(pos: NavCalcPreferredRefPos());
14304
14305 // [DEBUG]
14306 g.NavScoringDebugCount = 0;
14307#if IMGUI_DEBUG_NAV_RECTS
14308 if (ImGuiWindow* debug_window = g.NavWindow)
14309 {
14310 ImDrawList* draw_list = GetForegroundDrawList(debug_window);
14311 int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
14312 //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
14313 }
14314#endif
14315}
14316
14317void ImGui::NavInitRequestApplyResult()
14318{
14319 // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
14320 ImGuiContext& g = *GImGui;
14321 if (!g.NavWindow)
14322 return;
14323
14324 ImGuiNavItemData* result = &g.NavInitResult;
14325 if (g.NavId != result->ID)
14326 {
14327 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14328 g.NavJustMovedToId = result->ID;
14329 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14330 g.NavJustMovedToKeyMods = 0;
14331 g.NavJustMovedToIsTabbing = false;
14332 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14333 }
14334
14335 // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
14336 // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
14337 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14338 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
14339 g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
14340 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14341 g.NavLastValidSelectionUserData = result->SelectionUserData;
14342 if (g.NavInitRequestFromMove)
14343 SetNavCursorVisibleAfterMove();
14344}
14345
14346// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
14347static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
14348{
14349 // Bias initial rect
14350 ImGuiContext& g = *GImGui;
14351 const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
14352
14353 // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
14354 // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
14355 // - But each successful move sets new bias on one axis, only cleared when using mouse.
14356 if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
14357 {
14358 if (preferred_pos_rel.x == FLT_MAX)
14359 preferred_pos_rel.x = ImMin(lhs: r.Min.x + 1.0f, rhs: r.Max.x) - rel_to_abs_offset.x;
14360 if (preferred_pos_rel.y == FLT_MAX)
14361 preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
14362 }
14363
14364 // Apply general bias on the other axis
14365 if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
14366 r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
14367 else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
14368 r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
14369}
14370
14371void ImGui::NavUpdateCreateMoveRequest()
14372{
14373 ImGuiContext& g = *GImGui;
14374 ImGuiIO& io = g.IO;
14375 ImGuiWindow* window = g.NavWindow;
14376 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14377 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14378
14379 if (g.NavMoveForwardToNextFrame && window != NULL)
14380 {
14381 // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
14382 // (preserve most state, which were already set by the NavMoveRequestForward() function)
14383 IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
14384 IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
14385 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
14386 }
14387 else
14388 {
14389 // Initiate directional inputs request
14390 g.NavMoveDir = ImGuiDir_None;
14391 g.NavMoveFlags = ImGuiNavMoveFlags_None;
14392 g.NavMoveScrollFlags = ImGuiScrollFlags_None;
14393 if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
14394 {
14395 const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
14396 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadLeft, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_LeftArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
14397 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadRight, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_RightArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
14398 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadUp, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_UpArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
14399 if (!IsActiveIdUsingNavDir(dir: ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressed(key: ImGuiKey_GamepadDpadDown, flags: repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(key: ImGuiKey_DownArrow, flags: repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
14400 }
14401 g.NavMoveClipDir = g.NavMoveDir;
14402 g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14403 }
14404
14405 // Update PageUp/PageDown/Home/End scroll
14406 // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
14407 float scoring_rect_offset_y = 0.0f;
14408 if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
14409 scoring_rect_offset_y = NavUpdatePageUpPageDown();
14410 if (scoring_rect_offset_y != 0.0f)
14411 {
14412 g.NavScoringNoClipRect = window->InnerRect;
14413 g.NavScoringNoClipRect.TranslateY(dy: scoring_rect_offset_y);
14414 }
14415
14416 // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
14417#if IMGUI_DEBUG_NAV_SCORING
14418 //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
14419 // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
14420 if (io.KeyCtrl)
14421 {
14422 if (g.NavMoveDir == ImGuiDir_None)
14423 g.NavMoveDir = g.NavMoveDirForDebug;
14424 g.NavMoveClipDir = g.NavMoveDir;
14425 g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
14426 }
14427#endif
14428
14429 // Submit
14430 g.NavMoveForwardToNextFrame = false;
14431 if (g.NavMoveDir != ImGuiDir_None)
14432 NavMoveRequestSubmit(move_dir: g.NavMoveDir, clip_dir: g.NavMoveClipDir, move_flags: g.NavMoveFlags, scroll_flags: g.NavMoveScrollFlags);
14433
14434 // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
14435 if (g.NavMoveSubmitted && g.NavId == 0)
14436 {
14437 IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
14438 g.NavInitRequest = g.NavInitRequestFromMove = true;
14439 g.NavInitResult.ID = 0;
14440 if (g.IO.ConfigNavCursorVisibleAuto)
14441 g.NavCursorVisible = true;
14442 }
14443
14444 // When using gamepad, we project the reference nav bounding box into window visible area.
14445 // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
14446 // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
14447 if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
14448 {
14449 bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
14450 bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
14451 ImRect inner_rect_rel = WindowRectAbsToRel(window, r: ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
14452
14453 // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
14454 // Otherwise 'inner_rect_rel' would be off on the move result frame.
14455 inner_rect_rel.Translate(d: CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
14456
14457 if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(r: window->NavRectRel[g.NavLayer]))
14458 {
14459 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
14460 float pad_x = ImMin(lhs: inner_rect_rel.GetWidth(), rhs: window->FontRefSize * 0.5f);
14461 float pad_y = ImMin(lhs: inner_rect_rel.GetHeight(), rhs: window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
14462 inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
14463 inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
14464 inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
14465 inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
14466 window->NavRectRel[g.NavLayer].ClipWithFull(r: inner_rect_rel);
14467 g.NavId = 0;
14468 }
14469 }
14470
14471 // Prepare scoring rectangle.
14472 // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
14473 ImRect scoring_rect;
14474 if (window != NULL)
14475 {
14476 ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
14477 scoring_rect = WindowRectRelToAbs(window, r: nav_rect_rel);
14478 scoring_rect.TranslateY(dy: scoring_rect_offset_y);
14479 if (g.NavMoveSubmitted)
14480 NavBiasScoringRect(r&: scoring_rect, preferred_pos_rel&: window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], move_dir: g.NavMoveDir, move_flags: g.NavMoveFlags);
14481 IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
14482 //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
14483 //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
14484 }
14485 g.NavScoringRect = scoring_rect;
14486 //g.NavScoringNoClipRect.Add(scoring_rect);
14487}
14488
14489void ImGui::NavUpdateCreateTabbingRequest()
14490{
14491 ImGuiContext& g = *GImGui;
14492 ImGuiWindow* window = g.NavWindow;
14493 IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
14494 if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
14495 return;
14496
14497 const bool tab_pressed = IsKeyPressed(key: ImGuiKey_Tab, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
14498 if (!tab_pressed)
14499 return;
14500
14501 // Initiate tabbing request
14502 // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
14503 // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
14504 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14505 if (nav_keyboard_active)
14506 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
14507 else
14508 g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
14509 ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
14510 ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
14511 ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
14512 NavMoveRequestSubmit(move_dir: ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
14513 g.NavTabbingCounter = -1;
14514}
14515
14516// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
14517void ImGui::NavMoveRequestApplyResult()
14518{
14519 ImGuiContext& g = *GImGui;
14520#if IMGUI_DEBUG_NAV_SCORING
14521 if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
14522 return;
14523#endif
14524
14525 // Select which result to use
14526 ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
14527
14528 // Tabbing forward wrap
14529 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
14530 if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
14531 result = &g.NavTabbingResultFirst;
14532
14533 // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
14534 const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14535 if (result == NULL)
14536 {
14537 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14538 g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
14539 if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14540 SetNavCursorVisibleAfterMove();
14541 NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
14542 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
14543 return;
14544 }
14545
14546 // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
14547 if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
14548 if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
14549 result = &g.NavMoveResultLocalVisible;
14550
14551 // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
14552 if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
14553 if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
14554 result = &g.NavMoveResultOther;
14555 IM_ASSERT(g.NavWindow && result->Window);
14556
14557 // Scroll to keep newly navigated item fully into view.
14558 if (g.NavLayer == ImGuiNavLayer_Main)
14559 {
14560 ImRect rect_abs = WindowRectRelToAbs(window: result->Window, r: result->RectRel);
14561 ScrollToRectEx(window: result->Window, item_rect: rect_abs, flags: g.NavMoveScrollFlags);
14562
14563 if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
14564 {
14565 // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
14566 float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
14567 SetScrollY(window: result->Window, scroll_y: scroll_target);
14568 }
14569 }
14570
14571 if (g.NavWindow != result->Window)
14572 {
14573 IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
14574 g.NavWindow = result->Window;
14575 g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
14576 }
14577
14578 // Clear active id unless requested not to
14579 // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
14580 // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
14581 if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
14582 ClearActiveID();
14583
14584 // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
14585 // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
14586 if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
14587 {
14588 g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
14589 g.NavJustMovedToId = result->ID;
14590 g.NavJustMovedToFocusScopeId = result->FocusScopeId;
14591 g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
14592 g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
14593 g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
14594 //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
14595 }
14596
14597 // Apply new NavID/Focus
14598 IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
14599 ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
14600 SetNavID(id: result->ID, nav_layer: g.NavLayer, focus_scope_id: result->FocusScopeId, rect_rel: result->RectRel);
14601 if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
14602 g.NavLastValidSelectionUserData = result->SelectionUserData;
14603
14604 // Restore last preferred position for current axis
14605 // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
14606 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
14607 {
14608 preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
14609 g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
14610 }
14611
14612 // Tabbing: Activates Inputable, otherwise only Focus
14613 if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
14614 g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
14615
14616 // Activate
14617 if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
14618 {
14619 g.NavNextActivateId = result->ID;
14620 g.NavNextActivateFlags = ImGuiActivateFlags_None;
14621 if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
14622 g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
14623 }
14624
14625 // Make nav cursor visible
14626 if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
14627 SetNavCursorVisibleAfterMove();
14628}
14629
14630// Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
14631// FIXME: In order to support e.g. Escape to clear a selection we'll need:
14632// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
14633// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
14634static void ImGui::NavUpdateCancelRequest()
14635{
14636 ImGuiContext& g = *GImGui;
14637 const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14638 const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14639 if (!(nav_keyboard_active && IsKeyPressed(key: ImGuiKey_Escape, flags: 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, flags: 0, ImGuiKeyOwner_NoOwner)))
14640 return;
14641
14642 IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
14643 if (g.ActiveId != 0)
14644 {
14645 ClearActiveID();
14646 }
14647 else if (g.NavLayer != ImGuiNavLayer_Main)
14648 {
14649 // Leave the "menu" layer
14650 NavRestoreLayer(layer: ImGuiNavLayer_Main);
14651 SetNavCursorVisibleAfterMove();
14652 }
14653 else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
14654 {
14655 // Exit child window
14656 ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
14657 ImGuiWindow* parent_window = child_window->ParentWindow;
14658 IM_ASSERT(child_window->ChildId != 0);
14659 FocusWindow(window: parent_window);
14660 SetNavID(id: child_window->ChildId, nav_layer: ImGuiNavLayer_Main, focus_scope_id: 0, rect_rel: WindowRectAbsToRel(window: parent_window, r: child_window->Rect()));
14661 SetNavCursorVisibleAfterMove();
14662 }
14663 else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
14664 {
14665 // Close open popup/menu
14666 ClosePopupToLevel(remaining: g.OpenPopupStack.Size - 1, restore_focus_to_window_under_popup: true);
14667 }
14668 else
14669 {
14670 // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
14671 // FIXME-NAV: This should happen on window appearing.
14672 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14673 if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
14674 g.NavWindow->NavLastIds[0] = 0;
14675
14676 // Clear nav focus
14677 if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
14678 g.NavId = 0;
14679 if (g.IO.ConfigNavEscapeClearFocusWindow)
14680 FocusWindow(NULL);
14681 }
14682}
14683
14684// Handle PageUp/PageDown/Home/End keys
14685// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
14686// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
14687// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
14688static float ImGui::NavUpdatePageUpPageDown()
14689{
14690 ImGuiContext& g = *GImGui;
14691 ImGuiWindow* window = g.NavWindow;
14692 if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
14693 return 0.0f;
14694
14695 const bool page_up_held = IsKeyDown(key: ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
14696 const bool page_down_held = IsKeyDown(key: ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
14697 const bool home_pressed = IsKeyPressed(key: ImGuiKey_Home, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14698 const bool end_pressed = IsKeyPressed(key: ImGuiKey_End, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
14699 if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
14700 return 0.0f;
14701
14702 if (g.NavLayer != ImGuiNavLayer_Main)
14703 NavRestoreLayer(layer: ImGuiNavLayer_Main);
14704
14705 if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY)
14706 {
14707 // Fallback manual-scroll when window has no navigable item
14708 if (IsKeyPressed(key: ImGuiKey_PageUp, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14709 SetScrollY(window, scroll_y: window->Scroll.y - window->InnerRect.GetHeight());
14710 else if (IsKeyPressed(key: ImGuiKey_PageDown, flags: ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
14711 SetScrollY(window, scroll_y: window->Scroll.y + window->InnerRect.GetHeight());
14712 else if (home_pressed)
14713 SetScrollY(window, scroll_y: 0.0f);
14714 else if (end_pressed)
14715 SetScrollY(window, scroll_y: window->ScrollMax.y);
14716 }
14717 else
14718 {
14719 ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
14720 const float page_offset_y = ImMax(lhs: 0.0f, rhs: window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight());
14721 float nav_scoring_rect_offset_y = 0.0f;
14722 if (IsKeyPressed(key: ImGuiKey_PageUp, repeat: true))
14723 {
14724 nav_scoring_rect_offset_y = -page_offset_y;
14725 g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
14726 g.NavMoveClipDir = ImGuiDir_Up;
14727 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
14728 }
14729 else if (IsKeyPressed(key: ImGuiKey_PageDown, repeat: true))
14730 {
14731 nav_scoring_rect_offset_y = +page_offset_y;
14732 g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
14733 g.NavMoveClipDir = ImGuiDir_Down;
14734 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
14735 }
14736 else if (home_pressed)
14737 {
14738 // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
14739 // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
14740 // Preserve current horizontal position if we have any.
14741 nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
14742 if (nav_rect_rel.IsInverted())
14743 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14744 g.NavMoveDir = ImGuiDir_Down;
14745 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14746 // FIXME-NAV: MoveClipDir left to _None, intentional?
14747 }
14748 else if (end_pressed)
14749 {
14750 nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
14751 if (nav_rect_rel.IsInverted())
14752 nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
14753 g.NavMoveDir = ImGuiDir_Up;
14754 g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
14755 // FIXME-NAV: MoveClipDir left to _None, intentional?
14756 }
14757 return nav_scoring_rect_offset_y;
14758 }
14759 return 0.0f;
14760}
14761
14762static void ImGui::NavEndFrame()
14763{
14764 ImGuiContext& g = *GImGui;
14765
14766 // Show CTRL+TAB list window
14767 if (g.NavWindowingTarget != NULL)
14768 NavUpdateWindowingOverlay();
14769
14770 // Perform wrap-around in menus
14771 // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
14772 // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
14773 if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
14774 NavUpdateCreateWrappingRequest();
14775}
14776
14777static void ImGui::NavUpdateCreateWrappingRequest()
14778{
14779 ImGuiContext& g = *GImGui;
14780 ImGuiWindow* window = g.NavWindow;
14781
14782 bool do_forward = false;
14783 ImRect bb_rel = window->NavRectRel[g.NavLayer];
14784 ImGuiDir clip_dir = g.NavMoveDir;
14785
14786 const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
14787 //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
14788 if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14789 {
14790 bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
14791 if (move_flags & ImGuiNavMoveFlags_WrapX)
14792 {
14793 bb_rel.TranslateY(dy: -bb_rel.GetHeight()); // Previous row
14794 clip_dir = ImGuiDir_Up;
14795 }
14796 do_forward = true;
14797 }
14798 if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
14799 {
14800 bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
14801 if (move_flags & ImGuiNavMoveFlags_WrapX)
14802 {
14803 bb_rel.TranslateY(dy: +bb_rel.GetHeight()); // Next row
14804 clip_dir = ImGuiDir_Down;
14805 }
14806 do_forward = true;
14807 }
14808 if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14809 {
14810 bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
14811 if (move_flags & ImGuiNavMoveFlags_WrapY)
14812 {
14813 bb_rel.TranslateX(dx: -bb_rel.GetWidth()); // Previous column
14814 clip_dir = ImGuiDir_Left;
14815 }
14816 do_forward = true;
14817 }
14818 if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
14819 {
14820 bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
14821 if (move_flags & ImGuiNavMoveFlags_WrapY)
14822 {
14823 bb_rel.TranslateX(dx: +bb_rel.GetWidth()); // Next column
14824 clip_dir = ImGuiDir_Right;
14825 }
14826 do_forward = true;
14827 }
14828 if (!do_forward)
14829 return;
14830 window->NavRectRel[g.NavLayer] = bb_rel;
14831 NavClearPreferredPosForAxis(axis: ImGuiAxis_X);
14832 NavClearPreferredPosForAxis(axis: ImGuiAxis_Y);
14833 NavMoveRequestForward(move_dir: g.NavMoveDir, clip_dir, move_flags, scroll_flags: g.NavMoveScrollFlags);
14834}
14835
14836// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
14837// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
14838// If you want a window to never be focused, you may use the e.g. NoInputs flag.
14839bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
14840{
14841 return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
14842}
14843
14844static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
14845{
14846 ImGuiContext& g = *GImGui;
14847 for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
14848 if (ImGui::IsWindowNavFocusable(window: g.WindowsFocusOrder[i]))
14849 return g.WindowsFocusOrder[i];
14850 return NULL;
14851}
14852
14853static void NavUpdateWindowingTarget(int focus_change_dir)
14854{
14855 ImGuiContext& g = *GImGui;
14856 IM_ASSERT(g.NavWindowingTarget);
14857 if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
14858 return;
14859
14860 const int i_current = ImGui::FindWindowFocusIndex(window: g.NavWindowingTarget);
14861 ImGuiWindow* window_target = FindWindowNavFocusable(i_start: i_current + focus_change_dir, i_stop: -INT_MAX, dir: focus_change_dir);
14862 if (!window_target)
14863 window_target = FindWindowNavFocusable(i_start: (focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_stop: i_current, dir: focus_change_dir);
14864 if (window_target) // Don't reset windowing target if there's a single window in the list
14865 {
14866 g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
14867 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14868 }
14869 g.NavWindowingToggleLayer = false;
14870}
14871
14872// Apply focus and close overlay
14873static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window)
14874{
14875 // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ?
14876 // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
14877 ImGuiContext& g = *GImGui;
14878 if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)
14879 {
14880 ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
14881 ClearActiveID();
14882 SetNavCursorVisibleAfterMove();
14883 ClosePopupsOverWindow(ref_window: apply_focus_window, restore_focus_to_window_under_popup: false);
14884 FocusWindow(window: apply_focus_window, flags: ImGuiFocusRequestFlags_RestoreFocusedChild);
14885 IM_ASSERT(g.NavWindow != NULL);
14886 apply_focus_window = g.NavWindow;
14887 if (apply_focus_window->NavLastIds[0] == 0)
14888 NavInitWindow(window: apply_focus_window, force_reinit: false);
14889
14890 // If the window has ONLY a menu layer (no main layer), select it directly
14891 // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
14892 // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
14893 // the target window as already been previewed once.
14894 // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
14895 // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
14896 // won't be valid.
14897 if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
14898 g.NavLayer = ImGuiNavLayer_Menu;
14899
14900 // Request OS level focus
14901 if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
14902 g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
14903 }
14904 g.NavWindowingTarget = NULL;
14905}
14906
14907// Windowing management mode
14908// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
14909// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
14910static void ImGui::NavUpdateWindowing()
14911{
14912 ImGuiContext& g = *GImGui;
14913 ImGuiIO& io = g.IO;
14914
14915 ImGuiWindow* apply_focus_window = NULL;
14916 bool apply_toggle_layer = false;
14917
14918 ImGuiWindow* modal_window = GetTopMostPopupModal();
14919 bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
14920 if (!allow_windowing)
14921 g.NavWindowingTarget = NULL;
14922
14923 // Fade out
14924 if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
14925 {
14926 g.NavWindowingHighlightAlpha = ImMax(lhs: g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, rhs: 0.0f);
14927 if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
14928 g.NavWindowingTargetAnim = NULL;
14929 }
14930
14931 // Start CTRL+Tab or Square+L/R window selection
14932 // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
14933 const ImGuiID owner_id = ImHashStr(data_p: "##NavUpdateWindowing");
14934 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
14935 const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
14936 const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(key_chord: g.ConfigNavWindowingKeyNext, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14937 const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(key_chord: g.ConfigNavWindowingKeyPrev, flags: ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
14938 const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, flags: ImGuiInputFlags_RouteAlways, owner_id);
14939 const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad;
14940 const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
14941 bool just_started_windowing_from_null_focus = false;
14942 if (start_toggling_with_gamepad)
14943 {
14944 g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer
14945 g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu;
14946 g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad;
14947 }
14948 if (start_windowing_with_gamepad || start_windowing_with_keyboard)
14949 if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(i_start: g.WindowsFocusOrder.Size - 1, i_stop: -INT_MAX, dir: -1))
14950 {
14951 if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad)
14952 g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
14953 g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
14954 g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
14955 g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
14956 if (g.NavWindow == NULL)
14957 just_started_windowing_from_null_focus = true;
14958
14959 // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
14960 if (keyboard_next_window || keyboard_prev_window)
14961 SetKeyOwnersForKeyChord(key_chord: (g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
14962 }
14963
14964 // Gamepad update
14965 if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad)
14966 {
14967 if (g.NavWindowingTarget != NULL)
14968 {
14969 // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise
14970 // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast.
14971 g.NavWindowingTimer += io.